3

Is there a way to check in Java if the network a computer is capable of handling IPv6 connections? 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.

3 Answers 3

4

Yes; you can just loop through interfaces and check whether any of them have an IPv6 address that is not a loop-back.

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;
0
2

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

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.

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

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.