1

I am trying to find the client's IP. And I was told that 'request.getHeader("HTTP_X_FORWARDED_FOR")' cannot be trusted since it may be forged and I should use request.getRemoteAddr instead.(In my case it's ok to just get the proxy's IP) So my question is:

why ServletRequest.getRemoteAddr cannot be forged?

another question: what's the difference between HTTP_X_FORWARDED_FOR and X_FORWARDED_FOR?

dario
  • 5,149
  • 12
  • 28
  • 32
bylijinnan
  • 756
  • 3
  • 11
  • 27
  • 1
    It *can* be forged, but it's much harder. It comes from the IP packet, not from an HTTP header. – user207421 Jun 30 '15 at 08:37
  • Thanks! If i understand correctly:HTTP header is in 'application layer' of OSI model so it's easily forged through program(java is one of them), but if I want to change the return value of ServletRequest.getRemoteAddr, I have to parse the ip packet, which is much harder. – bylijinnan Jul 01 '15 at 11:44

1 Answers1

1

If you do request.getRemoteAddr();

and if the user is behind a proxy server or accessing your web server through a load balancer then the above code will get the IP address of the proxy server or load balancer server, not the original IP address of a client.

So if

In my case it's ok to just get the proxy's IP

you are ok with this then request.getRemoteAddr(); is enough.

But in Ideal case you should try this

//is client behind something?
   String ipAddress = request.getHeader("X-FORWARDED-FOR");  
   if (ipAddress == null) {  
       ipAddress = request.getRemoteAddr();  
   }

X_FORWARDED_FOR

The X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or load balancer.

HTTP_X_FORWARDED_FOR

A header HTTP_X_FORWARDED_FOR is set by proxy servers to identify the ip-address of the host that is making the HTTP request through the proxy.

In short they're all the same header, just referred to differently by various implementations. For more view this : HTTP Headers: What is the difference between X-FORWARDED-FOR, X_FORWARDED_FOR and HTTP_X_FORWARDED_FOR?

Community
  • 1
  • 1
Bacteria
  • 8,406
  • 10
  • 50
  • 67
  • Thanks! In java, will request.getHeader("X-FORWARDED-FOR") and request.getHeader("X_FORWARDED_FOR") and request.getHeader("HTTP_X_FORWARDED_FOR") return the same value? – bylijinnan Jul 01 '15 at 11:31