Get the client IP address or forwarder IP address in C# ASP.NET.
/// <summary>
/// Attempts to retrieve the real client ip (w/ proxy detection).
/// </summary>
/// <returns>The IP address of the remote client,
/// or "0.0.0.0" if it cannot be obtained.</returns>
public static string GetClientIpAddress()
{
const string defaultValue = "0.0.0.0";
HttpContext context;
if ((context = HttpContext.Current) == null)
{
return defaultValue;
}
HttpRequest request;
try
{
// store a local ref to the request object:
request = context.Request;
}
catch (HttpException)
{
Debug.WriteLine("Http request context is not available.");
return defaultValue;
}
//
// check proxy forwarder indicators first:
string forwarderForIp = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(forwarderForIp))
{
int firstCommaIndex = forwarderForIp.IndexOf(',');
if (firstCommaIndex > 0)
{
// X-Forwarded-For can return multiple ip's, so
// just get the first one.
// ex: X-Forwarded-For: client, proxy1, proxy2
forwarderForIp = forwarderForIp.Substring(0, firstCommaIndex).Trim();
}
if (!forwarderForIp.Equals("unknown",
StringComparison.InvariantCultureIgnoreCase))
{
return forwarderForIp;
}
}
// get the client ip from server from server vars:
string remoteAdd = request.ServerVariables["REMOTE_ADDR"];
return !string.IsNullOrEmpty(remoteAdd) ? remoteAdd : defaultValue;
}