Last active
October 31, 2022 20:05
-
-
Save nikanos/c14f2be104786d41f97e5da0e8195e5c to your computer and use it in GitHub Desktop.
GetRemoteIP - extension method on HttpRequestBase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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