开发者

Read X-Forwarded-For header

I want to read the value of the X-Forwarded-For header value in a reque开发者_开发技巧st.

I've tried

HttpContext.Current.Request.Headers["X-Forwarded-For"].Split(new char[] { ',' }).FirstOrDefault();  

in C#.

OR do I need to split the header by ":" and the take the second string? I am asking this because, Wikipedia says

The general format of the field is: X-Forwarded-For: client1, proxy1, proxy2


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.


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();


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜