Tomcat – Get Real IP behind Load Balancer

Lokesh Gupta

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 !!

Comments

Subscribe
Notify of
guest
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode