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;
}
// headers in the order of trust, most trusted at the top
Then in your JSP, you can just do
<%=getClientIpAddr(slingRequest)%>
Note: Make sure that all headers are allowed from the dispatcher
At dispatcher, side make sure that you are allowing all the headers with this configuration in dispatcher.any
/clientheaders
{
"*"
}
Then in your JSP, you can just do
<%=getClientIpAddr(slingRequest)%>
Note: Make sure that all headers are allowed from the dispatcher
At dispatcher, side make sure that you are allowing all the headers with this configuration in dispatcher.any
/clientheaders
{
"*"
}
No comments:
Post a Comment
If you have any doubts or questions, please let us know.