I want to try to check the IP using ServerVariable

2019-03-04 13:26发布

问题:

I want to try testing the current ip address to find current country

so i try this code... HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

but it is always return 127.0.0.1'

Is there any other code that i can get my ip address on internet like 61.90.25.10 instead of the local one.

回答1:

HttpContext.Current.Request.UserHostAddress;

or

HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

To get the IP address of the machine and not the proxy use the following code

HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

But as your using this application offline you will always receive the IP address of your PC because that’s the IP the server will see in another word your not going outside your router and connecting back on the server so your external ip is not been used:

If you test your application on running server online and try to print out:

Response.Write("IP Address:");
Response.Write("IP: " + HttpContext.Current.Request.UserHostAddress);
Response.Write("IP1: " + HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
Response.Write("IP2: " + HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);

You will see the public ip you have, take care if your using reverse proxy before reaching your PC like cloudflare Make sure to use the HTTP_X_FORWARDED_FOR Otherwise you can use the remote_addr or userhostaddress.