Search code examples
javaipipv6

How to normalise IPv6 address in Java?


Given a string which contains an IPv6 address in one of it's formats, is there a Java standart way to normalise it in a way that the same normalised value for different formats of the same address?
i.e

normalise("2001:db8:0:0:1:0:0:1") = x
normalise("2001:db8::1:0:0:1") = x
normalise("2001:db8:0:0:1::1") = x

Solution

  • You can achieve this easily by parsing the string with InetAddress.getByName(String) and then converting back to string with getHostAddress():

    public static String normalize(String s) throws UnknownHostException {
        return InetAddress.getByName(s).getHostAddress();
    }
    

    This method returns "2001:db8:0:0:1:0:0:1" for all your 3 examples.

    By the way: The code above can normalize IPv6 and IPv4 addresses.