From a81475d9fb926e123bf9f2c034ebaff59764b14a Mon Sep 17 00:00:00 2001 From: Andrew Kaster Date: Sun, 9 Oct 2022 15:16:34 -0600 Subject: [PATCH] LibCore: Don't assume that the first address from getaddrinfo is IPv4 By passing AF_UNSPEC to getaddrinfo, we're telling the system's implementation that we are ok getting either (or both) IPv4 and IPv6 addresses in our result. On my Ubuntu 22.04 system, the first addrinfo returned for "www.google.com" holds an IPv6 address, which when interpreted as an IPv4 sockaddr_in gives an address of 0.0.0.0. This fixes TestTLSHandshake in Lagom locally. --- Userland/Libraries/LibCore/Stream.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Userland/Libraries/LibCore/Stream.cpp b/Userland/Libraries/LibCore/Stream.cpp index 74e7c1b4ed..bab2474af5 100644 --- a/Userland/Libraries/LibCore/Stream.cpp +++ b/Userland/Libraries/LibCore/Stream.cpp @@ -350,12 +350,17 @@ ErrorOr Socket::resolve_host(String const& host, SocketType type) return Error::from_string_view({ error_string, strlen(error_string) }); } - auto* socket_address = bit_cast(results->ai_addr); - NetworkOrdered network_ordered_address { socket_address->sin_addr.s_addr }; + ScopeGuard free_results = [results] { freeaddrinfo(results); }; - freeaddrinfo(results); + for (auto* result = results; result != nullptr; result = result->ai_next) { + if (result->ai_family == AF_INET) { + auto* socket_address = bit_cast(result->ai_addr); + NetworkOrdered network_ordered_address { socket_address->sin_addr.s_addr }; + return IPv4Address { network_ordered_address }; + } + } - return IPv4Address { network_ordered_address }; + return Error::from_string_literal("Could not resolve to IPv4 address"); } ErrorOr Socket::connect_local(int fd, String const& path)