简体   繁体   English

Java 中的 IPv6 可用性

[英]IPv6 Availability in Java

Is there a way to check in Java if the network a computer is capable of handling IPv6 connections?如果计算机网络能够处理 IPv6 连接,有没有办法检查 Java? I'm not asking how to check if a byte array is an IPv4 address or an IPv6, or if an InetAddress is one or the other, but how to tell if the network itself would support such a connection.我不是在问如何检查字节数组是 IPv4 地址还是 IPv6,或者 InetAddress 是其中之一,而是如何判断网络本身是否支持这种连接。

Yes;是的; you can just loop through interfaces and check whether any of them have an IPv6 address that is not a loop-back.您可以循环遍历接口并检查它们中是否有任何一个不是环回的 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;

The above functional version just the first interface, not iterates them all.上面的功能版本只是第一个接口,不是全部迭代。 To iterate them all:将它们全部迭代:

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));
}

If you want the above in a more functional way, you can check this little helper method.如果您希望以更实用的方式实现上述功能,您可以查看这个小助手方法。 It does precisely what the above does, albeit using streams, functions and lambdas.尽管使用了流、函数和 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));

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM