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 :
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 making a donation to this charity, thanks.

Related Posts

Popular Posts