what is the right way to get request's ip

sprite picture sprite · Aug 21, 2013 · Viewed 67.1k times · Source

I find some different ways to get ip in servlet. but i don't know which one is right and why.

1:

request.getHeader( "X-Real-IP" )

2:

  String ip = request.getHeader("X-Forwarded-For"); 
  if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = request.getHeader("Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = request.getHeader("WL-Proxy-Client-IP");  
    }  
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = request.getHeader("HTTP_CLIENT_IP");  
    }  
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
    }  
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
        ip = request.getRemoteAddr();  
    } `

3:

 String ip=request.getHeader("x-forwarded-for");
                if(ip==null){
                    ip=request.getRemoteAddr();
                }
                String ips[]=ip.split(",");`
                                ip=ips[0];

Answer

Stephen C picture Stephen C · Aug 21, 2013

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.