[英]Get Client Ip while submit a form. (ASP.net C#)
I want to get the client ip when the user submit a form in my site. 当用户在我的站点中提交表单时,我想获取客户端IP。 I try to use that command:
Request.UserHostAddress
我尝试使用该命令:
Request.UserHostAddress
but I get instead of the ip: ::1
但是我得到的不是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
是等效于127.0.0.1
的IPv6。
::1
is the same as localhost
::1
与localhost
相同
in ASP.NET you can do this to get the user IP Address 在ASP.NET中,您可以执行此操作以获取用户IP地址
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. 您可以使用REMOTE_ADDR,但如果您在本地访问该站点,则可能无法使用,它将显示本地主机。 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"];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.