diff --git a/lib/internal/validators.js b/lib/internal/validators.js index 110b045a063460..56b26d6292261d 100644 --- a/lib/internal/validators.js +++ b/lib/internal/validators.js @@ -428,7 +428,7 @@ const validatePort = hideStackFrames((port, name = 'Port', allowZero = true) => (typeof port === 'string' && StringPrototypeTrim(port).length === 0) || +port !== (+port >>> 0) || port > 0xFFFF || - (port === 0 && !allowZero)) { + (+port === 0 && !allowZero)) { throw new ERR_SOCKET_BAD_PORT(name, port, allowZero); } return port | 0; diff --git a/test/parallel/test-dgram-connect.js b/test/parallel/test-dgram-connect.js index 30e817f344a42c..8d2d78652366af 100644 --- a/test/parallel/test-dgram-connect.js +++ b/test/parallel/test-dgram-connect.js @@ -55,7 +55,7 @@ assert.throws(() => { code: 'ERR_SOCKET_DGRAM_NOT_CONNECTED' }); -[ 0, null, 78960, undefined ].forEach((port) => { +[ 0, '0', null, 78960, undefined ].forEach((port) => { assert.throws(() => { client.connect(port); }, { diff --git a/test/parallel/test-internal-validators-validateport.js b/test/parallel/test-internal-validators-validateport.js index a4c92b8dbca929..aad6ac926e71df 100644 --- a/test/parallel/test-internal-validators-validateport.js +++ b/test/parallel/test-internal-validators-validateport.js @@ -21,3 +21,10 @@ for (let n = 0; n <= 0xFFFF; n++) { ].forEach((i) => assert.throws(() => validatePort(i), { code: 'ERR_SOCKET_BAD_PORT' })); + +// When `allowZero` is false, both the number `0` and the string `'0'` (and +// other numeric-zero string forms) must be rejected. +[0, '0', '0x0', '0o0', '0b0'].forEach((i) => assert.throws( + () => validatePort(i, 'Port', false), + { code: 'ERR_SOCKET_BAD_PORT' }, +));