C#: Getting a user IP behind a proxy (HTTP_X_FORWARDED_FOR)
by George Kosmidis / Published 12 years ago, modified 5 years ago
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 = String.IsNullOrWhiteSpace( HttpContent.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;
}
Simple as that!