How can I get LAN IP-A for a computer using Java? I want the IP address associated with the router and the rest of the network.
I have tried something like this:
socket s = new socket ("Www.google.com", 80); String ip = s.getLocalAddress (). GetHostAddress (); S.close ();
It seems to work in some cases, but sometimes it separates the loopback address or something completely. In addition, it requires an internet connection.
Has anyone got another precise method of doing this?
Edit: Thought it would be better to ask here in a comment ..
What if you got many interfaces? For example, for a cable, one for WiFi and one virtual box, is it really impossible to see which network is connected to?
Try java.net Network Interface
Import java.net.NetworkInterface; For (Last counting & lt; network interface & gt; interface = network interface; gate network interface; interface; additional additional elements ();) {last network interface cur = interfaces.nextElement (); If (cur.isLoopback ()) {continue; } System.out.println ("interface" + cur.getName ()); Add to (last interface address: cur.getInterfaceAddresses ()) {Last InetAddress inet_addr = addr.getAddress (); If (Inet_addr example (Inet4Address)) {continue; } System.out.println ("address:" + inet_addr.getHostAddress () + "/" + addr.getNetworkPrefixLength ()); System.out.println ("broadcast address:" + addr.getBroadcast () .getHostAddress ()); }}
Comments
Post a Comment