Skip to content

Commit cf05257

Browse files
committed
Test for server.listen() more carefully, fix bug
1 parent a01e095 commit cf05257

File tree

3 files changed

+58
-27
lines changed

3 files changed

+58
-27
lines changed

lib/net.js

+9-8
Original file line numberDiff line numberDiff line change
@@ -1075,8 +1075,15 @@ Server.prototype.listen = function () {
10751075
self.addListener('listening', lastArg);
10761076
}
10771077

1078-
var port = toPort(arguments[0] != lastArg ? arguments[0] : null);
1079-
if (port === false) {
1078+
var port = toPort(arguments[0]);
1079+
1080+
if (arguments.length == 0 || typeof arguments[0] == 'function') {
1081+
// Don't bind(). OS will assign a port with INADDR_ANY.
1082+
// The port can be found with server.address()
1083+
self.type = 'tcp4';
1084+
self.fd = socket(self.type);
1085+
self._doListen(port);
1086+
} else if (port === false) {
10801087
// the first argument specifies a path
10811088
self.fd = socket('unix');
10821089
self.type = 'unix';
@@ -1101,12 +1108,6 @@ Server.prototype.listen = function () {
11011108
}
11021109
}
11031110
});
1104-
} else if (!arguments[1]) {
1105-
// Don't bind(). OS will assign a port with INADDR_ANY.
1106-
// The port can be found with server.address()
1107-
self.type = 'tcp4';
1108-
self.fd = socket(self.type);
1109-
self._doListen(port);
11101111
} else {
11111112
// the first argument is the port, the second an IP
11121113
require('dns').lookup(arguments[1], function (err, ip, addressType) {

test/simple/test-net-server-bind.js

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
var common = require('../common');
2+
var assert = require('assert');
3+
var net = require('net');
4+
5+
6+
// With only a callback, server should get a port assigned by the OS
7+
8+
var address0;
9+
var server0 = net.createServer(function (socket) { });
10+
11+
server0.listen(function() {
12+
address0 = server0.address();
13+
console.log("address0 %j", address0);
14+
server0.close();
15+
});
16+
17+
18+
// No callback to listen(), assume we can bind in 100 ms
19+
20+
var address1;
21+
var server1 = net.createServer(function(socket) { });
22+
23+
server1.listen(common.PORT);
24+
25+
setTimeout(function () {
26+
address1 = server1.address()
27+
console.log("address1 %j", address1);
28+
server1.close();
29+
}, 100);
30+
31+
32+
// Callback to listen()
33+
34+
var address2;
35+
var server2 = net.createServer(function(socket) { });
36+
37+
server2.listen(common.PORT+1, function () {
38+
address2 = server2.address()
39+
console.log("address2 %j", address2);
40+
server2.close();
41+
});
42+
43+
44+
45+
process.on('exit', function () {
46+
assert.ok(address0.port > 100);
47+
assert.equal(common.PORT, address1.port);
48+
assert.equal(common.PORT+1, address2.port);
49+
});

test/simple/test-net-server-listen-assigned-port.js

-19
This file was deleted.

0 commit comments

Comments
 (0)