From 89a282c12edbf43c8a647609cc4676a8667b5468 Mon Sep 17 00:00:00 2001 From: Simon Chopin Date: Thu, 16 Jan 2025 19:39:01 +0100 Subject: [PATCH] test_net: figure out the proper IP protocol for localhost On some systems, localhost is only defined for 127.0.0.1 (e.g. Ubuntu and Debian containers). However, there is code that hardcodes possible values for localhost, making it possible to open an IPv6 socket for localhost. On those systems, the socket will be open but urllib3 will resolve localhost *only* to 127.0.0.1, thus failing miserably to connect. To resolve the situation, rather than defaulting to IPv6 we actually resolve localhost and use the socket family of the first result. On my current system (upcoming Ubuntu Plucky) if localhost=::1 is defined in /etc/hosts it will come up as the first result, if not 127.0.0.1 will. V2: Use self.port rather than a forgotten hardcoded port. Fixes: f01628ca6b1b "fix localhost network tests on systems with IPv6" --- tests/test_net.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/tests/test_net.py b/tests/test_net.py index 5084474d..581edcfb 100755 --- a/tests/test_net.py +++ b/tests/test_net.py @@ -38,12 +38,9 @@ class RetryServer: def run_fake_server(self): addr = ('localhost', self.port) - if socket.has_dualstack_ipv6(): - server_sock = socket.create_server( - addr, family=socket.AF_INET6, dualstack_ipv6=True - ) - else: - server_sock = socket.create_server(addr) + # localhost might not be a valid name for all families, use the first available + family = socket.getaddrinfo(addr[0], addr[1], type=socket.SOCK_STREAM)[0][0] + server_sock = socket.create_server(addr, family=family) server_sock.listen(5) server_sock.settimeout(5) time.sleep(0.001) # wait for it to start