How can i get the LAN IP-address of a computer using Java? I want the IP-address which is connected to the router and the rest of the network.
I've tried something like this:
Socket s = new Socket("www.google.com", 80);
String ip = s.getLocalAddress().getHostAddress();
s.close();
This seem to work on some cases, but sometimes it returns the loopback-address or something completely different. Also, it requires internet connection.
Does anyone got a more accurate method of doing this?
EDIT: Thought it would be better to ask here than in a comment..
What if you got many interfaces? For example, one for cable, one for wifi and one for virtual box or so. Is it impossible to actually see which one is connected to the network?
As Daniel already pointed out, you cannot know which interface is the one "connected". What if, for example, the computer has multiple network interface cards which are both connected to separate physical LANs?
Let the user decide which interface to use or try them all, depending on what your use case is.
At first: There is no single address. Your machine has at least two adresses (127.0.0.1 on "lo" and maybe 192.168.1.1 on "eth1").
You want this: Listing network interfaces
As you may expect, you cannot automatically detect which one is connected to any of your routers, since this needs potentially complex parsing of your routing tables. But if you just want any non-local address this should be enought. To be sure, try to use this at least one time on vista or Windows 7, since they add IPv6 addresses.
The following is sample output from the example program:
Try java.net.NetworkInterface
This is a method I've used for a while. It includes a little hack to figure out the externally visible ip-address as well.