Sam Cromer
Sam Cromer

Reputation: 707

System.Web.HttpContext.Current.Request.UserHostAddress;

I am using the following code to obtain the user I.P. address but something strange is happening. I am, receiving the same ip address every time no matter if I am on my desktop or on my iPhone. I am on our network where the web servers live when I hit the page from my desktop but on my iPhone I was not even in the building. I have not run into this issue before, the ip address that I am getting back is an internal one assigned to the web servers.

string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
Response.Write(ip);

Outside of my network I still get the same ip address 172.16.0.22 which is a router address, not our external ip. Is there a way to obtain the external ip address.

Upvotes: 8

Views: 44735

Answers (3)

Sanjay Zalke
Sanjay Zalke

Reputation: 1371

I hope this will be resolved by this time, I ran into same issue. Like you we I knew the IP address was one of the server on the network (Load Balancer).

If your solution is load balanced web servers, then there are high chances that your load balancer is updating the request header information, rerouting through some software load balancer or something.

In case on local testing, update the router configuration to pass the request details. read some router configuration manual, there should be something which will have this setting. :)

Supply your router information, someone will have router/hardware knowledge on this.

I am not a hardware expert, but ask your network administrator to either pass-on the header info as is or at least update "X-Forwarded-For" information. So you can build code to read this information consistently.

Find more information about the traffic routing techniques used in industry and issues here.

Sanjay

Upvotes: 3

maycil
maycil

Reputation: 764

Try this;

if (!String.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"]))
      ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
else
      ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

Request.UserHostAddress return server IP which IIS run on.

Upvotes: 0

DotNetUser
DotNetUser

Reputation: 6612

see this link http://thepcspy.com/read/getting_the_real_ip_of_your_users/

        // Look for a proxy address first
        _ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        // If there is no proxy, get the standard remote address
        if (_ip == null || _ip.ToLower() == "unknown")
            _ip = Request.ServerVariables["REMOTE_ADDR"];

Upvotes: 7

Related Questions