欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

获取用户真实ip

程序员文章站 2022-03-13 17:03:05
public static string GetRealIP() { string result = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"]; if(string.IsNullOrEmpty(result)){ res ......

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?)$");
}