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
integrateX-Forwarded-For
andX-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 !!
HI Lokesh,
tell me, if i add catalina, juli, util like tomcat jars in other server and configure xml, it will work or not?
Can this configuration work well with other web servers, such as Jetty?
Thanks
RemoteIpFilter
is tomcat specific. It will NOT work in other servers.