diff --git a/lib/net.js b/lib/net.js index b446e218478f78..cf48edb0274cc7 100644 --- a/lib/net.js +++ b/lib/net.js @@ -785,9 +785,10 @@ Socket.prototype._getpeername = function() { if (!this._handle || !this._handle.getpeername || this.connecting) { return this._peername || {}; } else if (!this._peername) { - this._peername = {}; - // FIXME(bnoordhuis) Throw when the return value is not 0? - this._handle.getpeername(this._peername); + const out = {}; + const err = this._handle.getpeername(out); + if (err) return out; + this._peername = out; } return this._peername; }; diff --git a/test/parallel/test-net-remote-address.js b/test/parallel/test-net-remote-address.js new file mode 100644 index 00000000000000..a116cb99d3bcab --- /dev/null +++ b/test/parallel/test-net-remote-address.js @@ -0,0 +1,23 @@ +'use strict'; + +const common = require('../common'); +const net = require('net'); +const { strictEqual } = require('assert'); + +const server = net.createServer(); + +server.listen(common.mustCall(function() { + const socket = net.connect({ port: server.address().port }); + + strictEqual(socket.connecting, true); + strictEqual(socket.remoteAddress, undefined); + + socket.on('connect', common.mustCall(function() { + strictEqual(socket.remoteAddress !== undefined, true); + socket.end(); + })); + + socket.on('end', common.mustCall(function() { + server.close(); + })); +}));