Skip to content

Commit 3a14b7e

Browse files
committed
net: fix SocketAddress.parse default port handling
1 parent 5f92b6d commit 3a14b7e

2 files changed

Lines changed: 13 additions & 10 deletions

File tree

lib/internal/socketaddress.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
22

33
const {
4+
NumberParseInt,
45
ObjectSetPrototypeOf,
56
Symbol,
67
} = primordials;
@@ -153,18 +154,17 @@ class SocketAddress {
153154
// other pieces here that do... the destucturing, the SocketAddress
154155
// constructor, etc. So we wrap this in a try/catch to be safe.
155156
try {
156-
const {
157-
hostname: address,
158-
port,
159-
} = URLParse(`http://${input}`);
157+
// url.port strips default HTTP ports (e.g. 80), so parse the port from
158+
// the raw input string instead.
159+
const { hostname: address } = URLParse(`http://${input}`);
160160
if (address.startsWith('[') && address.endsWith(']')) {
161-
return new SocketAddress({
162-
address: address.slice(1, -1),
163-
port: port | 0,
164-
family: 'ipv6',
165-
});
161+
const portStart = input.indexOf(']:');
162+
const port = portStart !== -1 ? NumberParseInt(input.slice(portStart + 2), 10) || 0 : 0;
163+
return new SocketAddress({ address: address.slice(1, -1), port, family: 'ipv6' });
166164
}
167-
return new SocketAddress({ address, port: port | 0 });
165+
const lastColon = input.lastIndexOf(':');
166+
const port = lastColon !== -1 ? NumberParseInt(input.slice(lastColon + 1), 10) || 0 : 0;
167+
return new SocketAddress({ address, port });
168168
} catch {
169169
// Ignore errors here. Return undefined if the input cannot
170170
// be successfully parsed or is not a proper socket address.

test/parallel/test-socketaddress.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,9 @@ describe('net.SocketAddress...', () => {
148148
{ input: '0x.0x.0', address: '0.0.0.0', port: 0, family: 'ipv4' },
149149
{ input: '[1:0::]', address: '1::', port: 0, family: 'ipv6' },
150150
{ input: '[1::8]:123', address: '1::8', port: 123, family: 'ipv6' },
151+
{ input: '127.0.0.1:80', address: '127.0.0.1', port: 80, family: 'ipv4' },
152+
{ input: '127.0.0.1:443', address: '127.0.0.1', port: 443, family: 'ipv4' },
153+
{ input: '[::1]:80', address: '::1', port: 80, family: 'ipv6' },
151154
];
152155

153156
good.forEach((i) => {

0 commit comments

Comments
 (0)