110,533
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 获取web客户端ip
/// </summary>
/// <returns></returns>
public static string GetWebClientIp()
{
string userIP = "未获取用户IP";
try
{
if (System.Web.HttpContext.Current == null
|| System.Web.HttpContext.Current.Request == null
|| System.Web.HttpContext.Current.Request.ServerVariables == null)
return "";
string CustomerIP = "";
//CDN加速后取到的IP simone 090805
CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
if (!string.IsNullOrEmpty(CustomerIP))
{
return CustomerIP;
}
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!String.IsNullOrEmpty(CustomerIP))
return CustomerIP;
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
{
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (CustomerIP == null)
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
else
{
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (string.Compare(CustomerIP, "unknown", true) == 0)
return System.Web.HttpContext.Current.Request.UserHostAddress;
return CustomerIP;
}
catch { }
return userIP;
}
/// <summary>
/// 获取本机IP地址
/// </summary>
/// <returns></returns>
public static string GetIpAddress()
{
string hostName = Dns.GetHostName(); //获取本机名
IPHostEntry localhost = Dns.GetHostByName(hostName); //方法已过期,可以获取IPv4的地址
IPAddress localaddr = localhost.AddressList[0];
return localaddr.ToString();
}
一个获取客户端的,一个获取本机的
using System.Net;
IPAddress[] ips= Dns.GetHostAddresses("www.baidu.com");
string ip = ips[0].ToString();
string ip=HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
string ip = Request.UserHostAddress;
string ip=HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
[/quote]
前者是请求的地址,后者是如果请求来自代理服务器,那么所代理的机器的地址
用前一个会使得使用代理访问的被视作同一个地址,使用后者,后者可以伪造。