Skip to content

Instantly share code, notes, and snippets.

@nikanos
Last active October 31, 2022 20:05
Show Gist options
  • Save nikanos/c14f2be104786d41f97e5da0e8195e5c to your computer and use it in GitHub Desktop.
Save nikanos/c14f2be104786d41f97e5da0e8195e5c to your computer and use it in GitHub Desktop.
GetRemoteIP - extension method on HttpRequestBase
public static string GetRemoteIP(this HttpRequestBase request, bool useForwardedForHeader = false)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
const string FORWARDED_FOR = "HTTP_X_FORWARDED_FOR";
const string REMOTE_ADDR = "REMOTE_ADDR";
string ipAddress = null;
if (useForwardedForHeader)
ipAddress = request.ServerVariables[FORWARDED_FOR].Split(",".ToCharArray()).FirstOrDefault()?.Trim();
if (string.IsNullOrEmpty(ipAddress))
ipAddress = request.ServerVariables[REMOTE_ADDR];
return ipAddress;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment