Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why HttpServletRequest.getRemoteAddr() doesn't work in Java servlet? [duplicate]

I'm developing a web app with java servlet, I hope to get the user ip info by calling request.getRemoteAddr() from inside processRequest(HttpServletRequest request,HttpServletResponse response).

But it returns a wrong IP. Since I'm not very knowledgeable about this area, I don't know what it is displaying, maybe a proxy, I got this:

RemoteAddr : 127.0.0.1
RemoteHost : 127.0.0.1
x-forwarded-for : null

127.0.0.1 is not my IP.

Yet when I go to: http://www.javascriptkit.com/script/script2/displayip.shtml it will display the right one, since I'm using servlet, I don't have the .shtml to my dynamically generated html page, what can I do? And why the script on that site can display it correctly while request.getRemoteAddr() can't do it?

Thanks for all the answers, I have a clue now, after deploying it to the server, it works as expected. Showed the correct address.

But even when I develop it on my local machine, how to ask it to display the absolute IP as if it running on a real server? Or is it doable?

like image 985
Frank Avatar asked Nov 04 '08 18:11

Frank


2 Answers

What IP address is it displaying? My guess is there's some proxy or something changing things. (For instance, that script page displayed my ADSL router's IP address - not the one inside my LAN - for obvious reasons.)

EDIT: Now that you've shown that the IP address you're seeing is 127.0.0.1 the answer is fairly clear - you're seeing your loopback adapter (i.e. the shortcut to the same machine) presumably because you're testing on the same machine you're developing on. The answer is entirely correct.

Try it from a different machine and you'll get a more useful IP address.

like image 195
Jon Skeet Avatar answered Sep 29 '22 03:09

Jon Skeet


Check the X-Forwarded-For header by calling request.getHeader("X-Forwarded-For") and see what IP does it return.

like image 34
Vijay Dev Avatar answered Sep 29 '22 03:09

Vijay Dev