From 9aef414b73c2d211b8b7fa692feedc0a8dda0b4d 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 d6e0ad679fd5ea..a67dda1309c722 100644 --- a/lib/net.js +++ b/lib/net.js @@ -780,9 +780,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(); + })); +}));