Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions lib/internal/socketaddress.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions test/parallel/test-socketaddress.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
];

Expand Down
Loading