How do I get the remote address of a client in servlet?

grassbl8d picture grassbl8d · Jan 13, 2011 · Viewed 75.7k times · Source

Is there any way that I could get the original IP address of the client coming to the server? I can use request.getRemoteAddr(), but I always seem to get the IP of the proxy or the web server.

I would want to know the IP address that the client is using to connect to me. Is there anyway that I could get it?

Answer

Fareed Alnamrouti picture Fareed Alnamrouti · Mar 10, 2013

try this:

public static String getClientIpAddr(HttpServletRequest request) {  
        String ip = request.getHeader("X-Forwarded-For");  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }  
        return ip;  
    }