How to get client Ip Address in Java

Normally, you can use servletRequest.getRemoteAddr() to get the client’s IP address that’s accessing your Java web application.

String ipAddress = request.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 “X-Forwarded-For (XFF)“.

   //is client behind something?
   String ipAddress = request.getHeader("X-FORWARDED-FOR");  
   if (ipAddress == null) {  
	   ipAddress = request.getRemoteAddr();  
   }

References

  1. Wiki X-Forwarded-For
  2. ServletRequest JavaDoc
  3. HttpServletRequest JavaDoc
  4. How to get Server IP address in Java
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Vishal

    Nice. Thanks.!!

  • Siva

    i am getting output for the above code is 0:0:0:0:0:0:0:1, how to correct ip address from request object.

    • Marcos

      It works when deployed. On localhost it shows the 0:0:0:0:0:0:0:1 address you are seeing. Try it.

  • qingshan

    public static String getIpAddr(HttpServletRequest request) {
    String ip = request.getHeader(“X-Real-IP”);
    if (null != ip && !””.equals(ip.trim())
    && !”unknown”.equalsIgnoreCase(ip)) {
    return ip;
    }
    ip = request.getHeader(“X-Forwarded-For”);
    if (null != ip && !””.equals(ip.trim())
    && !”unknown”.equalsIgnoreCase(ip)) {
    // get first ip from proxy ip
    int index = ip.indexOf(‘,’);
    if (index != -1) {
    return ip.substring(0, index);
    } else {
    return ip;
    }
    }
    return request.getRemoteAddr();
    }

  • dude

    X-FORWARDED-FOR is not safe because client can owerwrite it in request. Best solution is good configured proxy server.

  • saurabh mittal

    Hey Mkyong…i agree what you say about user behind the proxy server, but using “X-FORWARDED-FOR” didn’t help either. It is giving null. I am trying to get the real ip address of the client but its not working.
    Only request.getRemoteAddr() gives some ip address but that ip address is not of the client its of the proxy server or the load balancer.

    • srinu

      req.getHeader(“x-forwarded-for”);

      • Shubhrajyoti satpathy

        hi srinu can u tell me how i shall be add this in project

  • Pingback: How to get Server IP address in Java()