what is the right way to get request's ip [duplicate]

Solution 1:

The answer is complicated.

  • If your servlet is running on a webserver that is behind a reverse proxy or load balancer, then that web proxy can be configured to inject a request header that gives the IP address that the request came from. Different reverse proxies will inject different headers. Consult the documentation for your (front-end) server.

  • If your client uses a (forward) proxy, then it might insert headers to say what the client IP address is ... or it might not. And the IP address it insert might be incorrect.

  • The value you get by calling request.getRemoteAddr() is going to be the IP address of the immediate upstream source of the request.

None of the headers that you listed is standard, but "x-forwarded-for" is reputed to be a defacto standard; i.e. it is the one that is most likely to be inserted by a proxy, etc ... if anything is injected.

Finally, even if you did get an IP address, it wouldn't necessarily help you. For instance, if the client sits on a private network and connects to the internet via a NAT gateway, then the IP address in HTTP request will be an address of the NAT server ... not the actual client IP.


So what does this all mean? Well basically, it means that in general you cannot reliably find out the IP address of the system that the request originated from.

Solution 2:

This seems the most we can do to get the original IP address of the client

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