Conversion IPv6 to long and long to IPv6

Testeross picture Testeross · Jul 26, 2013 · Viewed 22.2k times · Source

How should I perform conversion from IPv6 to long and vice versa?

So far I have:

    public static long IPToLong(String addr) {
            String[] addrArray = addr.split("\\.");
            long num = 0;
            for (int i = 0; i < addrArray.length; i++) {
                    int power = 3 - i;

                    num += ((Integer.parseInt(addrArray[i], 16) % 256 * Math.pow(256, power)));
            }
            return num;
    }

    public static String longToIP(long ip) {
            return ((ip >> 24) & 0xFF) + "."
                    + ((ip >> 16) & 0xFF) + "."
                    + ((ip >> 8) & 0xFF) + "."
                    + (ip & 0xFF);

    }

Is it correct solution or I missed something?

(It would be perfect if the solution worked for both ipv4 and ipv6)

Answer

Guigoz picture Guigoz · Jan 19, 2016

You can also use java.net.InetAddress
It works with both ipv4 and ipv6 (all formats)

public static BigInteger ipToBigInteger(String addr) {
    InetAddress a = InetAddress.getByName(addr)
    byte[] bytes = a.getAddress()
    return new BigInteger(1, bytes)
}