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, dunno if it is the same on windows) how to do it?;
views:
738answers:
3Your computer may have multiple IPs. How do you know which one? The way I do it is to have a very simple CGI running on another machine that reports back the IP it's seen, and I hit that when I need to know what my IP looks like to the outside world.
In my windows,
System.out.println(InetAddress.getLocalHost().getHostAddress());
prints 10.50.16.136
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:
// instead of google.com, use what makes most sense to you
// 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.