Tuesday, December 6, 2011

Retrieving Client IP Address from Request

This post is relevant for Tomcat users who want to retrieve the IP Address of the client from which the request intiated. To be more specific this post is more suitable to users using Tomcat version 6.0.24 or higher.

The method getRemoteAddr() defined in HttpServletRequest class does not return the correct IP Address of the client. The only way to get the correct value of client IP Address was to write code to handle the header "X-FORWARDED-FOR". This header contains the list of all IP addresses (separated by commas) of all the proxies/hops through which the request passes before reaching the server.

However, the catch here is; there can be header spoofing which may result in incorrect value being returned by this Header.

The best option available to strip the messy code handling for "X-FORWARDED-FOR" and get the correct value of client IP Address is using the "RemoteIPValve". This valve can be configured in Tomcat (server.xml) and this results in getRemoteAddr() method returning the correct IP.

To configure the valve, add the below line in server.xml:

(<)Valve className="org.apache.catalina.valves.RemoteIpValve" /(>)

If in case your server is behind a load balancer, then you need to add the IP Address of the load balancer into the internal Proxies list

(<)Valve className="org.apache.catalina.valves.RemoteIpValve" internalProxies = "127\.0\.0\.1"/(>)

Always remember to escape the dot (.) with a slash (\), as it expects a regular expression for internalProxies.

Hope this help others as well!!