Skip to content

Commit ef24ba7

Browse files
committedSep 26, 2024
Add explicit support for localhost DNS lookup
This change also includes a few micro-optimizations for the DNS helpers. Fixes: #22633
1 parent edba60b commit ef24ba7

File tree

2 files changed

+24
-16
lines changed

2 files changed

+24
-16
lines changed
 

‎src/library.js

+10-16
Original file line numberDiff line numberDiff line change
@@ -913,27 +913,24 @@ addToLibrary({
913913
$DNS: {
914914
address_map: {
915915
id: 1,
916-
addrs: {},
917-
names: {}
916+
addrs: {'localhost': '127.0.0.1'},
917+
names: {'127.0.0.1': 'localhost'}
918918
},
919919

920920
lookup_name(name) {
921921
// If the name is already a valid ipv4 / ipv6 address, don't generate a fake one.
922-
var res = inetPton4(name);
923-
if (res !== null) {
922+
if (inetPton4(name) != null) {
924923
return name;
925924
}
926-
res = inetPton6(name);
927-
if (res !== null) {
925+
// Unlike the inetPton4 above we don't need and explict null comparison
926+
// here since there are no valie v6 addresses that are falsey.
927+
if (inetPton6(name)) {
928928
return name;
929929
}
930930

931931
// See if this name is already mapped.
932-
var addr;
933-
934-
if (DNS.address_map.addrs[name]) {
935-
addr = DNS.address_map.addrs[name];
936-
} else {
932+
var addr = DNS.address_map.addrs[name];
933+
if (!addr) {
937934
var id = DNS.address_map.id++;
938935
assert(id < 65535, 'exceeded max address mappings of 65535');
939936

@@ -947,11 +944,8 @@ addToLibrary({
947944
},
948945

949946
lookup_addr(addr) {
950-
if (DNS.address_map.names[addr]) {
951-
return DNS.address_map.names[addr];
952-
}
953-
954-
return null;
947+
// Returns `undefined` if that address is not in the map.
948+
return DNS.address_map.names[addr];
955949
}
956950
},
957951

‎test/sockets/test_getaddrinfo.c

+14
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,20 @@ int main() {
293293
assert(sa4->sin_port == ntohs(80));
294294
freeaddrinfo(servinfo);
295295

296+
// test loopback address
297+
err = getaddrinfo("localhost", "89", &hints, &servinfo);
298+
assert(!err);
299+
print_addrinfo(servinfo);
300+
sa4 = ((struct sockaddr_in*)servinfo->ai_addr);
301+
assert(servinfo->ai_family == AF_INET);
302+
assert(servinfo->ai_socktype == SOCK_STREAM);
303+
assert(servinfo->ai_protocol == IPPROTO_TCP);
304+
assert(sa4->sin_port == ntohs(89));
305+
struct in_addr addr;
306+
inet_aton("127.0.0.1", &addr);
307+
assert(sa4->sin_addr.s_addr == addr.s_addr);
308+
freeaddrinfo(servinfo);
309+
296310
#ifdef __EMSCRIPTEN__
297311
// test gai_strerror
298312
CHECK_ERR(0, "Unknown error");

0 commit comments

Comments
 (0)
Failed to load comments.