使用反向代理时,如何获取访问客户IP的地址

转自:https://www.cnblogs.com/mypath/articles/5239687.html

https://imququ.com/post/x-forwarded-for-header-in-http.html

一般来说,X-Forwarded-For是用于记录代理信息的,每经过一级代理(匿名代理除外),代理服务器都会把这次请求的来源IP追加在X-Forwarded-For中

来自4.4.4.4的一个请求,header包含这样一行

X-Forwarded-For: 1.1.1.1, 2.2.2.2, 3.3.3.3

代表 请求由1.1.1.1发出,经过三层代理,第一层是2.2.2.2,第二层是3.3.3.3,而本次请求的来源IP4.4.4.4是第三层代理

 

实际操作:

首先是在使用 nginx 中,需要加入 X-Forwarded-For 配置,当然要是自己换成别的头也可以,只不过这个比较标准:

复制代码
server {
    listen       80;
    
    server_name  some.test.com;

    location / {
        proxy_pass http://172.26.190.212:7003;
        proxy_set_header X_Real_IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_connect_timeout       600;
        proxy_send_timeout          600;
        proxy_read_timeout          600;
        send_timeout                600;
    }
}
复制代码

 

然后在 asp.net core 中,就可对其进行读取了,以下是测试代码:

复制代码
public ActionResult<object> RemoteIpTest()
{
    var request_host = Request.Host.Host + ":" + Request.Host.Port;
    var remoteIp = Request.HttpContext.Connection.RemoteIpAddress.ToString() + ":" + Request.HttpContext.Connection.RemotePort;
    var localIp = Request.HttpContext.Connection.LocalIpAddress.ToString() + ":" + Request.HttpContext.Connection.LocalPort;

    var x_forwarded_for = new StringValues();
    var x_forwarded_remote_ip = "";
    if (Request.Headers.ContainsKey("X-Forwarded-For"))
    {
        x_forwarded_for = Request.Headers["X-Forwarded-For"];
        if (x_forwarded_for.Any())
        {
            var ip_list = x_forwarded_for.Last().Split(',', StringSplitOptions.RemoveEmptyEntries);
            if (ip_list.Any())
            {
                x_forwarded_remote_ip = ip_list.First().Trim();
            }
        }
    }

    var x_real_ip = new StringValues();
    if (Request.Headers.ContainsKey("X_Real_IP"))
    {
        x_real_ip = Request.Headers["X_Real_IP"];
    }

    return new { request_host, remoteIp, localIp, x_forwarded_remote_ip, x_forwarded_for, x_real_ip };
}
复制代码
posted @   不是豆豆  阅读(969)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
友情链接:迷途


点击右上角即可分享
微信分享提示