Skip to content

Instantly share code, notes, and snippets.

@yupadhyay
Created February 14, 2016 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yupadhyay/7d6086ca163734103a76 to your computer and use it in GitHub Desktop.
Save yupadhyay/7d6086ca163734103a76 to your computer and use it in GitHub Desktop.
public enum IPHeaders {
CLIENT_IP_UNDERSCORE("Client_IP"),
CLIENT_IP("Client-IP"),
X_CLIENT_IP("X-Client-IP"),
X_FORWARDED_FOR("X-Forwarded-For"),
FORWARDED_FOR("Forwarded-For"),
VIA("Via"),
REMOTE_ADDR("Remote-Addr"),
X_REMOTE_ADDR("X-Remote-Addr"),
X_CLUSTER_CLIENT_IP("X-Cluster-Client-IP"),
X_FORWARDED("X-Forwarded"),
FORWARDED("Forwarded");
public final String text;
private IPHeaders(String text)
{
this.text = text;
}
public String getText()
{
return text;
}
};
//And Then
public String getClientIpAddr(SlingHttpServletRequest request) {
String ip = "";
// looks through http headers, case-insensitive
for (IPHeaders ipHeader : IPHeaders.values()) {
ip = StringEscapeUtils.escapeHtml4(request.getHeader(ipHeader.getText()));
if (ip != null) {
LOGGER.debug(ipHeader.getText() + "=" + ip);
}
if (ip != null && ip.length()>0 && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
}
// note that if headers aren't set, we could return source of immediate upstream request
// using request.getRemoteAddr(), but this isn't meaningful for us
String remoteAddr = request.getRemoteAddr();
if (remoteAddr != null) {
LOGGER.debug("getRemoteAddr=" + remoteAddr);
ip = remoteAddr;
}
if (ip == null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)) {
ip = "0.0.0.0"; // send a dummy value
}
return ip;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment