vikifor
vikifor

Reputation: 3466

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?

Upvotes: 3

Views: 9081

Answers (1)

Hardik Sheth
Hardik Sheth

Reputation: 198

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(); 
}

Upvotes: 1

Related Questions