这里只讨论IPv6转成整形,整形到IPv6请见《Nodejs: 整形数字转IPv6》
IPv6的解析与转换目前最方便的做法是使用第三方包ip-address将IPv6转换成jsbn.BigInteger。经测试,在nodejs 4.6,8.16,10.4等三个版本上都能正常使用。
npm install ip-address
如果要自己写的话,因为IPv6支持0的压缩表示以及对IPv4的兼容,所以解析是比较麻烦的,另一个比较麻烦的原因是IpV6是128bit,必须用BigInt才能保存,而nodejs从v10.4.1才开始支持BigInt,一般的数字类型不能用的原因是会被表示为科学计数法,而且后面若干位会被置为0。
示例:
var Address6 = require('ip-address').Address6;
//参数:ipv6str字符串
//返回:jsbn.BigInteger的一个实例
var Ipv6ToBigInt = function (ipv6str) {
var address = new Address6(ipv6str);
if (address.isValid() == false) {
throw new Error("invalid ipv6")
}
return address.bigInteger();
};
var convert = function (ipv6str) {
try {
var addr = Ipv6ToBigInt(ipv6str);
console.log(ipv6str + " -> " + addr.toString());
} catch (err) {
console.log(ipv6str + " -> " + err);
}
};
var addr1 = Ipv6ToBigInt("2001:024f:ffff:ffff:ffff:ffff:ffff:fff1");
var addr2 = Ipv6ToBigInt("2001:024f:ffff:ffff:ffff:ffff:ffff:fff4");
console.log("addr1:" + addr1.toString());
console.log("addr2:" + addr2.toString());
console.log("addr1 < addr2:" + (addr1.compareTo(addr2) < 0));
console.log("addr1 > addr2:" + (addr1.compareTo(addr2) > 0));
console.log("\n特殊情况,包括0压缩和IPv4的映射到IPv6");
convert("::");
convert("2001::");
convert("::2001");
convert("2001:024f::ffff:ffff:fff4");
convert("::ffff:10.2.3.45");
convert("::10.2.3.45");
convert("::a02:32d");
console.log("\n非法ipv6");
convert("10.2.3.45");
convert("2001:024f::ffff::ffff:fff4");
convert("2001:024f::ffff:ffff:fff41");
convert("2001:024f:ffff:fff4");
console.log("\nipv6查看字节");
var address = new Address6("2001:024f::ffff:ffff:ffff:fffa");
console.log(address.toUnsignedByteArray());
输出:
addr1:42540535065048051205038211803318845425
addr2:42540535065048051205038211803318845428
addr1 < addr2:true
addr1 > addr2:false
特殊情况,包括0压缩和IPv4的映射到IPv6
:: -> 0
2001:: -> 42540488161975842760550356425300246528
::2001 -> 8193
2001:024f::ffff:ffff:fff4 -> 42540534985819888690774155684751605748
::ffff:10.2.3.45 -> 281470849647405
::10.2.3.45 -> 167904045
::a02:32d -> 167904045
非法ipv6
10.2.3.45 -> Error: invalid ipv6
2001:024f::ffff::ffff:fff4 -> Error: invalid ipv6
2001:024f::ffff:ffff:fff41 -> Error: invalid ipv6
2001:024f:ffff:fff4 -> Error: invalid ipv6
ipv6查看字节
[ 32, 1, 2, 79, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 250 ]