Read X-Forwarded-For header

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

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


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.


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

Tags:

C#

Asp.Net