3 回答
TA贡献1836条经验 获得超13个赞
是的; 您可以循环遍历接口并检查它们中是否有任何一个不是环回的 IPv6 地址。
final Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
final Iterator<InterfaceAddress> e2 = e.nextElement().getInterfaceAddresses().iterator();
while (e2.hasNext()) {
final InetAddress ip = e2.next().getAddress();
if (ip.isLoopbackAddress() || ip instanceof Inet4Address){
continue;
}
return true;
}
}
return false;
TA贡献1862条经验 获得超6个赞
上面的功能版本只是第一个接口,不是全部迭代。将它们全部迭代:
private static boolean supportsIPv6() throws SocketException {
return Collections.list(NetworkInterface.getNetworkInterfaces()).stream()
.map(NetworkInterface::getInterfaceAddresses)
.flatMap(Collection::stream)
.map(InterfaceAddress::getAddress)
.anyMatch(((Predicate<InetAddress>) InetAddress::isLoopbackAddress).negate().and(address -> address instanceof Inet6Address));
}
TA贡献1804条经验 获得超8个赞
如果您希望以更实用的方式实现上述功能,您可以查看这个小助手方法。尽管使用了流、函数和 lambda 表达式,但它确实执行了上述操作。
private static boolean supportsIPv6() throws SocketException {
return Stream.of(NetworkInterface.getNetworkInterfaces().nextElement())
.map(NetworkInterface::getInterfaceAddresses)
.flatMap(Collection::stream)
.map(InterfaceAddress::getAddress)
.anyMatch(((Predicate<InetAddress>) InetAddress::isLoopbackAddress).negate().and(address -> address instanceof Inet6Address));
}
添加回答
举报