调用: string ip = GetClientIP();
/// <summary>
/// 获取客户端IP
/// </summary>
/// <returns></returns>
public static string GetClientIP()
{
string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.UserHostAddress;
}
if (!IsIP(result))
{
result = "127.0.0.1";
}
return result;
}
public static bool IsIP(string ip)
{
//判断是否为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?)$");
}