Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions lib/ipaddr.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,30 @@
return true;
}

function matchLength(first, second) {
if (first.length !== second.length) {
throw new Error('ipaddr: cannot matchLength for objects with different lengths');
}
let offset = 0 ;
let length = 0 ;
while (offset < first.length && first[offset] == second[offset]) {
offset++ ;
length += 8 ;
}
let bit = 0x80 ;
let index = 0 ;
if (offset < first.length) {
let a = first[offset] ;
let b = second[offset] ;
while (index < 8 && (a & bit) == (b & bit)) {
index ++ ;
bit = bit >> 1 ;
}
return length + index ;
} else
return length ;
}

function parseIntAuto (string) {
// Hexadedimal base 16 (0x#)
if (hexRegex.test(string)) {
Expand Down Expand Up @@ -240,6 +264,15 @@
return matchCIDR(this.octets, other.octets, 8, cidrRange);
};

IPv4.prototype.commonPrefixLength = function (other) {
if (other.kind() !== 'ipv4') {
throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one');
throw new Error('ipaddr: cannot match ipv4 address with non-ipv4 one');

}

return matchLength(this.toByteArray(), other.toByteArray()) ;
}


// returns a number of leading ones in IPv4 address, making sure that
// the rest is a solid sequence of 0's (valid netmask)
// returns either the CIDR length or null if mask is not valid
Expand Down Expand Up @@ -602,6 +635,14 @@
return matchCIDR(this.parts, other.parts, 16, cidrRange);
};

IPv6.prototype.commonPrefixLength = function (other) {
if (other.kind() !== 'ipv6') {
throw new Error('ipaddr: cannot match ipv6 address with non-ipv6 one');
}

return matchLength(this.toByteArray(), other.toByteArray()) ;
}

// returns a number of leading ones in IPv6 address, making sure that
// the rest is a solid sequence of 0's (valid netmask)
// returns either the CIDR length or null if mask is not valid
Expand Down