I'm developing an ASP.NET project and I need to determine the client's IP address.
Currently, the following code on our production server
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
returns an IP address that is in the same subnet as the production server's IP address (i.e., not solving my problem as it's not the client's IP address).
However, on our test server, that same line of code returns the client's IP address (the desired result). Anyone have an idea why?
I've tried using the above line of code subbing in the following values, all of which return null or an empty string:
"HTTP_X_COMING_FROM"
"HTTP_X_FORWARDED_FOR"
"HTTP_X_FORWARDED"
"HTTP_X_REAL_IP"
"HTTP_VIA"
"HTTP_COMING_FROM"
"HTTP_FORWARDED_FOR"
"HTTP_FORWARDED"
"HTTP_FROM"
"HTTP_PROXY_CONNECTION"
"CLIENT_IP"
"FORWARDED"
As an alternative, I found the following code that does return an array of IP and contains the client's IP address (at index 4):
string strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
string ip = addr[4] != null ? addr[4].ToString() : "";
While debugging, I noticed that the IPAddress objects in addr have either (A) Address errors if it's an IPv6 address, or (B) ScopeId errors if it's an IPv4 address. These errors don't seem to be an issue, but I'm not sure if they'll matter once in production.
Is there a better way to get the client's IP address than the way I have here?