UserHostAddress gives wrong IPs

后端 未结 7 1634
[愿得一人]
[愿得一人] 2021-01-02 03:26

I collect statistics on IP addresses from where users visit my site and I have noticed what there are only two IP addresses presented, 172.16.16.1 and 172.16.16.248. The pro

7条回答
  •  一向
    一向 (楼主)
    2021-01-02 03:42

    Building on Dave Anderson's answer, here is a snippet that takes into account a chain of reverse proxies.

    string forwardedFor = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    
    string ipStr = string.IsNullOrWhiteSpace(forwardedFor) 
                       ? Request.ServerVariables["REMOTE_ADDR"] 
                       : forwardedFor.Split(',').Select(s => s.Trim()).First();
    

提交回复
热议问题