使用SSL java获取负载均衡器后面的客户端IP地址

时间:2015-02-19 01:03:43

标签: tomcat ip load-balancing

我在负载均衡器后面有2个tomcat应用服务器和ssl。我想获取用户请求来自的IP地址。我正在使用此代码:

String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
    ipAddress = request.getRemoteAddr();
}
即使在负载均衡器上启用了发送x-forwarded-for的属性,

request.getHeader("X-FORWARDED-FOR")也始终为null,并且request.getRemoteAddr()始终提供负载均衡器的IP地址。

当我们禁用ssl时,这工作正常,我得到了客户端IP,而不是负载均衡器的IP。是否有可能在不禁用ssl的情况下获取客户端IP?

1 个答案:

答案 0 :(得分:0)

我有同样的问题,我尝试了下面的代码并且它对我有用

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