net mvc
public static string GetIP(HttpRequestBase request){// 尝试获取 X-Forwarded-For 头string result = request.Headers["X-Forwarded-For"]?.Split(',').FirstOrDefault()?.Trim();if (string.IsNullOrEmpty(result)){// 获取用户的 IP 地址result = request.UserHostAddress;}// 如果获取到的是 "::1" 或者空值,尝试使用主机名if (string.IsNullOrEmpty(result) || result == "::1"){result = request.Url.Host; // 返回主机名}// 如果仍然没有找到有效的 IP 地址,返回默认值return string.IsNullOrEmpty(result) ? "127.0.0.1" : result;}//上面是方法,下面是调用string ipaddress = GetIP(Request);
net core
public static string GetIP(HttpContext? context)
{string result = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();if (string.IsNullOrEmpty(result)){result = context.Connection.RemoteIpAddress?.ToString();}if (string.IsNullOrEmpty(result)){result = context.Request.Host.ToString();}if (string.IsNullOrEmpty(result)){return "127.0.0.1";}return result;
}//上面是方法,下面是调用
GetIP(HttpContext)
这样获取到的地址跟百度上直接搜的ip是一样的