Getting Client IP in Apache/Tomcat

19 03 2009

This is an issue that just keep coming back to me but I always tend to forget how it’s been resolved before.  I would have to research into the issue every single time.  The problem is that request.getRemoteAddr() doesn’t always return the client IP in Tomcat (or any app servers) when it’s sitting behind a proxy.  In my case, Tomcat is behind Apache’s balancer.  When you call request.getRemoteAddr(), it would return the Apache server’s IP instead of the client IP.  

To get the actual client IP, you need to pull it from the header.  Apache sets a header variable called “x-forwarded-for” with the client IP.  You can simply grab it from the header:

String ip = request.getHeader("x-forwarded-for");

This is just one of the thing I found annoying. I can understand why request.getRemoteAddr() doesn’t always return client IP. I’m hoping eventually Tomcat will have a reliable method to return a proper client IP.

Join the forum discussion on this post - (1) Posts