APS.NET获取用户端真实IP
APS.NET获取用户端真实IP
ASP.NET的Request自带一个获取用户端IP的属性 Request.UserHostAddress,但通过UserHostAddress获取的IP地址并不能保证真实、准确,并且上客户端使用了代理怎么办?
if (Request.ServerVariables["REMOTE_ADDR"] != null)//发出请求的远程主机的IP地址
{
this.IPAddress = Request.ServerVariables["REMOTE_ADDR"].ToString();
}
else
{
if (Request.ServerVariables["HTTP_VIA"] != null)//判断是否设置代理,若使用了代理
{
if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)//获取代理服务器的IP
{
this.IPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else
{
this.IPAddress = Request.UserHostAddress
}
}
else
{
this.IPAddress = Request.UserHostAddress;
}
}
使用上述代码,可以保证准确的获取到客户端IP地址。
ASP.NET的Request自带一个获取用户端IP的属性 Request.UserHostAddress,但通过UserHostAddress获取的IP地址并不能保证真实、准确,并且上客户端使用了代理怎么办?
if (Request.ServerVariables["REMOTE_ADDR"] != null)//发出请求的远程主机的IP地址
{
this.IPAddress = Request.ServerVariables["REMOTE_ADDR"].ToString();
}
else
{
if (Request.ServerVariables["HTTP_VIA"] != null)//判断是否设置代理,若使用了代理
{
if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)//获取代理服务器的IP
{
this.IPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else
{
this.IPAddress = Request.UserHostAddress
}
}
else
{
this.IPAddress = Request.UserHostAddress;
}
}
使用上述代码,可以保证准确的获取到客户端IP地址。
浙公网安备 33010602011771号