1. 程式人生 > >獲取用戶真實ip

獲取用戶真實ip

name regex htm get tex arc www. eal ive

原文:獲取用戶真實ip

public static string GetRealIP()
{
string result = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
if(string.IsNullOrEmpty(result)){
result = System.Web.HttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"];
}
if(string.IsNullOrEmpty(result)){
result = System.Web.HttpContext.Current.Request.Headers["HTTP_VIA"];
}
if(string.IsNullOrEmpty(result)){
result = System.Web.HttpContext.Current.Request.Headers["REMOTE_ADDR"];
}
if(string.IsNullOrEmpty(result)||!IsIp(result)){
result = "127.0.0.1";
}
return result;
}

/// <summary>
///是否為ip
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool IsIp(string ip)
{
return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}

獲取用戶真實ip