diff --git a/lib/net.js b/lib/net.js index 1c98cf4820178f..4318beb501b028 100644 --- a/lib/net.js +++ b/lib/net.js @@ -733,7 +733,7 @@ Socket.prototype._destroy = function(exception, cb) { }; Socket.prototype._getpeername = function() { - if (!this._handle || !this._handle.getpeername) { + if (!this._handle || !this._handle.getpeername || this.connecting) { return this._peername || {}; } else if (!this._peername) { this._peername = {}; @@ -760,7 +760,9 @@ protoGetter('remoteAddress', function remoteAddress() { }); protoGetter('remoteFamily', function remoteFamily() { - return `IPv${this._getpeername().family}`; + const { family } = this._getpeername(); + + return family ? `IPv${family}` : family; }); protoGetter('remotePort', function remotePort() { diff --git a/test/parallel/test-net-remote-address-port.js b/test/parallel/test-net-remote-address-port.js index f7162d0f90f933..615f22979c2ff9 100644 --- a/test/parallel/test-net-remote-address-port.js +++ b/test/parallel/test-net-remote-address-port.js @@ -53,6 +53,14 @@ const server = net.createServer(common.mustCall(function(socket) { server.listen(0, function() { const client = net.createConnection(this.address().port, '127.0.0.1'); const client2 = net.createConnection(this.address().port); + + assert.strictEqual(client.remoteAddress, undefined); + assert.strictEqual(client.remoteFamily, undefined); + assert.strictEqual(client.remotePort, undefined); + assert.strictEqual(client2.remoteAddress, undefined); + assert.strictEqual(client2.remoteFamily, undefined); + assert.strictEqual(client2.remotePort, undefined); + client.on('connect', function() { assert.ok(remoteAddrCandidates.includes(client.remoteAddress)); assert.ok(remoteFamilyCandidates.includes(client.remoteFamily));