Java 中的 IPv6 可用性

如果计算机网络能够处理 IPv6 连接,有没有办法检查 Java?我不是在问如何检查字节数组是 IPv4 地址还是 IPv6,或者 InetAddress 是其中之一,而是如何判断网络本身是否支持这种连接。


莫回无
浏览 235回答 3
3回答

开心每一天1111

是的; 您可以循环遍历接口并检查它们中是否有任何一个不是环回的 IPv6 地址。final Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();while (e.hasMoreElements()) {&nbsp; &nbsp; final Iterator<InterfaceAddress> e2 = e.nextElement().getInterfaceAddresses().iterator();&nbsp; &nbsp; while (e2.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; final InetAddress ip = e2.next().getAddress();&nbsp; &nbsp; &nbsp; &nbsp; if (ip.isLoopbackAddress() || ip instanceof Inet4Address){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }}return false;

阿波罗的战车

上面的功能版本只是第一个接口,不是全部迭代。将它们全部迭代:private static boolean supportsIPv6() throws SocketException {&nbsp; &nbsp; return Collections.list(NetworkInterface.getNetworkInterfaces()).stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(NetworkInterface::getInterfaceAddresses)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .flatMap(Collection::stream)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(InterfaceAddress::getAddress)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .anyMatch(((Predicate<InetAddress>) InetAddress::isLoopbackAddress).negate().and(address -> address instanceof Inet6Address));}

胡说叔叔

如果您希望以更实用的方式实现上述功能,您可以查看这个小助手方法。尽管使用了流、函数和 lambda 表达式,但它确实执行了上述操作。private static boolean supportsIPv6() throws SocketException {&nbsp; &nbsp; return Stream.of(NetworkInterface.getNetworkInterfaces().nextElement())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(NetworkInterface::getInterfaceAddresses)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.flatMap(Collection::stream)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(InterfaceAddress::getAddress)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.anyMatch(((Predicate<InetAddress>) InetAddress::isLoopbackAddress).negate().and(address -> address instanceof Inet6Address));}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java