File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1515
1616
1717def find_free_port () -> int :
18- """Return a TCP port number that is currently free .
18+ """Return a free TCP port by binding to port 0 and reading the assignment .
1919
20- Binds a socket to port 0 so the OS assigns an available port, then
21- releases it and returns the chosen number. There is an inherent race
22- between releasing the socket and the caller binding the port, but in
23- 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.
20+ Probes IPv6 loopback first to match the backend's ``[::]`` bind (so an
21+ IPv6-occupied port isn't wrongly reported free), falling back to IPv4.
2922 """
3023 if socket .has_ipv6 :
3124 try :
3225 with socket .socket (socket .AF_INET6 , socket .SOCK_STREAM ) as s :
33- s .bind (("::" , 0 ))
26+ s .bind (("::1 " , 0 ))
3427 return s .getsockname ()[1 ]
3528 except OSError :
3629 pass # IPv6 not usable on this host; fall back to IPv4.
You can’t perform that action at this time.
0 commit comments