IPv6 Address to Long
I have written code for converting coloned IPv6 IP address to BigInteger value in Java.
I have already written similar code for IPv4 IP address (see this post).
The function is useful when you compare IP addresses based on numeric magnitude relationship.
Java Code
public static BigInteger colonIpV6_to_BigInteger(String colonedIP) { String[] addrArray = colonedIP.split(":", -1); BigInteger num = BigInteger.ZERO; BigInteger block = BigInteger.valueOf(65536); for (int i = 0; i < addrArray.length; i++) { if(!addrArray[i].equals("")) { int power = 8-i; BigInteger value = BigInteger.valueOf(Long.parseLong(addrArray[i], 16) % 65536L); value = value.multiply(block.pow(power)); num = num.add(value); } } return num; }
Here is an example.
// following code output "22170076769632982771575277020213308075606016" System.out.println(colonIpV6_to_BigInteger("FE80:0000:0000:0000:0202:B3FF:FE1E:8329"));
コメント
"int power = 8-i;"
should be
"int power = 7-i;"
Anyways, great solution, thanks!
Jakub