#region 获取web客户端ip
///
/// 获取web客户端ip
///
///
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;
}
#endregion
///
/// 取得客户端真实IP地址
///
public static string IPAddress
{
get
{
string result = string.Empty;
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(result))
{
//可能有代理
if (result.IndexOf(".") != -1) //没有“.”肯定是非IPv4格式
{
if (result.IndexOf(",") != -1) { return result; }
else if (IsIPAddress(result)) { return result; }//代理即是IP格式
else { result = null; }//代理中的内容 非IP,取IP
}
else { result = null; }
}
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.UserHostAddress;
}
return result;
}
}
应该可以直接取到地址的。REMOTE_ADDR, REMOTE_HOST。环境变量。