0

I'm trying to get client IP address in Struts2. The request is routed through Apache web server to Tomcat server, both servers reside on same physical server. The connection between client and Apache is secure but not between Apache and Tomcat. When I try to get client IP address, I always get 127.0.0.1. How do I get client IP address in Struts2/Servlet from Apache web server?

Thanks in advance!

lupchiazoem
  • 8,026
  • 6
  • 36
  • 42
  • I just noticed a notification on this. @balusc The question was asked in 2014 and you mark it as duplicate in 2016. Seriously? – lupchiazoem May 21 '19 at 07:14

2 Answers2

2

IP address of the client in a servlet you can get so -

HttpServletRequest httpServletRequest = (HttpServletRequest) request;

// Proxy
String userIpAddress = httpServletRequest.getHeader("X-Forwarded-For");

if(userIpAddress == null) {
   userIpAddress = request.getRemoteAddr();
}
  • If `userIpAddress` is not `null`, will it also contain proxy address? If so, please help me to decide maximum length to store `userIpAddress` value in database. Thanks! – lupchiazoem Feb 17 '14 at 03:38
  • 1
    In fact, I had this doubt after seeing Stephen's comment - "A request may go through multiple proxies". Your point helps - "left-most being the original client". BTW, I know about max client IP address. That's why I had specifically mentioned `userIpAddress`(mentioned as code) and not about client ip. :) – lupchiazoem Feb 17 '14 at 06:26
2

When I try to get client IP address, I always get 127.0.0.1.

That is because the request when you see it in the servlet in Tomcat has been (reverse) proxied by the Apache front end, and the Apache <-> Tomcat traffic is going over the loopback network.

The solution is to check the headers added by the proxy; e.g. see @Alexey's answer.

A couple of things to note:

  • This behaviour (proxies adding headers) is not specified by the HTTP specs.

  • Different proxies behave differently; e.g. they may add a different header.

  • A request may go through multiple proxies.

  • In general, there is no guarantee that a proxy is telling the truth, or that it will reveal the information at all.

  • The "ultimate" client IP address could be a NATed address ... meaning that you will have create difficulty identifying the true client.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216