0

I've tried various ways to get the IP address such as mine when visiting a .aspx page. I'm connected through a AT&T cellular hotspot device and I get an IP address which is incorrect. If I google "whats my IP address" google gets it right. I know this because I was trying to get access to something through my firewall which I needed my IP address for and it wasn't working. I verified Google's was in fact correct. But why are they different? I've browsed various resources on the web and some get what I return in .NET and some get what Google is showing. Here is the code I'm using which is not returning the correct IP address.

protected string GetIPAddress()
{
    System.Web.HttpContext context = System.Web.HttpContext.Current; 
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (!string.IsNullOrEmpty(ipAddress))
    {
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
        {
            return addresses[0];
        }
    }

    return context.Request.ServerVariables["REMOTE_ADDR"];
}

I have also tried simply httpContext.Current.UserHostAddress which also returns the incorrect IP address.

Neal
  • 9,487
  • 15
  • 58
  • 101
  • Is the site by any chance going through a service such as Cloudflare? – luly Jun 07 '17 at 01:48
  • Possible duplicate of [How to get the public IP address of a user in C#](https://stackoverflow.com/questions/19285957/how-to-get-the-public-ip-address-of-a-user-in-c-sharp) – Alexander Jun 07 '17 at 02:04
  • Any chance you run your server on the same network as client? IP you observe may help to diagnose the issue - at least first part of IPv4 – Alexei Levenkov Jun 07 '17 at 02:45
  • The servers are my own, not hosted through anyone else. Windows Server 2012 R2 behind a firewall but no proxy or anything that changes IP addresses. This is not a duplicate, the code is the same but it is not returning the correct IP address for me hitting my site but Google does show the correct IP per my post. I am not at the same location as the servers, just connecting through my cellular hotspot. – Neal Jun 07 '17 at 12:11

0 Answers0