From 81e1f54157a4104017a4ae36734b2181c2f2b2d1 Mon Sep 17 00:00:00 2001 From: Terry Chen Date: Thu, 30 Apr 2026 17:07:58 -0400 Subject: [PATCH] net: preserve port 80 in SocketAddress.parse Fixes: https://github.com/nodejs/node/issues/62906 Signed-off-by: Terry Chen --- lib/internal/socketaddress.js | 14 ++++++++++++-- test/parallel/test-socketaddress.js | 4 ++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/internal/socketaddress.js b/lib/internal/socketaddress.js index 724ffd90cf77f1..812e28c9347073 100644 --- a/lib/internal/socketaddress.js +++ b/lib/internal/socketaddress.js @@ -42,6 +42,15 @@ const { URLParse } = require('internal/url'); const kHandle = Symbol('kHandle'); const kDetail = Symbol('kDetail'); +function getSocketAddressPort(input, port) { + if (port !== '') { + return port; + } + // HTTP URLs omit explicit default ports such as ":80". SocketAddress input + // has no default port, so use a scheme without a default port here. + return URLParse(`socket://${input}`).port; +} + class SocketAddress { static isSocketAddress(value) { return value?.[kHandle] !== undefined; @@ -157,14 +166,15 @@ class SocketAddress { hostname: address, port, } = URLParse(`http://${input}`); + const addressPort = getSocketAddressPort(input, port) | 0; if (address.startsWith('[') && address.endsWith(']')) { return new SocketAddress({ address: address.slice(1, -1), - port: port | 0, + port: addressPort, family: 'ipv6', }); } - return new SocketAddress({ address, port: port | 0 }); + return new SocketAddress({ address, port: addressPort }); } catch { // Ignore errors here. Return undefined if the input cannot // be successfully parsed or is not a proper socket address. diff --git a/test/parallel/test-socketaddress.js b/test/parallel/test-socketaddress.js index cf29795a48fcfa..474783f1674877 100644 --- a/test/parallel/test-socketaddress.js +++ b/test/parallel/test-socketaddress.js @@ -141,12 +141,16 @@ describe('net.SocketAddress...', () => { it('SocketAddress.parse() works as expected', () => { const good = [ { input: '1.2.3.4', address: '1.2.3.4', port: 0, family: 'ipv4' }, + { input: '1.2.3.4:80', address: '1.2.3.4', port: 80, family: 'ipv4' }, + { input: '1.2.3.4:080', address: '1.2.3.4', port: 80, family: 'ipv4' }, { input: '192.168.257:1', address: '192.168.1.1', port: 1, family: 'ipv4' }, { input: '256', address: '0.0.1.0', port: 0, family: 'ipv4' }, + { input: '999999999:80', address: '59.154.201.255', port: 80, family: 'ipv4' }, { input: '999999999:12', address: '59.154.201.255', port: 12, family: 'ipv4' }, { input: '0xffffffff', address: '255.255.255.255', port: 0, family: 'ipv4' }, { input: '0x.0x.0', address: '0.0.0.0', port: 0, family: 'ipv4' }, { input: '[1:0::]', address: '1::', port: 0, family: 'ipv6' }, + { input: '[1::8]:80', address: '1::8', port: 80, family: 'ipv6' }, { input: '[1::8]:123', address: '1::8', port: 123, family: 'ipv6' }, ];