tags:

views:

113

answers:

2

hello everyone,

i would like to know, whether there is a library which I can use to convert a represenation of a long IPv6 adress (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?

+2  A: 
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.

James Van Huis
Except it doesn't remove redundant zeros, e.g., `0000:0000:0001` should be `::1` but becomes `::0001` - fixable by doing something like `replaceAll("(:|^)0+(\\d)", "$1$2")` on the result, though.
gustafc
Good catch. Your \\d should be [0-9A-Fa-F] though. Will update to fix.
James Van Huis
A: 

I doubt it. Look at RFC5952

Msck