I am having 2 tomcat application servers behind load balancer with ssl. I like to get the IP address from which user request is coming from . I am using this code:
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
request.getHeader("X-FORWARDED-FOR") is always null even if property for sending x-forwarded-for is enabled on load balancer, and request.getRemoteAddr() is always giving the IP address of load balancer.
When we disable ssl, this work fine, I got client IP, not the IP of the load balancer. Is it possible somehow to get client IP without disabling ssl?
I had the same issue, I tried below code and it has worked for me
private static final String[] HEADERS_LIST = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR"
};
public static String getClientIp(HttpServletRequest request) {
for (String header : HEADERS_LIST) {
String ip = request.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
}
return request.getRemoteAddr();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With