简体   繁体   English

JavaScript如何测试一个IPv6地址是否大于另一个?

[英]JavaScript how to test if one IPv6 address is larger than another?

Given two IPv6 addresses in string format ie "2001:0db8:0000:0000:0000:ff00:0042:8328" and "2001:0db8:0000:0000:0000:ff00:0042:8329" 给定两个字符串格式的IPv6地址,即“2001:0db8:0000:0000:0000:ff00:0042:8328”和“2001:0db8:0000:0000:0000:ff00:0042:8329”

how can I test if one is larger than the other? 如何测试一个是否大于另一个? IPv4 was easy, convert into an integer value and compare, but IPv6 numbers are so large this becomes unfeasable. IPv4很容易,转换成整数值并进行比较,但IPv6数字太大,这变得无法实现。

Replace the address by ":" transform individually each term as hexadecimal value. 用“:”替换地址,将每个术语单独转换为十六进制值。

Compare the final result of each string. 比较每个字符串的最终结果。

function toHex(str) {
    var hex = '';
    for(var i=0;i<str.length;i++) {
        hex += ''+str.charCodeAt(i).toString(16);
    }
    return hex;
}

Remove : and do a hexa compare for the entire string. 删除:并对整个字符串执行hexa比较。

var first = "2001:0db8:0000:0000:0000:ff00:0042:8328".replace(/:/g, "");
var second = "2001:0db8:0000:0000:0000:ff00:0042:8329".replace(/:/g, "");

// compare

如果你不介意使用第三方库,那就是ip-address

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM