Finding the Java Network Interface for the Default Gateway

In Java, I would like to find java.net.NetworkInterface corresponding to the interface used, access to the default gateway. Interface names, etc. Not known in advance.

In other words, if my routing table were as follows: I need an interface matching "bond0":

$ netstat -r Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface 10.10.10.0 * 255.255.255.0 U 0 0 0 bond0 10.10.11.0 * 255.255.255.0 U 0 0 0 eth2 10.10.11.0 * 255.255.255.0 U 0 0 0 eth3 10.10.12.0 * 255.255.255.0 U 0 0 0 eth4 10.10.13.0 * 255.255.255.0 U 0 0 0 eth5 default mygateway 0.0.0.0 UG 0 0 0 bond0 

After doing a search on Google, I still could not find the answer.

change
The java runtime should “know” how to get this information (not to say that it is exposed). When connecting java.net.MulticastSocket to a multicast group using a join call (InetAddress grpAddr) (which the interface does not specify), the apparent behavior seems to join the default interface (as defined above). This works even if intf is not the first interface specified in the routing table by default. However, the main POSIX call that joins the mcast group requires this information !:

 struct ip_mreqn group; group.imr_multiaddr = ... group.imr_address = **address of the interface!** setsockopty(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &group, sizeof(group)); 

Point : by providing a method to join a multicast group that does not require intf, the java platform must implicitly know how to determine the corresponding intf on each platform.

+7
source share
2 answers

My way:

 try(DatagramSocket s=new DatagramSocket()) { s.connect(InetAddress.getByAddress(new byte[]{1,1,1,1}), 0); return NetworkInterface.getByInetAddress(s.getLocalAddress()).getHardwareAddress(); } 

Due to the use of a datagram (UDP), it is not connected anywhere, so the port number can be meaningless, and the remote address ( 1.1.1.1 ) cannot be accessed, we simply route it.

+4
source

As far as I know, there will be no good way to do this, because such low-level details for Java are very difficult to implement in a cross-platform way. java.net.NetworkInterface may help a little, but if the methods available are not enough, you may have to resort to something more ugly.

Is this something that will work on a particular platform forever or should it be more portable? In the worst case, you can try to execute a system command and analyze the output, but it is not very portable or stable.

Some related topics:

Is it possible to get the IP address and MAC address of the default gateway in java?

Finding a SSID for a Wireless Network with Java

0
source

All Articles