I am running a ASp.Net mvc app in localhost - dev server given with visual studio. I want to get the IP address. I tried
Request.UserHostAddress
and
Request.ServerVariables("REMOTE_ADDR")
In both cases, I am getting ::1 as the result. What is it? Why am I getting it? How can I get 127.0.0.1 or 192.168.1.xxx?
You are getting a valid IP Address. ::1
is local_host in IPv6. (underscore used in local_host to stop SO from thinking it was some sort of bad text)
What you're seeing when calling 'localhost' is valid. ::1 is the IPv6 loopback address. Equivalent to 127.0.0.1 for IPv4.
Instead of calling:
http://localhost/...
Call:
http://{machinename}/...
-or-
http://127.0.0.1/...
-or-
http://192.168.1.XXX/...
[Replace {machinename} with your machine's computer name. Replace XXX with your computers IP address.]
Anyone calling into your machine to the MVC app will have there valid IP address as a result. If the client is a IPv6 host it will save there IPv6 IP address. If the client is a IPv4 host it will save there IPv4 IP address.
If you always want to save a IPv4 address take a look at this article on how they accomplished it with a simple class http://www.4guysfromrolla.com/articles/071807-1.aspx. You should be able to take there example and build a quick helper method to accomplish this.
Request.Params["REMOTE_ADDR"]
instead of Request.ServerVariables("REMOTE_ADDR")
If you want localhost return 127.0.0.1, maybe you need to change your "hosts" file. You can find it in "%systemdrive%\Windows\System32\drivers\etc"
It works for me, now I get 127.0.0.1 with "Request.ServerVariables["REMOTE_ADDR"]". I uncomment 127.0.0.1 (remove #).
Here you can find default hosts file http://support.microsoft.com/kb/972034
My file
# localhost name resolution is handled within DNS itself.
127.0.0.1 localhost
# ::1 localhost
below code i have used for finding ip
public static string GetIp()
{
var Request = HttpContext.Current.Request;
try
{
Console.WriteLine(string.Join("|", new List<object> {
Request.UserHostAddress,
Request.Headers["X-Forwarded-For"],
Request.Headers["REMOTE_ADDR"]
})
);
var ip = Request.UserHostAddress;
if (Request.Headers["X-Forwarded-For"] != null)
{
ip = Request.Headers["X-Forwarded-For"];
Console.WriteLine(ip + "|X-Forwarded-For");
}
else if (Request.Headers["REMOTE_ADDR"] != null)
{
ip = Request.Headers["REMOTE_ADDR"];
Console.WriteLine(ip + "|REMOTE_ADDR");
}
return ip;
}
catch (Exception ex)
{
Log.WriteInfo("Message :" + ex.Message + "<br/>" + Environment.NewLine +
"StackTrace :" + ex.StackTrace);
}
return null;
}
来源:https://stackoverflow.com/questions/5795534/why-am-i-getting-1-as-ip-address-in-asp-net-and-how-to-get-the-proper-ip-add