Skip to content

Commit

Permalink
Add explicit support for localhost DNS lookup
Browse files Browse the repository at this point in the history
This change also includes a few micro-optimizations for the DNS helpers.

Fixes: #22633
  • Loading branch information
sbc100 committed Sep 26, 2024
1 parent 2b0980d commit abd6526
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 16 deletions.
26 changes: 10 additions & 16 deletions src/library.js
Original file line number Diff line number Diff line change
Expand Up @@ -913,27 +913,24 @@ addToLibrary({
$DNS: {
address_map: {
id: 1,
addrs: {},
names: {}
addrs: {'localhost': '127.0.0.1'},
names: {'127.0.0.1': 'localhost'}
},

lookup_name(name) {
// If the name is already a valid ipv4 / ipv6 address, don't generate a fake one.
var res = inetPton4(name);
if (res !== null) {
if (inetPton4(name) != null) {
return name;
}
res = inetPton6(name);
if (res !== null) {
// Unlike the inetPton4 above we don't need and explict null comparison
// here since there are no valie v6 addresses that are falsey.
if (inetPton6(name)) {
return name;
}

// See if this name is already mapped.
var addr;

if (DNS.address_map.addrs[name]) {
addr = DNS.address_map.addrs[name];
} else {
var addr = DNS.address_map.addrs[name];
if (!addr) {
var id = DNS.address_map.id++;
assert(id < 65535, 'exceeded max address mappings of 65535');

Expand All @@ -947,11 +944,8 @@ addToLibrary({
},

lookup_addr(addr) {
if (DNS.address_map.names[addr]) {
return DNS.address_map.names[addr];
}

return null;
// Returns `undefined` if that address is not in the map.
return DNS.address_map.names[addr];
}
},

Expand Down
14 changes: 14 additions & 0 deletions test/sockets/test_getaddrinfo.c
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,20 @@ int main() {
assert(sa4->sin_port == ntohs(80));
freeaddrinfo(servinfo);

// test loopback address
err = getaddrinfo("localhost", "89", &hints, &servinfo);
assert(!err);
print_addrinfo(servinfo);
sa4 = ((struct sockaddr_in*)servinfo->ai_addr);
assert(servinfo->ai_family == AF_INET);
assert(servinfo->ai_socktype == SOCK_STREAM);
assert(servinfo->ai_protocol == IPPROTO_TCP);
assert(sa4->sin_port == ntohs(89));
struct in_addr addr;
inet_aton("127.0.0.1", &addr);
assert(sa4->sin_addr.s_addr == addr.s_addr);
freeaddrinfo(servinfo);

#ifdef __EMSCRIPTEN__
// test gai_strerror
CHECK_ERR(0, "Unknown error");
Expand Down

0 comments on commit abd6526

Please sign in to comment.