X icon indicating copy to clipboard operation
X copied to clipboard

请问HttpServer如何获取访问客户端的IP地址

Open haycun opened this issue 8 months ago • 3 comments

请问HttpServer如何获取访问客户端的IP地址,如果服务前置有网关或防火墙之类的,获取的一直是网关或防火墙地址,如何能获取到如Request.UserHostAddress一样的地址?

haycun avatar Jun 07 '25 16:06 haycun

你说的应该是反向代理,nginx之类。需要在反向代理里面设置,增加http请求头,标明原始请求ip才行。 不仅仅是httpserver,就算是标准asp.net,或者任何其它web框架,都需要这么处理。

nnhy avatar Jun 07 '25 16:06 nnhy

目前遇到的情况是这样的,服务前端有负载均衡,使用Request.UserHostAddress可以获取到客户端的访问IP,使用DefaultHttpContext.Current.Connection.Remote.EndPoint.Address获取到的是内部网关地址

haycun avatar Jun 08 '25 10:06 haycun

期望是在记录日志时能获取到访问客户端的IP地址

haycun avatar Jun 08 '25 10:06 haycun

你可能需要的是这个:


    /// <summary>获取用户主机</summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public static String GetUserHost(this HttpContext context)
    {
        var request = context.Request;

        var str = "";
        if (str.IsNullOrEmpty()) str = request.Headers["X-Remote-Ip"];
        if (str.IsNullOrEmpty()) str = request.Headers["HTTP_X_FORWARDED_FOR"];
        if (str.IsNullOrEmpty()) str = request.Headers["X-Real-IP"];
        if (str.IsNullOrEmpty()) str = request.Headers["X-Forwarded-For"];
        if (str.IsNullOrEmpty()) str = request.Headers["REMOTE_ADDR"];
        //if (str.IsNullOrEmpty()) str = request.Headers["Host"];
        if (str.IsNullOrEmpty())
        {
            var addr = context.Connection?.RemoteIpAddress;
            if (addr != null)
            {
                if (addr.IsIPv4MappedToIPv6) addr = addr.MapToIPv4();
                str = addr + "";
            }
        }

        return str + "";
    }

nnhy avatar Jun 23 '25 14:06 nnhy