Skip to content

Commit eac2951

Browse files
committed
fix find port func
need to set SO_REUSEADDR because socket is in STATE_WAIT as per this diagram: https://en.wikipedia.org/wiki/File%3aTcp_state_diagram_fixed_new.svg
1 parent f1f8c33 commit eac2951

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/idom/server/utils.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import asyncio
2+
import errno
3+
import socket
24
import time
35
from contextlib import closing
46
from functools import wraps
57
from importlib import import_module
6-
from socket import socket
78
from threading import Event, Thread
89
from typing import Any, Callable, List, Optional, TypeVar, cast
910

@@ -86,13 +87,15 @@ def find_builtin_server_type(type_name: str) -> ServerFactory[Any, Any]:
8687
def find_available_port(host: str, port_min: int = 8000, port_max: int = 9000) -> int:
8788
"""Get a port that's available for the given host and port range"""
8889
for port in range(port_min, port_max):
89-
with closing(socket()) as sock:
90+
with closing(socket.socket()) as sock:
91+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
9092
try:
9193
sock.bind((host, port))
92-
except OSError:
93-
pass
94+
except socket.error as error:
95+
if error.errno != errno.EADDRINUSE:
96+
raise
9497
else:
9598
return port
9699
raise RuntimeError(
97-
f"Host {host!r} has no available port in range {port_max}-{port_max}"
100+
f"Host {host!r} has no available port in range {port_min}-{port_max}"
98101
)

0 commit comments

Comments
 (0)