net: add SocketAddress.parse · nodejs/node@566f0a1 · GitHub
Skip to content

Commit 566f0a1

Browse files
jasnellruyadorno
authored andcommitted
net: add SocketAddress.parse
Adds a new `net.SocketAddress.parse(...)` API. ```js const addr = SocketAddress.parse('123.123.123.123:1234'); console.log(addr.address); // 123.123.123.123 console.log(addr.port); 1234 ``` PR-URL: #56076 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
1 parent ed7eab1 commit 566f0a1

3 files changed

Lines changed: 182 additions & 100 deletions

File tree

doc/api/net.md

Lines changed: 11 additions & 0 deletions

lib/internal/socketaddress.js

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ const {
3737
kDeserialize,
3838
} = require('internal/worker/js_transferable');
3939

40+
const { URL } = require('internal/url');
41+
4042
const kHandle = Symbol('kHandle');
4143
const kDetail = Symbol('kDetail');
4244

@@ -74,7 +76,7 @@ class SocketAddress {
7476
validatePort(port, 'options.port');
7577
validateUint32(flowlabel, 'options.flowlabel', false);
7678

77-
this[kHandle] = new _SocketAddress(address, port, type, flowlabel);
79+
this[kHandle] = new _SocketAddress(address, port | 0, type, flowlabel | 0);
7880
this[kDetail] = this[kHandle].detail({
7981
address: undefined,
8082
port: undefined,
@@ -138,6 +140,36 @@ class SocketAddress {
138140
flowlabel: this.flowlabel,
139141
};
140142
}
143+
144+
/**
145+
* Parse an "${ip}:${port}" formatted string into a SocketAddress.
146+
* Returns undefined if the input cannot be successfully parsed.
147+
* @param {string} input
148+
* @returns {SocketAddress|undefined}
149+
*/
150+
static parse(input) {
151+
validateString(input, 'input');
152+
// While URL.parse is not expected to throw, there are several
153+
// other pieces here that do... the destucturing, the SocketAddress
154+
// constructor, etc. So we wrap this in a try/catch to be safe.
155+
try {
156+
const {
157+
hostname: address,
158+
port,
159+
} = URL.parse(`http://${input}`);
160+
if (address.startsWith('[') && address.endsWith(']')) {
161+
return new SocketAddress({
162+
address: address.slice(1, -1),
163+
port: port | 0,
164+
family: 'ipv6',
165+
});
166+
}
167+
return new SocketAddress({ address, port: port | 0 });
168+
} catch {
169+
// Ignore errors here. Return undefined if the input cannot
170+
// be successfully parsed or is not a proper socket address.
171+
}
172+
}
141173
}
142174

143175
class InternalSocketAddress {

test/parallel/test-socketaddress.js

Lines changed: 138 additions & 99 deletions

0 commit comments

Comments
 (0)