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


  1. Wiki X-Forwarded-For
  2. ServletRequest JavaDoc
  3. HttpServletRequest JavaDoc
  4. How to get Server IP address in Java
Tags :
Founder of, 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.
My website is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts