I want to get the ip address whoever is registering in my site. How to do this in ASPNET. I used the following code, but, it is not getting the proper IP Address
string ipaddress = Request.UserHostAddress;
I want to get the ip address whoever is registering in my site. How to do this in ASPNET. I used the following code, but, it is not getting the proper IP Address
string ipaddress = Request.UserHostAddress;
You can use this method to get the IP address of the client machine.
public static String GetIP()
{
String ip =
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;
}
HTTP_X_FORWARDED_FOR should be used BUT it can return multiple IP addresses separated by a comma. See this page.
So you should always check it. I personally use the Split function.
public static String GetIPAddress()
{
String ip =
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
else
ip = ip.Split(',')[0];
return ip;
}
If a client is connecting through a transparent non-anonymous proxy, you can get their address from:
Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
which can return null or "unknown" if the IP can't be obtained that way.
Request.ServerVariables["REMOTE_ADDR"] should be the same as Request.UserHostAddress, either of which can be used if the request is not from a non-anonymous proxy.
However, if the request comes from an anonymous proxy, then it's not possible to directly obtain the IP of the client. That's why they call those proxies anonymous.