Alex Rivera | Logout

java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?

Asked 2010-03-04T17:23:52.697
56

I'm writing a simple networking app. I need to know the real IP of my machine on the network, like 192.168.1.3 . getLocalHost returns 127.0.0.1 (on Linux, I don't know if it is the same on windows). How to do it?

Edit
Report

1 Answer

23

As the machine might have multiple addresses, it's hard to determine which one is the one for you. Normally, you want the system to assign an IP based on its routing table. As the result depends on the IP you'd like to connect to, there is a simple trick: Simply create a connection and see what address you've got from the OS:

// output on my machine: "192.168.1.102"
Socket s = new Socket("192.168.1.1", 80);
System.out.println(s.getLocalAddress().getHostAddress());
s.close();

// output on my machine: "127.0.1.1"
System.out.println(InetAddress.getLocalHost().getHostAddress());

I'm not sure whether it's possible to do this without establishing a connection though. I think I've once managed to do it with Perl (or C?), but don't ask me about Java. I think it might be possible to create a UDP socket (DatagramSocket) without actually connecting it.

If there is a NAT router on the way you won't be able to get the IP that remote hosts will see though. However, as you gave 192.* as an example, I think you don't care.

answered 2010-03-04T17:32:18.633

Your Answer