使用反向代理時,如何獲取訪問客戶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 };
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM