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?

2
  • 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. Jul 2, 2019 at 17:22
  • This may help stackoverflow.com/questions/735350/…
    – VDWWD
    Jul 2, 2019 at 18:04

2 Answers 2

0

Gets the HttpRequestBase object for the current HTTP request.

Request.UserHostAddress

you can get a client's IP address.

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.

1
  • Using HTTP_X_FORWARDED_FOR consistently returns an empty string. And REMOTE_ADDR returns the incorrect IP address of the production server.
    – beh1
    Jul 3, 2019 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.