I can't find a question or post specific to Azure for this, and I'm not sure what's different in the environment in Azure versus my testing environments that would cause this.
I've tried a few methods to get this to work but I'm not coming right. Please note this isn't Webapi, so using the HttpRequestMessage, as far as I know, is not going to work either.
Here's what I've tried so far:
Method 1:
string ipAddress = "";
IPHostEntry Host = default(IPHostEntry);
Host = Dns.GetHostEntry(System.Environment.MachineName);
ipAddress = Host.AddressList.SingleOrDefault(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).MapToIPv4().ToString();
Method 2:
string userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(userIP))
{
userIP = Request.ServerVariables["REMOTE_ADDR"];
}
return userIP;
Thanks in advance.
Read the value transported in this header:
x-forwarded-for: "91.23.44.24:52623"
Note there's a source port number trailing the IP address, so parse accordingly.
Also, as #NicoD correctly points out, the header in question may contain an array of proxy servers the request traversed. For example:
x-forwarded-for: "91.23.44.24:52623, 91.23.44.155"
Syntax
X-Forwarded-For: <client>, <proxy1>, <proxy2>
<client> The client IP address
<proxy1>, <proxy2> If a request goes through multiple proxies, the IP addresses of each successive proxy is listed. This means, the right-most IP address is the IP address of the most recent proxy and the left-most IP address is the IP address of the originating client.
What about that glaring port number you ask?
From https://www.rfc-editor.org/rfc/rfc7239:
5.2. Forwarded For
[...] this parameter MAY instead contain an IP
address (and, potentially, a port number).
All client requests are terminated in the frontend layer and proxied via Application Request Routing to your web worker (hosting the MVC5 application).
Related
My application is sending reports to another application (which maintains a database of reports) on the network with simple IPv4 addresses. I can construct a valid IPAddress in two ways:
string address = "200.1.2.41";
IPAddress ip1 = IPAddress.Parse(address);
IPAddress ip2 = (Dns.GetHostEntry(address)).AddressList[0];
If address represents an IP that is reachable, both methods are quick (though IPAddress.Parse is quickest). But if address is not reachable (eg. the server is off or the user has entered the wrong IP in Settings) then Parse is lightning quick...but Dns.GetHostEntry hangs for up to 9s.
I did a parameter-by-parameter check and the final variables ip1 and ip2 are identical. Given that Parse is always quick, and that I'm using standard four-octet IPv4 addresses only, is there any compelling reason to use the Dns.GetHostEntry method? Might I need Dns.GetHostEntry if I switch to IPv6 or named hosts like FOOD.HALL.01 in future?
If you just want get an instance of IPAddress for your IP address string representation, than yes, using the DNS for that purpose is absolute overkill.
All sorts of timeouts, latencies, etc. are absolute expected. At least compared to the purely local parsing and disecting of the string representation that happens in IPAddress.Parse(). What that does is, ask the DNS server to resolve the IP address string into a hostname "entry". From that you get the IP address back that you knew all along (albeit as string and not IPAddress).
Now, if you want to be able to "convert" host names into IP addresses in the future, then yes, you need to go via DNS.
But you could always do it in that manner (conceptually):
// First see if it is a valid IP address rep - fast.
IPAddress ip;
if (!IPAddress.TryParse(address, out ip))
{
// See if it is a hostname - slower.
ip = Dns.GetHostEntry(address).AddressList[0];
}
And yes, IPAddress.TryParse() (or Parse()) can handle IPv4 and IPv6 addresses.
I have simple HttpClient which works perfectly when using ipv4/fqdb/host names (please see below for code snippet). However same code doesn't work, the moment I tried to use ipv6 address to connect to server. I probably need to change some configuration settings and able to define uri with ipv6 address.
I have looked at msdn and it has the following statement:
If the host name is an IPv6 address, the canonical IPv6 address is used. ScopeId and other optional IPv6 data are removed - http://msdn.microsoft.com/en-us/library/system.uri.aspx
Not sure what it means, will try to figure it out.
What can I try to fix the problem?
Looks like I need to keep ipv6 address in square brackets [enclose it '[]']
http://[fe08::83e7:71e8:1364:0dff%19]:58703/ and looks like everything is working OK now. thanks to How to include ipv6 addresses with (or without) zone indexes in uri for .net remoting?
Code:
this.Client = new HttpClient();
**//below line throws UriFormatException (Invalid URI: Invalid port specified)**
this.Client.BaseAddress = new Uri(http://fe08::83e7:71e8:1364:0dff%19:58703/);
this.Client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/xml"));
//whereas below code works, when ipv4/fqdn is used...
this.Client = new HttpClient();
this.Client.BaseAddress = new Uri(10.0.0.1:58501);
this.Client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/xml"));
You need to specify the URI in the format specified by RFC 2732. Basically, wrap the actual IPv6 address in square brackets.
The ScopeId you mention is the "%19" part of your example URI. The very high-level, hand-waving description is "it basically identifies which network interface the address corresponds to on the local machine." This Super User post and this MSDN article have reasonably understandable detailed descriptions of what it actually means, if you're interested.
In your case, all you really need to know is that it's meaningless/misleading to include it in a BaseAddress property because the value is only meaningful for your specific machine. It doesn't make sense to send it out in HTTP responses since the value has no meaning for remote clients. That's why, as the documentation you mention points out, HttpClient won't use it even if you include it in the BaseAddress.
The final updated URI would look like:
this.Client.BaseAddress = new Uri(#"http://[ef08::83e7:71e8:1364:0dff]:54502/");
I think I may be in a situation where the answer is this is not possible but in case not here goes...
I have written an ASP .NET MVC 3 application and I am using the Request.UserHostName property and then passing the value that that returns into Dns.GetHostEntry to find out all the possible IPs and the host name for the currently connected client, for example:
var clientAddress = Request.UserHostName;
var entry = Dns.GetHostEntry(clientAddress);
Generally that is fine except I have a case where I get a "host not found" SocketException from the Dns.GetHostEntry call.
The really odd thing is that the address that is returned from the Request.UserHostName property is not the public address or any of the private addresses. To prove this I ran this bit of code on the client machine in question...
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var a in host.Aliases)
{
Console.WriteLine("alias '{0}'", a);
}
foreach (var a in host.AddressList)
{
Console.WriteLine("ip address '{0}'", a);
}
// ...from http://stackoverflow.com/a/2353177/1039947...
String direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
{
using (var stream = new StreamReader(response.GetResponseStream()))
{
direction = stream.ReadToEnd();
}
}
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
Console.WriteLine("Public IP: '{0}'", direction);
It prints three IP addresses (::1, one private and one public) but none of them are the address that is returned from Request.UserHostName.
If I pass in any of the addresses printed from the above test application into the Dns.GetHostEntry method I get a sensible value back.
So, is there any way that I could get from this strange IP address that is not the public nor any of the privates, to one where I could get the host entry for it without an exception (and what is this address)?
By the way, there is no X_FORWARD_FOR header or anything else that I may be able to identify the client with, as far as I can tell, in the HTTP message?
Background to the Question
So it was pointed out (thanks Damien) that if I explained why I am asking this perhaps someone can provide an alternative approach so here is some background...
I have a requirement that the administrator of the application should be allowed to specify in the configuration a single machine that is allowed to view the page - IP address or machine name - I can probably get the machine name requirement removed but even if they specify the IP address in the configuration it will still not match the IP address that is returned from the UserHostName property since they will use the IP address that is returned when they ping the machine name.
My thinking, therefore, was that if I take whatever is sent in the HTTP header and pass that into GetHostEntry then take all the possible results from that (all the IPs and the host name) and see if any of them match the configured value I could say "allow" otherwise "disallow" (I was going to remove the part of the host name before the first dot too, to cover that eventuality). That scheme has been blown out of the water by this situation I have where the IP address is not at all what I would expect.
The host name of the client is not normally known because it is not transmitted at the HTTP level. The server cannot know it. Look at the HTTP requests with Fiddler to see for yourself that there is not a lot of information available to the server (and the client can forge all request contents of course).
Use the UserHostAddress property to get the IP address. That is the most you can reliably find out. Once you have that you can try to reverse the IP to a host name but that is not always possible.
I have a more specific answer to your question. By examining the source code for HttpRequest.UserHostName here, I found that it maps to a IIS server variable named REMOTE_HOST which is described here. The property will return the IP adddress of the client, unless you have configured IIS in the way described, in which case IIS will do a reverse DNS lookup to attempt to return the name associated with the IP.
Make sure you read the Remarks section at Dns.GetHostEntry on the many cases it can (partially) fail:
Remarks
The GetHostEntry method queries a DNS server for the IP
address that is associated with a host name or IP address.
If an empty string is passed as the hostNameOrAddress argument, then this method
returns the IPv4 and IPv6 addresses of the local host.
If the host name could not be found, the SocketException exception is returned
with a value of 11001 (Windows Sockets error WSAHOST_NOT_FOUND). This
exception can be returned if the DNS server does not respond. This
exception can also be returned if the name is not an official host
name or alias, or it cannot be found in the database(s) being queried.
The ArgumentException exception is also returned if the
hostNameOrAddress parameter contains Any or IPv6Any.
The GetHostEntry method assumes that if an IP literal string is passed in the
hostNameOrAddress parameter that the application wants an IPHostEntry
instance returned with all of the properties set. These properties
include the AddressList, Aliases, and HostName. As a result, the
implementation of the GetHostEntry method exhibits the following
behavior when an IP string literal is passed:
The method tries to parse the address. If the hostNameOrAddress parameter contains a legal IP string literal, then the first phase succeeds.
A reverse lookup using the IP address of the IP string literal is attempted to obtain the host name. This result is set as the HostName property.
The host name from this reverse lookup is used again to obtain all the possible
IP addresses associated with the name and set as the AddressList
property.
For an IPv4 string literal, all three steps above may
succeed. But it is possible for a stale DNS record for an IPv4 address
that actually belongs to a different host to be returned. This may
cause step #3 to fail and throw an exception (there is a DNS PTR
record for the IPv4 address, but no DNS A record for the IPv4
address).
For IPv6, step #2 above may fail, since most IPv6
deployments do not register the reverse (PTR) record for an IPv6
address. So this method may return the string IPv6 literal as the
fully-qualified domain (FQDN) host name in the HostName property.
The GetHostAddresses method has different behavior with respect to IP
literals. If step #1 above succeeds (it successfully parses as an IP
address), that address is immediately returned as the result. There is
no attempt at a reverse lookup.
IPv6 addresses are filtered from the results of the GetHostEntry method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty
IPHostEntry instance if only IPv6 results where available for the
hostNameOrAddress.parameter.
The Aliases property of the IPHostEntry instance returned is not populated by this method and will always be empty.
I want my request to go out through a specific IP Addresses. Is there a way to do that in WCF. The explanation of why I need this is a little long winded so i'd rather not get into that.
Here is sample code
string ipAddress = "192.168.0.32";
IService service;
ChannelFactory<IOmlService> factory = new ChannelFactory<IService>(new BasicHttpBinding(), new EndpointAddress("http://" + IPAddress + ":6996/IService"));
service = factory.CreateChannel();
service.Test();
Here is an example scenario to explain exactly what i'm looking for. Let's say I have two IPs on my machine (192.168.0.30 and 192.168.0.31). Both of them can hit 192.168.0.32. If i run this code now, it will hit the IP (.32) from any of my IPs (.30 or .31). How can i force it to go through a specific IP of mine (say .30). Is there any way to do that using WCF?
The answer to the question is that it cannot be done. Here is the answer from a Microsoft MVP
So you want to let the client-side machine proactively select one of the network adpater interface(installed on it) to send out the WCF requests? I'm afraid this is out of WCF's control since WCF only focus on the following addresses:
** when behave as a host, we can choose to bind to a specific hostname/address to listen for client requests
** when behave as a client, we can choose the destination address/hostname to send request to.
Are you trying to make something similar to IP-Sec on the Server so it only accepts request from specific IP addresses?
In this case, you need to implement IEndpointBehavior and IDispatchMessageInspector and:
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
RemoteEndpointMessageProperty remoteAddress =
(OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as
RemoteEndpointMessageProperty);
// validate ip here
return null;
}
It seems to me that your problem should be solved by setting of an additional rote in the routing table. Try do following from the Command Prompt started with administrative rights:
route add 192.168.0.32 mask 255.255.255.255 192.168.175.30
If you want to save the route add -p switch additionally.
How do you get the ipaddress and location of every website vistor of your website through Asp.Net?
Thanks
To get the user's IP use:
Request.UserHostAddress
You can use this webservice to get their geographic location.
http://iplocationtools.com/ip_location_api.php
string VisitorIPAddress = Request.UserHostAddress.ToString();
and based on the ipaddress you can narrow down the location: find the geographical location of a host
Request.UserHostAddress won’t work if you're behind a proxy. Use this code:
public static String GetIPAddress()
{
String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
else
ip = ip.Split(',')[0];
return ip;
}
Note that HTTP_X_FORWARDED_FOR should be used BUT as it can return multiple IP addresses separated by a comma you need to use the Split function. See this page for more info.
Well the following property should give you the IP Address of teh client (or the clients proxy server)
Request.UserHostAddress
As for location, you'd need to use some GeoIP/GeoLocation plugin like MaxMind to figure that out.
http://www.maxmind.com/
To get the IP do:
Request.UserHostAddress
And you can map IP to location using a webservice (slower) or a database (faster) like this:
http://ip-to-country.webhosting.info/node/view/5
It's server technology-agnostic, but I'd recommend piggy-backing on Google's AJAX loader: http://code.google.com/apis/ajax/documentation/#ClientLocation
It's in Javascript and will even give you the person's city/state/country (well, it takes a guess based on IP address). Post it back to the server and it's available to you in ASP.NET or whatever.