Reputation: 602
I would like to get the ClientIPaddress but when I call to Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
I always get NULL
.
After checking the list of the Servervariables
I noticed that HTTP_X_FORWARDED_FOR
is not in the list of options.
Anyone knows how this is possible and how to solve? Or is it normal that this option is not in the list and I'm missing something.
Thanks in advance
Upvotes: 8
Views: 36288
Reputation: 1318
If you run it on local machine , it's normal to don't see any thing, otherwise you run it in on a real external host.
.net HTTP_X_FORWARDED_FOR NULL on localhost
Upvotes: 2
Reputation: 61
public string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
This method maybe useful for you.
Upvotes: 6
Reputation: 359
Please try this:
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();
return ip.Trim();
}
Found here:
http://mycodepad.wordpress.com/2013/04/26/c-getting-a-user-ip-behind-a-proxy-http_x_forwarded_for/
Upvotes: 4
Reputation: 759
Request.ServerVariables["HTTP_X_FORWARDED_FOR"]
will only have a value, if the request was forwarded by a proxy. Usually you will get the client IP by using Request.ServerVariables["REMOTE_ADDR"]
.
Upvotes: 11