0

I am trying to fetch the IP address using this:-

    protected void Page_Load(object sender, EventArgs e)
    {
        string ClientIP;
        ClientIP = HttpContext.Current.Request.UserHostAddress;
        Label1.Text = ClientIP;
    }

This code outputs 127.0.0.1.

And the code below displays nothing!

    string ClientIP;
    ClientIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    Label1.Text = ClientIP;

How do I fetch the IP address? The REAL IP address of a user?

[EDIT]

I don't want EXACT location BTW. I need to know the country and then redirect the user to a webpage accordingly.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Serenity
  • 4,968
  • 19
  • 65
  • 104
  • 2
    Keep in mind that NAT, proxies and so forth will obscure the results. – Brian Rasmussen Sep 10 '10 at 08:45
  • yep I know..just need to know the country – Serenity Sep 10 '10 at 08:48
  • 2
    I've had a proxy in the hosting centre that prevented getting the user-IP, so then you won't even get country data. – Hans Kesting Sep 10 '10 at 08:53
  • 1
    If you want to display a page in the "correct language", then *country* is not enough - there are multilingual countries (or foreigners living there). Checking UserLanguages is then better. – Hans Kesting Sep 10 '10 at 08:55
  • HTTP_ACCEPT_LANGUAGE is the server variable to know about browser's preferred language..right ? I am confused now..preferred language can be set as whatever in browser..isn't it ? So how can we be sure about the country ? Won't fetching IP address be the correct way to know about the country of a visitor?? – Serenity Sep 10 '10 at 10:35

2 Answers2

3
Request.Params["REMOTE_ADDR"]
Julius A
  • 38,062
  • 26
  • 74
  • 96
2

Using System.Net, try this -

// Then using host name, get the IP address list..
          IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
          IPAddress [] addr = ipEntry.AddressList;

          for (int i = 0; i < addr.Length; i++)
          {
              Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString ());
          }
Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103