-1

I need to get the user's local IP for my ASP.NET application and I'm using this method:

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"];
}

However, when I publish my website I always get 192.168.2.1 no matter where the user is opening the website from.

Does anyone know how to solve this issue?

  • 2
    `192.168.2.1` That's probably the router gateway. Is your server behind a router? – Alvin Wong Nov 01 '12 at 09:15
  • 1
    I need to check if the user opened the site from a certain range of IPs or not, but I cannot do this since I'm always getting 192.168.2.1 @AlvinWong –  Nov 01 '12 at 09:17
  • The current answers sort of prove a point made many times here - always post your relevant code, regardless of if it comes from a previous SO answer. Don't expect people to follow links to anywhere. =) – J. Steen Nov 01 '12 at 09:30
  • 1
    suggestion taken, post edited @J.Steen –  Nov 01 '12 at 09:34
  • The server is behind a router which uses port forwarding, so the connection is always to the router and NAT-ed to your server, so `REMOTE_ADDR` won't work. I think that's why `HTTP_X_FORWARDED_FOR` won't work either. – Alvin Wong Nov 01 '12 at 09:49
  • Then what can I use alternatively? For intance, http://jsonip.appspot.com/ works fine, but I will try to prevent user to connect to internet, but access it only locally, so he cannot open that site. @AlvinWong –  Nov 01 '12 at 09:51

2 Answers2

0

Some network devices make use of the X-forwarded-for header. You should check if the requests hitting your application have this header.

Greg B
  • 14,597
  • 18
  • 87
  • 141
0

You can get the client's IP address from HTTP_X_FORWARDED_FOR or REMOTE_ADDR.

var ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (string.IsNullOrEmpty(ipAddress ))
{
    ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}

return ipAddress;
Ekk
  • 5,627
  • 19
  • 27
  • 1
    I tried exactly the same, but I always get 192.168.2.1 no matter where the user is opening the website from. –  Nov 01 '12 at 09:29
  • ... as OP already does, if he uses the code in the linked answer. – J. Steen Nov 01 '12 at 09:29