但访问者访问站点时,经常需要获取客户的原始IP地址,比如用了Cloudflare,阿里CDN加速等云加速
这个时候,获取原始IP地址方法需要稍作处理
/// <summary>
/// 获得远程客户端IP
/// </summary>
/// <returns></returns>
public static string SiteIP()
{
var request = System.Web.HttpContext.Current.Request;
string ip = string.Empty;
if (!string.IsNullOrEmpty(request["X_FORWARDED_FOR"]))
{
return SiteIPSplit(request["X_FORWARDED_FOR"]);
}
else if (request.ServerVariables["HTTP_VIA"] != null)
{
if (request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null)
{
if (request.ServerVariables["HTTP_CLIENT_IP"] != null)
ip = request.ServerVariables["HTTP_CLIENT_IP"].ToString();
else
if (request.ServerVariables["REMOTE_ADDR"] != null)
ip = request.ServerVariables["REMOTE_ADDR"].ToString();
}
else
ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (request.ServerVariables["REMOTE_ADDR"] != null) ip = request.ServerVariables["REMOTE_ADDR"].ToString();
if (string.IsNullOrEmpty(ip)) ip = request.UserHostAddress;
return ip;
}
public static string SiteIPSplit(string IP)
{
if (IP.IndexOf(",") != -1)
{
string[] ip = IP.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
return ip[0];
}
return IP;
}