Skip to content

Commit a45172c

Browse files
authored
Do not crash when port in use (#15)
1 parent 4ff20db commit a45172c

1 file changed

Lines changed: 20 additions & 2 deletions

File tree

‎sendspin/serve/__init__.py‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Sendspin server application."""
22

33
import asyncio
4+
import errno
45
import logging
56
import signal
67
import socket
@@ -109,9 +110,26 @@ async def on_server_event(server: SendspinServer, event: SendspinEvent) -> None:
109110

110111
server.add_event_listener(on_server_event)
111112

112-
await server.start_server(port=config.port)
113+
# Find an available port
114+
port = config.port
115+
max_attempts = 10
116+
for attempt in range(max_attempts):
117+
try:
118+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
119+
s.bind(("", port))
120+
break
121+
except OSError as e:
122+
if e.errno == errno.EADDRINUSE and attempt < max_attempts - 1:
123+
port += 1
124+
else:
125+
raise
126+
else:
127+
raise OSError(f"Could not find available port after {max_attempts} attempts")
128+
129+
await server.start_server(port=port)
130+
113131
local_ip = get_local_ip()
114-
url = f"http://{local_ip}:{config.port}/"
132+
url = f"http://{local_ip}:{port}/"
115133
print(f"\nServer running at {url}")
116134
if local_ip == "localhost":
117135
print("Unable to print QR code because no LAN IP available\n")

0 commit comments

Comments
 (0)