How to get client Ip Address using Java HttpServletRequest


Hi, I am Malathi Boggavarapu working at Volvo Group and i live in Gothenburg, Sweden. I have been working on Java since several years and had vast experience and knowledge across various technologies.


In this post we will see how to get IP address from HttpServletRequest. 

For the web application which is not running behind the proxy server, we can directly get from the HttpServletRequest request object as below

remoteAdr = request.getRemoteAddr();

For suppose if your web application is behind a proxy server, load balancer or Cloudfare then you should get client Ip address using the Http request header X-Forwarded-For (XFF). See below.
private String getIpAddress(HttpServletRequest request) {
    String remoteAdr = "";
    if(request != null){
        remoteAdr = request.getHeader("X-FORWADED-FOR");
        if (remoteAdr == null || "".equals(remoteAdr)) {
            remoteAdr = request.getRemoteAddr();
        }
    }
    return remoteAdr;
}

If the above solution somehow does not work, please get all the headers
from request and see what actually hold the client IpAdress. 
Below is the method you can use to get all the headers and 
iterate through them.
private Map<String, String> getRequestHeaders(HttpServletRequest request) {

    Map<String, String> result = new HashMap<>();

    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        result.put(key, value);
    }
    return result;
}

Please post your queries or comments. Thank you!

Comments

Post a Comment

Popular posts from this blog

Bash - Execute Pl/Sql script from Shell script

How to install Portable JDK in Windows without Admin rights