Skip to content

Commit 1738c96

Browse files
rmgrvagg
authored andcommitted
net: ensure Socket reported address is current
Any time the connection state or the underlying handle itself changes, the socket's name (aka, local address) can change. To deal with this we need to reset the cached sockname any time we set or unset the internal handle or an existing handle establishes a connection. PR-URL: #2095 Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: Jeremiah Senkpiel <[email protected]>
1 parent cf9ba81 commit 1738c96

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

lib/net.js

+4
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ function initSocketHandle(self) {
9393
self.destroyed = false;
9494
self.bytesRead = 0;
9595
self._bytesDispatched = 0;
96+
self._sockname = null;
9697

9798
// Handle creation may be deferred to bind() or connect() time.
9899
if (self._handle) {
@@ -469,6 +470,7 @@ Socket.prototype._destroy = function(exception, cb) {
469470
});
470471
this._handle.onread = noop;
471472
this._handle = null;
473+
this._sockname = null;
472474
}
473475

474476
// we set destroyed to true before firing error callbacks in order
@@ -871,6 +873,7 @@ Socket.prototype.connect = function(options, cb) {
871873
this.destroyed = false;
872874
this._handle = null;
873875
this._peername = null;
876+
this._sockname = null;
874877
}
875878

876879
var self = this;
@@ -1032,6 +1035,7 @@ function afterConnect(status, handle, req, readable, writable) {
10321035

10331036
assert.ok(self._connecting);
10341037
self._connecting = false;
1038+
self._sockname = null;
10351039

10361040
if (status == 0) {
10371041
self.readable = readable;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'use strict';
2+
var common = require('../common');
3+
var assert = require('assert');
4+
var net = require('net');
5+
6+
var conns = 0;
7+
var clientLocalPorts = [];
8+
var serverRemotePorts = [];
9+
10+
var server = net.createServer(function(socket) {
11+
serverRemotePorts.push(socket.remotePort);
12+
conns++;
13+
});
14+
15+
var client = new net.Socket();
16+
17+
server.on('close', function() {
18+
assert.deepEqual(clientLocalPorts, serverRemotePorts,
19+
'client and server should agree on the ports used');
20+
assert.equal(2, conns);
21+
});
22+
23+
server.listen(common.PORT, common.localhostIPv4, testConnect);
24+
25+
function testConnect() {
26+
if (conns == 2) {
27+
return server.close();
28+
}
29+
client.connect(common.PORT, common.localhostIPv4, function() {
30+
clientLocalPorts.push(this.localPort);
31+
this.once('close', testConnect);
32+
this.destroy();
33+
});
34+
}

0 commit comments

Comments
 (0)