Skip to content

Commit

Permalink
add IPv6 prefixLengthFromSubnetMask
Browse files Browse the repository at this point in the history
Fixes #59
  • Loading branch information
silverwind authored and whitequark committed Jul 4, 2017
1 parent 9e22317 commit 9a275c3
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 4 deletions.
2 changes: 1 addition & 1 deletion ipaddr.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 41 additions & 0 deletions lib/ipaddr.js
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,47 @@
return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);
};

IPv6.prototype.prefixLengthFromSubnetMask = function() {
var cidr, i, k, part, stop, zeros, zerotable;
zerotable = {
0: 16,
32768: 15,
49152: 14,
57344: 13,
61440: 12,
63488: 11,
64512: 10,
65024: 9,
65280: 8,
65408: 7,
65472: 6,
65504: 5,
65520: 4,
65528: 3,
65532: 2,
65534: 1,
65535: 0
};
cidr = 0;
stop = false;
for (i = k = 7; k >= 0; i = k += -1) {
part = this.parts[i];
if (part in zerotable) {
zeros = zerotable[part];
if (stop && zeros !== 0) {
return null;
}
if (zeros !== 16) {
stop = true;
}
cidr += zeros;
} else {
return null;
}
}
return 128 - cidr;
};

return IPv6;

})();
Expand Down
40 changes: 40 additions & 0 deletions src/ipaddr.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,46 @@ class ipaddr.IPv6

return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff])

# 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
prefixLengthFromSubnetMask: ->
# number of zeroes in octet
zerotable =
0 : 16
32768: 15
49152: 14
57344: 13
61440: 12
63488: 11
64512: 10
65024: 9
65280: 8
65408: 7
65472: 6
65504: 5
65520: 4
65528: 3
65532: 2
65534: 1
65535: 0

cidr = 0
# non-zero encountered stop scanning for zeroes
stop = false
for i in [7..0] by -1
part = @parts[i]
if part of zerotable
zeros = zerotable[part]
if stop and zeros != 0
return null
unless zeros == 16
stop = true
cidr += zeros
else
return null
return 128 - cidr

# IPv6-matching regular expressions.
# For IPv6, the task is simpler: it is enough to match the colon-delimited
# hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at
Expand Down
Loading

0 comments on commit 9a275c3

Please sign in to comment.