We we’re trying to log the clients IP when using some of our API methods and they all returned the same IP.
So we used Request.UserHostAddress. Which obviously was returning the servers IP address all the time.
So how can we get the client IP?
Well by reading how the application Gateway works [1] we can see that it inserts six additional HTTP/s headers.The one i’m interested in is “x-forwarded-for”.
If you’re interested you can also log this in the IIS by adding a custom field to the IIS site log. Check resource below [2].
Then use the following code to get the IP. If you’re not going through a proxy or Load balancer the X-Forwaded-For will be empty and therefore we return Remote-Addr instead.
public static string GetIp()
{
var ip = String.IsNullOrWhiteSpace(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"])
? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]
: HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ip == null)
return string.Empty;
if (ip.Contains(","))
{
ip = ip.Split(',').First().Trim();
}
return ip;
}