C#: Getting a user IP behind a proxy (HTTP_X_FORWARDED_FOR)

0 0 votes
Article Rating

Did you know that HTTP_X_FORWARDED_FOR can return multiple IPs? According to http://en.wikipedia.org/wiki/X-Forwarded-For the format is:

X-Forwarded-For: client, proxy1, proxy2

So you just need:

Simple as that 🙂

0 0 votes
Article Rating
Subscribe
Notify of
guest
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
powlette

if (ip.Contains( “,” ))
ip.Split( ‘,’ ).First().Trim();

I think you mean to say:

if (ip.Contains( “,” ))
ip = ip.Split( ‘,’ ).First().Trim();

johnnyzone

Instead of:

HttpContext.Current.Request.ServerVariables[“HTTP_X_FORWARDED_FOR”] != null
&& HttpContext.Current.Request.ServerVariables[“HTTP_X_FORWARDED_FOR”] != “”

It is much easier to use the C# method for this exact check:

!String.IsNullOrWhiteSpace(HttpContext.Current.Request.ServerVariables[“HTTP_X_FORWARDED_FOR”])

George Kosmidis

True! Thanks!