mirror of https://github.com/lukechilds/node.git
Browse Source
This patch adds support for CIDR notation to the output of the `networkInterfaces()` method PR-URL: https://github.com/nodejs/node/pull/14307 Fixes: https://github.com/nodejs/node/issues/14006 Reviewed-By: Roman Reiss <me@silverwind.io> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Refael Ackermann <refack@gmail.com> Reviewed-By: Timothy Gu <timothygu99@gmail.com>v6
Mudit Ameta
7 years ago
committed by
Refael Ackermann
6 changed files with 125 additions and 7 deletions
@ -0,0 +1,41 @@ |
|||
'use strict'; |
|||
|
|||
function getCIDRSuffix(mask, protocol = 'ipv4') { |
|||
const isV6 = protocol === 'ipv6'; |
|||
const bitsString = mask |
|||
.split(isV6 ? ':' : '.') |
|||
.filter((v) => !!v) |
|||
.map((v) => pad(parseInt(v, isV6 ? 16 : 10).toString(2), isV6)) |
|||
.join(''); |
|||
|
|||
if (isValidMask(bitsString)) { |
|||
return countOnes(bitsString); |
|||
} else { |
|||
return null; |
|||
} |
|||
} |
|||
|
|||
function pad(binaryString, isV6) { |
|||
const groupLength = isV6 ? 16 : 8; |
|||
const binLen = binaryString.length; |
|||
|
|||
return binLen < groupLength ? |
|||
`${'0'.repeat(groupLength - binLen)}${binaryString}` : binaryString; |
|||
} |
|||
|
|||
function isValidMask(bitsString) { |
|||
const firstIndexOfZero = bitsString.indexOf(0); |
|||
const lastIndexOfOne = bitsString.lastIndexOf(1); |
|||
|
|||
return firstIndexOfZero < 0 || firstIndexOfZero > lastIndexOfOne; |
|||
} |
|||
|
|||
function countOnes(bitsString) { |
|||
return bitsString |
|||
.split('') |
|||
.reduce((acc, bit) => acc += parseInt(bit, 10), 0); |
|||
} |
|||
|
|||
module.exports = { |
|||
getCIDRSuffix |
|||
}; |
@ -0,0 +1,32 @@ |
|||
// Flags: --expose-internals
|
|||
'use strict'; |
|||
|
|||
require('../common'); |
|||
const assert = require('assert'); |
|||
const getCIDRSuffix = require('internal/os').getCIDRSuffix; |
|||
|
|||
const specs = [ |
|||
// valid
|
|||
['128.0.0.0', 'ipv4', 1], |
|||
['255.0.0.0', 'ipv4', 8], |
|||
['255.255.255.128', 'ipv4', 25], |
|||
['255.255.255.255', 'ipv4', 32], |
|||
['ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', 'ipv6', 128], |
|||
['ffff:ffff:ffff:ffff::', 'ipv6', 64], |
|||
['ffff:ffff:ffff:ff80::', 'ipv6', 57], |
|||
// invalid
|
|||
['255.0.0.1', 'ipv4', null], |
|||
['255.255.9.0', 'ipv4', null], |
|||
['255.255.1.0', 'ipv4', null], |
|||
['ffff:ffff:43::', 'ipv6', null], |
|||
['ffff:ffff:ffff:1::', 'ipv6', null] |
|||
]; |
|||
|
|||
specs.forEach(([mask, protocol, expectedSuffix]) => { |
|||
const actualSuffix = getCIDRSuffix(mask, protocol); |
|||
|
|||
assert.strictEqual( |
|||
actualSuffix, expectedSuffix, |
|||
`Mask: ${mask}, expected: ${expectedSuffix}, actual: ${actualSuffix}` |
|||
); |
|||
}); |
Loading…
Reference in new issue