Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion IPv6 to long and long to IPv6

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)

like image 249
Testeross Avatar asked Jul 26 '13 07:07

Testeross


1 Answers

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)
}
like image 182
Guigoz Avatar answered Sep 25 '22 21:09

Guigoz