Java finds the network interface of the default gateway

In Java, I want to find the Java. Net interface corresponding to the interface used net. The network interface arrives at the default gateway The name of the interface is not known in advance

In other words, if the following is my routing table, I want the interface to correspond to "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 some Google searches, I still can't find any answers

Edit: the Java runtime must "know" how to get this information (not that it has been exposed) When using join (InetAddress grpaddr) call (no interface specified), Java net. When multicastsocket connects to a multicast group, the obvious behavior seems to be to join on the "default" interface (as described above) This works even if the default INTF is not the first interface listed in the routing table However, this information is required for basic POSIX calls that join the mcast group!:

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

Key point: by providing a way to join multicast groups that do not require INTF, the Java platform must know how to determine the appropriate INTF on each platform

Solution

My approach is:

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

Due to the use of datagram (UDP), it will not connect anywhere, so the port number may be meaningless. The remote address (1.1.1.1) does not need to be reachable, but can be routed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>