Skip to content

Commit caeee38

Browse files
sam-githubMylesBorins
authored andcommitted
net: support passing undefined to listen()
For consistency with 4.x and 8.x. This commit also contains a forward port of #14232 to confirm that 4.x and 6.x behave identically with respect to the port argument. Backport-PR-URL: #14234 PR-URL: #14234 Refs: #14205 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Sam Roberts <[email protected]>
1 parent 1aac05b commit caeee38

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

lib/net.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1342,7 +1342,7 @@ Server.prototype.listen = function() {
13421342
self.once('listening', lastArg);
13431343
}
13441344

1345-
var port = toNumber(arguments[0]);
1345+
var port = typeof arguments[0] === 'undefined' ? 0 : toNumber(arguments[0]);
13461346

13471347
// The third optional argument is the backlog size.
13481348
// When the ip is omitted it can be the second argument.

test/parallel/test-net-listen-port-option.js

+44
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,47 @@ net.Server().listen({ port: '' + common.PORT }, close);
2626
net.Server().listen({ port: port }, common.fail);
2727
}, /invalid listen argument/i);
2828
});
29+
30+
// Repeat the tests, passing port as an argument, which validates somewhat
31+
// differently.
32+
33+
net.Server().listen(undefined, close);
34+
net.Server().listen('0', close);
35+
36+
// 'nan', skip, treated as a path, not a port
37+
//'+Infinity', skip, treated as a path, not a port
38+
//'-Infinity' skip, treated as a path, not a port
39+
40+
// 4.x treats these as 0, but 6.x treats them as invalid numbers.
41+
[
42+
-1,
43+
123.456,
44+
0x10000,
45+
1 / 0,
46+
-1 / 0,
47+
].forEach(function(port) {
48+
assert.throws(function() {
49+
net.Server().listen(port, common.fail);
50+
}, /"port" argument must be >= 0 and < 65536/i);
51+
});
52+
53+
// null is treated as 0
54+
net.Server().listen(null, close);
55+
56+
// false/true are converted to 0/1, arguably a bug, but fixing would be
57+
// semver-major. Note that true fails when port 1 low can't be listened on by
58+
// unprivileged processes (Linux) but the listen does succeed on some Windows
59+
// versions.
60+
net.Server().listen(false, close);
61+
62+
(function() {
63+
const done = common.mustCall(function(err) {
64+
if (err)
65+
return assert.strictEqual(err.code, 'EACCES');
66+
67+
assert.strictEqual(this.address().port, 1);
68+
this.close();
69+
});
70+
71+
net.Server().listen(true).on('error', done).on('listening', done);
72+
})();

0 commit comments

Comments
 (0)