6

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
  • 29,646
  • 56
  • 159
  • 233
  • 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,335,956
  • 823
  • 8,931
  • 9,049
6

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

Vijay Dev
  • 25,766
  • 20
  • 75
  • 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
  • 191,086
  • 39
  • 207
  • 222
Huntrods
  • 2,543
  • 3
  • 22
  • 28
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
  • 6,938
  • 25
  • 29