Request.UserHostAddress return IP address of Load Balancer
From within your own application, if nothing else has been done to help you, you're stuck. That's as much information as is available to you.
If you're lucky, your load-balancer has been configured to add one or more extra headers with information about the original request.
One common solution is the X-Forwarded-For
header:
The X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or load balancer.
which you would then access via the Request.Headers
property.
But discovering whether this (or another) header is available is not something we can help with - you need to talk to the people who configured the load balancer for your organization.
Used this code to inspect production environment... It worked for me:
System.Web.HttpRequest oRequest = System.Web.HttpContext.Current.Request;
string header;
string ip;
header = "HTTP_X_FORWARDED_FOR";
ip = oRequest.ServerVariables[header];
Response.Write(string.Format("{0} - {1}", header, ip) + Environment.NewLine);
header = "REMOTE_ADDR";
ip = oRequest.ServerVariables[header];
Response.Write(string.Format("{0} - {1}", header, ip) + Environment.NewLine);
header = "HTTP_CLIENT_IP";
ip = oRequest.ServerVariables[header];
Response.Write(string.Format("{0} - {1}", header, ip) + Environment.NewLine);
header = "Request.UserHostAddress";
ip = oRequest.UserHostAddress;
Response.Write(string.Format("{0} - {1}", header, ip) + Environment.NewLine);
In reference to @Damien_The_Unbeliever's answer, here's the complete solution:
public static string GetIpAddress()
{
var request = HttpContext.Current.Request;
// Look for a proxy address first
var ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
// If there is no proxy, get the standard remote address
if (string.IsNullOrWhiteSpace(ip)
|| string.Equals(ip, "unknown", StringComparison.OrdinalIgnoreCase))
ip = request.ServerVariables["REMOTE_ADDR"];
else
{
//extract first IP
var index = ip.IndexOf(',');
if (index > 0)
ip = ip.Substring(0, index);
//remove port
index = ip.IndexOf(':');
if (index > 0)
ip = ip.Substring(0, index);
}
return ip;
}