Read X-Forwarded-For header

后端 未结 4 2011
天涯浪人
天涯浪人 2020-12-10 11:02

I want to read the value of the X-Forwarded-For header value in a request.

I\'ve tried

HttpContext.Current.Request.Headers[\"X-Forwarded-For\"].Split         


        
相关标签:
4条回答
  • 2020-12-10 11:25

    If helps, this is a simple way of getting the user's IP address, considering the X_FORWARDED_FOR header

    var forwardedFor = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    
    var userIpAddress = String.IsNullOrWhiteSpace(forwardedFor) ?
        Request.ServerVariables["REMOTE_ADDR"] : forwardedFor.Split(',').Select(s => s.Trim()).FirstOrDefault();
    
    0 讨论(0)
  • 2020-12-10 11:33

    Don't forget that X-Forwarded-For can contain whatever client writes there. It can contain XSS or SQL-injection inside.

    0 讨论(0)
  • 2020-12-10 11:34

    The format that you get in return is client1, proxy1, proxy2

    So you split it with the comma, and get the first to see the ip of your client.

    0 讨论(0)
  • 2020-12-10 11:38

    Sometimes the first may contain one of the local (private) reserved addresses which is not useful. Also the first position(s) are open to to spoofing.

    Update - April 2018: Sampling the cases of a live production website where the first address is local (private) indicates some configuration issue on the end user's network or his ISP. The cases are occurring only rarely (<1%) and consistently for the same end users.

    The answer below suggests walking from right to left until you hit a public address. Not sure anyone actually does this but it points out the issue.

    https://husobee.github.io/golang/ip-address/2015/12/17/remote-ip-go.html

    0 讨论(0)
提交回复
热议问题