Friday 18 July 2014

How to get Client IP Adress in Java

Simply getting the IP of the remote client in Java is an easy task. Assuming we have a request instance, we can simply invoke the “getRemoteAddr” method

servletRequest.getRemoteAddr() 


But, if user is behind a proxy server or access your web server through a Load balancer (for example, in cloud hosting), the above code will get the IP address of the proxy server or load balancer server, not the original IP address of a client.

To solve it, you should get the IP address of the request’s HTTP header



Below is the code:


public class IPUtils {
private static final String[] HEADERS_TO_TRY = {
            "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 getClientIpAddress(HttpServletRequest request) {
        for (String header : HEADERS_TO_TRY)  {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
       }
        String ip =  request.getRemoteAddr();
        log.error("getClientIpAddress Remote ip Address :" +ip);
        return ip;
    }

}






No comments:

Post a Comment