ipaddr.js icon indicating copy to clipboard operation
ipaddr.js copied to clipboard

CIDR parsing fails to apply mask.

Open haight6716 opened this issue 5 years ago • 1 comments

While writing tests for that other issue I ran into this one - shouldn't this pass?

assert.equal(ipaddr.IPv4.parseCIDR('8.3.4.8/24').toString(), '8.3.4.0/24');

Admittedly it's invalid input, but shouldn't we silently fix it or throw? Instead, we produce invalid output.

haight6716 avatar Jul 31 '20 22:07 haight6716

This is because it parses the IP and CIDR separately. CIDR is used for checking through another function.

The octets stored is the one used from parsing the IP address irregardless of the existence of CIDR, thus toString will only return the parsed IP address, and if CIDR was given, then appends it afterwards.

You'll need to use the match function to test for CIDR (which only exists when using the parse function, not parseCIDR.

so

ipaddr.IPv4.parse('8.3.4.8').match(ipaddr.IPv4.parseCIDR('8.3.4.0/24'))

or

ipaddr.IPv4.parse('8.3.4.8').match(ipaddr.parse('8.3.4.0'), 24)

or

ipaddr.IPv4.parse('8.3.4.0').match(ipaddr.parse('8.3.4.8'), 24)

or

const test = ipaddr.IPv4.parseCIDR('8.3.4.8/24');
ipaddr.IPv4.parse('8.3.4.0').match(test[0], test[1]);

The parser doesn't know about any CIDR notations. It is only passed in the IP address string (without CIDR) for parsing. This is the same if you use parseCIDR, as it send everything before the slash to the parser for IP Address.

kennethtran93 avatar Aug 01 '20 06:08 kennethtran93