I want to get the client ip when the user submit a form in my site.
I try to use that command: Request.UserHostAddress
but I get instead of the ip: ::1
What should I do?
Thank you!
I want to get the client ip when the user submit a form in my site.
I try to use that command: Request.UserHostAddress
but I get instead of the ip: ::1
What should I do?
Thank you!
That's because you're testing locally. ::1
is the IPv6 equivalent to 127.0.0.1
.
::1
is the same as localhost
in ASP.NET you can do this to get the user IP Address
public static string GetUserIpAddress()
{
string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (ip == "::1") ip = "127.0.0.1"; // localhost
}
return ip;
}
You can use REMOTE_ADDR, but it might not work if you are accessing the site locally, it will show local host. Below code will help you
string clientIp = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if( !string.IsNullOrEmpty(clientIp) )
{
string[] forwardedIps = clientIp.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries );
clientIp = forwardedIps[forwardedIps.Length - 1];
}
else {
clientIp = context.Request.ServerVariables["REMOTE_ADDR"];
}