简体   繁体   中英

IPv6 as a comparable JavaScript string?

Preamble

In the age of IPv4 things were easy, because an IPv4 address could be converted into a simple 32-bit integer and then used for all kinds of comparative calculations.

With IPv6 it is a bit more awkward, because for one thing, 128-bit integers are not natively supported by JavaScript, and their conversion isn't straightforward at all. Which only leaves the option of dealing with a string presentation for IPv6.

Question

How to convert an IPv6 address of any known format into a comparable string(s)?

Requirements

  1. For any comparable string, if address A precedes address B then condition A < B must produce true in JavaScript. Similar logic must be valid for the rest of comparisons: === , <= , > and >= .
  2. For each IPv6 there must be generated as many strings as necessary to cover every range within the address, ie Start Address + End Address for every range.

Conversion of simplified IPv6 address format to the full format is not too difficult. There are only 3 rules that allows addresses to be simplified. The following are the rules listed in the order they must be undone to convert the address back to the full format:

  1. Dotted-quad notation (IPv4 address embedded inside IPv6 address)

  2. Leading zeros may be omitted

  3. Groups of zeros may be abbreviated with ::

Technically, depending on how you do your processing, 2 and 3 may be swapped.

So here's a simple converter that only converts valid IPv6 addresses (it's guaranteed to fail miserably if you feed it invalid IPv6 address because I'm not doing any validation):

function full_IPv6 (ip_string) {
    // replace ipv4 address if any
    var ipv4 = ip_string.match(/(.*:)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$)/);
    if (ipv4) {
        var ip_string = ipv4[1];
        ipv4 = ipv4[2].match(/[0-9]+/g);
        for (var i = 0;i < 4;i ++) {
            var byte = parseInt(ipv4[i],10);
            ipv4[i] = ("0" + byte.toString(16)).substr(-2);
        }
        ip_string += ipv4[0] + ipv4[1] + ':' + ipv4[2] + ipv4[3];
    }

    // take care of leading and trailing ::
    ip_string = ip_string.replace(/^:|:$/g, '');

    var ipv6 = ip_string.split(':');

    for (var i = 0; i < ipv6.length; i ++) {
        var hex = ipv6[i];
        if (hex != "") {
            // normalize leading zeros
            ipv6[i] = ("0000" + hex).substr(-4);
        }
        else {
            // normalize grouped zeros ::
            hex = [];
            for (var j = ipv6.length; j <= 8; j ++) {
                hex.push('0000');
            }
            ipv6[i] = hex.join(':');
        }
    }

    return ipv6.join(':');
}

You can probably do the embedded IPv4 processing after the .split(':') but I've already written it with regexp in mind. As can be seen from the code above, each step of the process is fairly simple. The only thing that tripped me was an off-by-one error in the j<=8 condition in the last for loop.

您没有指出解决方案是否可接受第三方库,但如果可以,我相信您可以使用ip-address库及其依赖项jsbn将每个地址解析为v6对象,调用v6.bigInteger()以jsbn BigInteger对象的形式获取地址,然后使用BigInteger.compareTo比较地址。

Just convert an IPv6 address to four 32-bit unsigned integers and loop over the four integers. I do this all the time:

在此处输入图片说明

There are only two things you need for manipulating either IPv4 or IPv6 addresses: the address and the mask. Both of these are the same length per protocol (IPv4=32 bits, IPv6=128 bits). Since I don't have 128-bit unsigned integers, I use an array of four 32-bit unsigned integers for both the IPv6 address and mask. Everything else can be built from those two values.

IPv6 is even easier than IPv4 in finding the first and last addresses since, in IPv6, the first address is the subnet, and the last address is the subnet plus the inverse mask.

Use the ip6 npm package to normalize the IPv6 addresses and then compare them directly.

let ip6 = require('ip6')

console.log(ip6.normalize('2404:6800:4003:808::200e'));
// 2404:6800:4003:0808:0000:0000:0000:200e 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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