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"
This commit is contained in:
Simon Chopin 2025-01-16 19:39:01 +01:00 committed by Hans-Christoph Steiner
parent 2716f93e79
commit 89a282c12e

View File

@ -38,12 +38,9 @@ class RetryServer:
def run_fake_server(self): def run_fake_server(self):
addr = ('localhost', self.port) addr = ('localhost', self.port)
if socket.has_dualstack_ipv6(): # localhost might not be a valid name for all families, use the first available
server_sock = socket.create_server( family = socket.getaddrinfo(addr[0], addr[1], type=socket.SOCK_STREAM)[0][0]
addr, family=socket.AF_INET6, dualstack_ipv6=True server_sock = socket.create_server(addr, family=family)
)
else:
server_sock = socket.create_server(addr)
server_sock.listen(5) server_sock.listen(5)
server_sock.settimeout(5) server_sock.settimeout(5)
time.sleep(0.001) # wait for it to start time.sleep(0.001) # wait for it to start