Tomcat – Get Real IP behind Load Balancer

Mostly for logging and security purposes, we need the IP address information for incoming requests.

1. HTTPServletRequest.getRemoteAddr()

In a Java web application, we can get IP address using HTTPServletRequest.getRemoteAddr() method.

String ipAddress = httpServletRequest.getRemoteAddr();

BUT, if our application is running behind a load balancer proxy and we would like to translate the real request IP that is used by the users instead of the IP from the proxy when our application instance receives the request – then the above statement will return IP address of balancer proxy only.

2. Tomcat’s RemoteIpFilter

In case of the above situation, we may use tomcat provided RemoteIpFilter servlet filter.

Internally RemoteIpFilter integrate X-Forwarded-For and X-Forwarded-Proto HTTP headers.

To configure, RemoteIpFilter using Java configuration – e.g. in spring boot application, register RemoteIpFilter bean with @Configuration annotation.

@Configuration
public class WebConfiguration {
	@Bean
	public RemoteIpFilter remoteIpFilter() {
		return new RemoteIpFilter();
	}
}

Or using XML configuration e.g. web.xml – use filter tag.

<filter>
    <filter-name>RemoteIpFilter</filter-name>
    <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
 </filter>
  
 <filter-mapping>
    <filter-name>RemoteIpFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
 </filter-mapping>

After registering the above filter, start the application.

Now when we can use request.remoteAddr() method, we will get the correct IP address of the calling client.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

3 thoughts on “Tomcat – Get Real IP behind Load Balancer”

  1. HI Lokesh,
    tell me, if i add catalina, juli, util like tomcat jars in other server and configure xml, it will work or not?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.