Skip to content

Commit 7b335f3

Browse files
committed
net: refactor logic branches
1 parent 5d23eb7 commit 7b335f3

1 file changed

Lines changed: 13 additions & 8 deletions

File tree

lib/internal/socketaddress.js

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -157,14 +157,19 @@ class SocketAddress {
157157
// url.port strips default HTTP ports (e.g. 80), so parse the port from
158158
// the raw input string instead.
159159
const { hostname: address } = URLParse(`http://${input}`);
160-
if (address.startsWith('[') && address.endsWith(']')) {
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' });
164-
}
165-
const lastColon = input.lastIndexOf(':');
166-
const port = lastColon !== -1 ? NumberParseInt(input.slice(lastColon + 1), 10) || 0 : 0;
167-
return new SocketAddress({ address, port });
160+
161+
const isIPv6 = address.startsWith('[') && address.endsWith(']');
162+
163+
// For IPv6, indexOf(']:') + 1 points at ':' (or 0 if absent, treated as no port).
164+
// For IPv4, lastIndexOf(':') points at ':' (or -1 if absent).
165+
const sepIdx = isIPv6 ? input.indexOf(']:') + 1 : input.lastIndexOf(':');
166+
const port = sepIdx > 0 ? NumberParseInt(input.slice(sepIdx + 1), 10) || 0 : 0;
167+
168+
return new SocketAddress({
169+
address: isIPv6 ? address.slice(1, -1) : address,
170+
port,
171+
family: isIPv6 ? 'ipv6' : 'ipv4',
172+
});
168173
} catch {
169174
// Ignore errors here. Return undefined if the input cannot
170175
// be successfully parsed or is not a proper socket address.

0 commit comments

Comments
 (0)