.net 获取客户端真实ip

发布时间 2023-12-05 12:14:54作者: IWing

Nginx 如何设置


情况1

在只有1层nginx代理的情况下,设置nginx配置“proxy_set_header X-Forwarded-For $remote_addr;”。(此时$remote_addr获取的是用户的真是ip)

情况2

在有多层反向代理的情况下,

1)设置“最外层”nginx配置和情况1一样“proxy_set_header X-Forwarded-For $remote_addr;”。

2)除了“最外层”之外的nginx配置“proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;”。

注意
如果你的 nginx 使用了 http_realip_module 模块,那么必须再配置一下受信任的cdn、nginx节点,否则 nginx 会认为X-Forwarded-For的内容都是可靠的,无法识别别人伪造的 X-Forwarded-For 头。

		proxy_pass   http://8.2.158.1:11029;
	    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		set_real_ip_from	8.168.31.5;
		set_real_ip_from	8.168.31.6;
		set_real_ip_from	16.18.22.0/24;

8.168.31.5、8.168.31.6、16.18.22.*网段 是cdn的ip地址,告诉 nginx 可以信任

Asp.Net 获取客户端真实ip


编写一个静态方法:

        public static string GetRemoteIpAddress(HttpContext httpContext, string[] trustXForwardedFor)
        {
            var remoteIpAddr = httpContext.Connection.RemoteIpAddress.ToString();
            if (trustXForwardedFor != null && trustXForwardedFor.Length > 0 && httpContext.Request.Headers.TryGetValue("X-Forwarded-For", out StringValues x_for))
            {
                var x_forArr = x_for.ToString().Split(',').Select(m => m.Trim()).Where(m => m.Length > 0).ToArray();
                if (trustXForwardedFor.Contains(remoteIpAddr))
                {
                    for (int i = x_forArr.Length - 1; i >= 0; i--)
                    {
                        var ip = x_forArr[i];
                        if (trustXForwardedFor.Contains(ip) == false)
                            return ip;
                    }
                }
                else
                {
                    return remoteIpAddr;
                }
            }

            return remoteIpAddr;
        }

然后在controller内部调用:

GetRemoteIpAddress(this.HttpContext, new string[] { "127.0.0.1", "::ffff:127.0.0.1", "172.19.149.142" })

"127.0.0.1", "::ffff:127.0.0.1", "172.19.149.142" 这是指定3个被排除的反向代理以及cdn的ip , 如果不传这些ip,那就表示服务器那边没有部署nginx这类型的反向代理服务,也没有使用cdn。

JMSFramework 微服务获取客户端真实ip


JMS 的 controller 自身就包含 GetRemoteIpAddress 方法,在controller 里面直接调用即可。

this.GetRemoteIpAddress(new string[] { "127.0.0.1", "::ffff:127.0.0.1", "172.19.149.142" });