我怎么知道哪个接口将允许UPD连接? 我得到了所有这样的网络接口的列表:
Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
$ ipconfig
Windows IP Configuration
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . : myworld.com
IPv4 Address. . . . . . . . . . . : 10.219.1.157
Subnet Mask . . . . . . . . . . . : 255.255.254.0
Default Gateway . . . . . . . . . : 10.219.0.1
Tunnel adapter isatap.myworld.com:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . : myworld.com
答案 0 :(得分:1)
我发现的解决方案是遍历所有接口,并测试已启用连接: 示例工作代码为:
public static DatagramChannel openDatagramChannelForAnyWorkingInterface(int port, String ip) throws IOException {
DatagramChannel channel;
try {
channel = DatagramChannel.open(StandardProtocolFamily.INET);
channel.configureBlocking(true);
channel.socket().setReuseAddress(true);
channel.bind(new InetSocketAddress(port));
Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface np : Collections.list(networkInterfaceEnumeration)) {
try {
channel.join(InetAddress.getByName(ip), NetworkInterface.getByName(np.getName()));
log.info("Data joining channel ip [{}], port [{}] interface [{}]", ip, port, np.getName());
break;
} catch (Exception ignore) {
}
}
} catch (Exception e) {
log.error("Exception while subscribing to market data: ", e);
throw e;
}
return channel;
}