Mostly for logging and security purpose, we need the information of IP address for incoming requests. In any java web application, you can get IP address using getRemoteAddr()
method.
String httpServletAddress = request.getRemoteAddr();
BUT, if your application is running behind a load balancer proxy and you 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 above statement get get you IP address of balancer proxy only.
Use Tomcat’s RemoteIpFilter
In case of above situation, you may use tomcat provided RemoteIpFilter
servlet filter.
To configure, RemoteIpFilter
using java configuration – e.g. in spring boot application, register 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 above filter, start the application.
Now when you will use request.remoteAddr()
method the you will get correct IP address of calling client.
Internally RemoteIpFilter
integrate X-Forwarded-For
and X-Forwarded-Proto
HTTP headers.
Another feature of this servlet filter is to replace the apparent scheme (http/https) and server port with the scheme presented by a proxy or a load balancer via a request header (e.g. “X-Forwarded-Proto”).
Happy Learning !!
Tushar
HI Lokesh,
tell me, if i add catalina, juli, util like tomcat jars in other server and configure xml, it will work or not?
Bill
Can this configuration work well with other web servers, such as Jetty?
Thanks
Lokesh Gupta
RemoteIpFilter
is tomcat specific. It will NOT work in other servers.