Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Library for converting a long IPv6 address into its compressed form

Tags:

java

ipv6

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?

like image 218
leifg Avatar asked Sep 21 '10 13:09

leifg


2 Answers

java-ipv6 is a very decent library for that. It also handles address ranges well.

like image 169
Hans-Peter Störr Avatar answered Sep 18 '22 00:09

Hans-Peter Störr


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.

like image 32
James Van Huis Avatar answered Sep 19 '22 00:09

James Van Huis