I modified the code from here below: How to Get IP Address?
static string IPForwarded =
string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"])
? null : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(',').Last().Trim();
static string IPRemoteAddress =
string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"])
? null : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
// Returns a simple message with both IPs
private static string GetIPMessage() { return
(String.IsNullOrWhiteSpace(IPForwarded) ? "" : "[HTTP_XFF " + IPForwarded + "] ") +
(String.IsNullOrWhiteSpace(IPRemoteAddress) ? "" : "[REMOTE_ADDR " + IPRemoteAddress + "] ");
}
In most variations of the original code, it returns the last IP in the list HTTP_X_FORWARDED_FOR
if it isn't empty. Or, it returns REMOTE_ADDR
. Is there any case where I should log both (as I do in GETIPMessage()
for possible IP blocking? In other words, are they mutually exclusive? Would one variable always be empty or useless if the other is present?