0

I am having many tomcat servers, which run the same JSP application and load balancer. I like to know from which IP address is client request. I am using this code:

String ipAddress = request.getHeader("X-FORWARDED-FOR");
        if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
        }

The code request.getHeader("X-FORWARDED-FOR") is always null and request.getRemoteAddr() is always returning the same IP address from diffrent client machines. What is the problem?

vikifor
  • 3,426
  • 4
  • 45
  • 75

2 Answers2

3

You said, request.getHeader("X-FORWARDED-FOR") is always null , you should check this at the load balancer level,may be from there it would have been modifying.

Regarding your second point request.getRemoteAddr() is always returning the same IP address from diffrent client machines, If you see the API Docs,it clearly specifies that this api call would return client address or address of last proxy that sent the request, and in your case it is load balancer(i assumed as per your description),which is why you are receiving same IP address.

dReAmEr
  • 6,986
  • 7
  • 36
  • 63
1

An "X-FORWARDED-FOR" header is often inserted by a proxy, load balancer or reverse proxy that sits between the client and your web server. However, this is only a convention / defacto standard, not a true standard. Your load balancer could be inserting a different header, or no header at all. You need to check the load balancer's documentation and/or configurations.

The IP address returned by request.getRemoteAddr() is the immediate upstream IP address that the request came from. It is quite likely to be your load balancer's IP address, but in other circumstances it could be the IP address of a client-side proxy, or a NAT server. In general, you cannot rely on it being the actual client IP address.

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