Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPv6 Availability in Java

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.

like image 615
Lev Knoblock Avatar asked Apr 11 '26 12:04

Lev Knoblock


2 Answers

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;
like image 126
user1133275 Avatar answered Apr 14 '26 02:04

user1133275


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));
}
like image 33
Vladimir Kvashin Avatar answered Apr 14 '26 03:04

Vladimir Kvashin