Skip to content

Commit

Permalink
net: Ensure consistent binding to IPV6 if address is absent
Browse files Browse the repository at this point in the history
See nodejs#7675
net.server.listen() behaves inconsistently depending on whether the port
number is provided.

1. port === 0 && host == '' (i.e. false-y), node creates an AF_INET
socket but does not call bind().

2. port > 0 && host == '', node creates an AF_INET6 socket and calls
bind().

The fix makes 1 consistent with 2.
  • Loading branch information
Raymond Feng committed May 23, 2014
1 parent 1bbb3cc commit 2973c4d
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/net.js
Original file line number Diff line number Diff line change
Expand Up @@ -1091,6 +1091,14 @@ var createServerHandle = exports._createServerHandle =
} else {
err = handle.bind(address, port);
}
} else {
// Try binding to ipv6 first
err = handle.bind6('::', port);
if (err) {
handle.close();
// Fallback to ipv4
return createServerHandle('0.0.0.0', port);
}
}

if (err) {
Expand Down
42 changes: 42 additions & 0 deletions test/simple/test-net-server-address.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,45 @@ server_ipv6.listen(common.PORT, localhost_ipv6, function() {
assert.strictEqual(address_ipv6.family, family_ipv6);
server_ipv6.close();
});

// Test without hostname or ip
var anycast_ipv6 = '::';
var server = net.createServer();

server.on('error', function(e) {
console.log('Error on ip socket: ' + e.toString());
});

// Specify the port number
server.listen(common.PORT, function() {
var address = server.address();
assert.strictEqual(address.address, anycast_ipv6);
assert.strictEqual(address.port, common.PORT);
assert.strictEqual(address.family, family_ipv6);
server.close();

// Don't specify the port number
server.listen(function() {
var address = server.address();
assert.strictEqual(address.address, anycast_ipv6);
assert.strictEqual(address.family, family_ipv6);
server.close();

// Specify a false-y port number
server.listen(0, function() {
var address = server.address();
assert.strictEqual(address.address, anycast_ipv6);
assert.strictEqual(address.family, family_ipv6);
server.close();

// Specify -1 as port number
server.listen(-1, function() {
var address = server.address();
assert.strictEqual(address.address, anycast_ipv6);
assert.strictEqual(address.family, family_ipv6);
server.close();
});

});
});
});

0 comments on commit 2973c4d

Please sign in to comment.