From ad91cf721a893413e3e0c8bbac192ad02b31ecda Mon Sep 17 00:00:00 2001 From: Daeyeon Jeong Date: Mon, 25 Jul 2022 17:09:49 +0900 Subject: [PATCH] net: fix socket._getpeername Fixes: https://github.com/nodejs/node/issues/43009 If calling `this._handle.getpeername` returns an error at the first call, its result shouldn't be cached to `this._peername`. Signed-off-by: Daeyeon Jeong daeyeon.dev@gmail.com PR-URL: https://github.com/nodejs/node/pull/43010 Reviewed-By: Paolo Insogna Reviewed-By: Matteo Collina Reviewed-By: Zeyu "Alex" Yang --- lib/net.js | 7 ++++--- test/parallel/test-net-remote-address.js | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 test/parallel/test-net-remote-address.js diff --git a/lib/net.js b/lib/net.js index 9670a662a99..e3d490ceed8 100644 --- a/lib/net.js +++ b/lib/net.js @@ -785,9 +785,10 @@ Socket.prototype._getpeername = function() { if (!this._handle || !this._handle.getpeername) { 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 00000000000..a116cb99d3b --- /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(); + })); +}));