Skip to content

Instantly share code, notes, and snippets.

@Martyr2
Created June 1, 2017 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Martyr2/796935d56d5471d4cd98382a69728dea to your computer and use it in GitHub Desktop.
Save Martyr2/796935d56d5471d4cd98382a69728dea to your computer and use it in GitHub Desktop.
Gets the visitors IP address for an ASP.NET address. Will take a proxy address if real visitor IP is not forwarded along by the proxy.
/// <summary>
/// Get the IP address of the current client visiting the website.
/// </summary>
/// <returns>String representing the IP address</returns>
public static string GetVisitorIPAddress()
{
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"];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment