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.
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;
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With