From 0611efd154f265393110ba2cc2603c6d2804a622 Mon Sep 17 00:00:00 2001 From: neil Date: Mon, 2 Nov 2026 07:09:03 -0800 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca --- llmhost/cli.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/llmhost/cli.py b/llmhost/cli.py index 50861e4..b10b307 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -227,6 +227,11 @@ def port_free(port): # 0.0.0.0:port bind while it does. for addr in ("0.0.0.0", "127.0.0.1"): 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: s.bind((addr, port)) except OSError: