File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -21,7 +21,20 @@ def find_free_port() -> int:
2121 releases it and returns the chosen number. There is an inherent race
2222 between releasing the socket and the caller binding the port, but in
2323 practice it is reliable for tests and far safer than fixed ports.
24+
25+ The in-memory backend binds the IPv6 wildcard (``[::]``), so the probe
26+ uses an IPv6 socket to mirror that bind and avoid returning a port that
27+ is free on IPv4 but already in use on IPv6. If IPv6 is unavailable, it
28+ falls back to IPv4.
2429 """
30+ if socket .has_ipv6 :
31+ try :
32+ with socket .socket (socket .AF_INET6 , socket .SOCK_STREAM ) as s :
33+ s .bind (("::" , 0 ))
34+ return s .getsockname ()[1 ]
35+ except OSError :
36+ pass # IPv6 not usable on this host; fall back to IPv4.
37+
2538 with socket .socket (socket .AF_INET , socket .SOCK_STREAM ) as s :
26- s .bind (("localhost " , 0 ))
39+ s .bind (("127.0.0.1 " , 0 ))
2740 return s .getsockname ()[1 ]
You can’t perform that action at this time.
0 commit comments