1

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?

beh1
  • 139
  • 1
  • 2
  • 15
  • Does your production traffic go through a load balancer? It may replace `REMOTE_ADDR` with the address of the load balancer. The load balancer may need to be configured to add the original IP address to `HTTP_X_FORWARDED_FOR`. – Scott Hannen Jul 02 '19 at 17:22
  • This may help https://stackoverflow.com/questions/735350/how-to-get-a-users-client-ip-address-in-asp-net – VDWWD Jul 02 '19 at 18:04

2 Answers2

0

Gets the HttpRequestBase object for the current HTTP request.

Request.UserHostAddress

you can get a client's IP address.

zaman
  • 145
  • 7
0

You can use this function to get ip address.

    private string GetUserIP()
    {
        string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (!string.IsNullOrEmpty(ipList))
        {

            var ips= ipList.Split(',');
            return ips[ips.Length - 1];
        }

        return Request.ServerVariables["REMOTE_ADDR"];
    }

NOTE: HTTP_X_FORWARDED_FOR header may have multiple IP's. The correct IP is the last one.

Kalpesh Bhadra
  • 406
  • 1
  • 6
  • 17
  • Using HTTP_X_FORWARDED_FOR consistently returns an empty string. And REMOTE_ADDR returns the incorrect IP address of the production server. – beh1 Jul 03 '19 at 15:56