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

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:

public static string GetUserIP() {   
    var ip = ( HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null
              && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "" )
		     ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
		     : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    if (ip.Contains( "," ))
        ip = ip.Split( ',' ).First().Trim();
    return ip;
}
Advertisements

4 thoughts on “C#: Getting a user IP behind a proxy (HTTP_X_FORWARDED_FOR)

  1. 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”])

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s