Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get client IP address behind load balancer with SSL java

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?

like image 393
vikifor Avatar asked Apr 06 '26 13:04

vikifor


1 Answers

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(); 
}
like image 150
Hardik Sheth Avatar answered Apr 11 '26 01:04

Hardik Sheth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!