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)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…