Port check: ignore TIME_WAIT leftovers on Linux

Binding without SO_REUSEADDR fails while connections to a just-stopped
server linger in TIME_WAIT, so setup moved to the next port even though
nothing was listening. Servers bind with SO_REUSEADDR, so check the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca
This commit is contained in:
neil 2026-11-02 07:09:03 -08:00
parent 22e3019725
commit 0611efd154

View file

@ -227,6 +227,11 @@ def port_free(port):
# 0.0.0.0:port bind while it does. # 0.0.0.0:port bind while it does.
for addr in ("0.0.0.0", "127.0.0.1"): for addr in ("0.0.0.0", "127.0.0.1"):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if sys.platform.startswith("linux"):
# Servers bind with SO_REUSEADDR, so connections lingering in TIME_WAIT (e.g. from
# a server that just stopped) don't block them; without it the port looks busy.
# On Linux this still fails if anything is listening. (On macOS it would not.)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try: try:
s.bind((addr, port)) s.bind((addr, port))
except OSError: except OSError: