I would like to know, whether there is a library which I can use to convert a represenation of a long IPv6 address (such as 2002:9876:57AB:0000:0000:0000:0000:0001) into the compressed IPv6 form (in this case: 2002:9876:57AB::1).
I was not able to find such a library. This library should not use any IP Api, a network connection must not be made.
I already tried
return Inet6Address.getByName(longAdress).toString();
but this just replaces the 4 zeros with 1 zero (in this case 2002:9876:57AB:0:0:0:0:1).
any suggestions?
java-ipv6 is a very decent library for that. It also handles address ranges well.
public class Ipv6AddressCompressor {
public static String getCompressedAddress(String longAddress) throws UnknownHostException {
longAddress = Inet6Address.getByName(longAddress).getHostAddress();
return longAddress.replaceFirst("(^|:)(0+(:|$)){2,8}", "::");
}
}
This should protect you against invalid addresses (throws the UnknownHostException), and will properly compress trailing ipv4 addresses (i.e. 0:0:0:0:0:0:255.255.255.255 -> ::FFFF:FFFF). This will also protect against already compressed addresses.
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