Java查找默认网关的网络接口 [英] Java finding network interface for default gateway

查看:254
本文介绍了Java查找默认网关的网络接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我想找到与使用的接口相对应的java.net.NetworkInterface到达默认网关.接口的名称等无法提前知道.

In Java, I'd like to find the java.net.NetworkInterface corresponding with the interface used reach the default gateway. The names of the interfaces, etc, are not know ahead of time.

换句话说,如果以下是我的路由表,则需要与"bond0"相对应的接口:

In other-words, if the following was my routing table, I would want the interface corresponding with "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

经过Google搜索后,我仍然没有找到答案.

After doing some google searching, I still haven't found any answer.


Java运行时必须知道"如何获取此信息(不是说它已公开).使用join(InetAddress grpAddr)调用(未指定接口)将java.net.MulticastSocket连接到多播组时,明显的行为似乎是在默认"接口上进行连接(如上定义).即使默认的intf不是路由表中列出的第一个接口,此方法也有效.但是,加入mcast组的基础POSIX调用需要此信息!:

edit:
The java runtime must "know" how to get this information (not to say that it's exposed). When joining a java.net.MulticastSocket to a multicast group using the join(InetAddress grpAddr) call (which does not specify an interface), the apparent behavior seems to be to join on the "default" interface (as define above). This works even when the default intf is not the first interface listed in the routing table. However, the underlying POSIX call that joins an 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));

要点:通过提供一种不需要intf的加入组播组的方法,java平台隐式地必须知道如何在每个平台上确定适当的intf.

The point: by providing a method to join a multicast group that doesn't require the intf, the java platform, implicitly, must know how to determine the appropriate intf on each platform.

推荐答案

我的方法是:

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

由于使用了数据报(UDP),因此它无法在任何地方连接,因此端口号可能毫无意义,并且不需要访问远程地址(1.1.1.1),只需路由即可.

Because of using datagram (UDP), it isn't connecting anywhere, so port number may be meaningless and remote address (1.1.1.1) needn't be reachable, just routable.

这篇关于Java查找默认网关的网络接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆