7

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?

Frank
  • 30,590
  • 58
  • 161
  • 244
  • When you say `wrong ip`, is the address within your domain? How wrong is it? Can you give us any more information about what the call _is_ returning? – Ken Gentle Nov 04 '08 at 18:52

5 Answers5

19

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6

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

Vijay Dev
  • 26,966
  • 21
  • 76
  • 96
4

The returned IP that you are showing is the localhost IP. This raises the question - where are you testing, and how are you accessing the servlet to test?

If you are running the servlet on your local (development) machine, and also calling it up from a browser on the same machine, then this output is absolutely correct.

Cheers,

-R

John Millikin
  • 197,344
  • 39
  • 212
  • 226
Huntrods
  • 2,561
  • 3
  • 22
  • 29
1

You're running your test server on your local computer and connecting to it on http://localhost/. Since you're connecting on the local interface, the source of the connection is also localhost, aka 127.0.0.1.

masto
  • 1,366
  • 9
  • 7
1

If you call your servlet using http://localhost:8080/servlet, you will usually get "localhost" as the remote addr. If you use the name of your machine, i.e. http://yourmachine/servlet, you will usally get the "correct" address.

mfx
  • 7,168
  • 26
  • 29