MCPcopy Index your code
hub / github.com/reactive-python/reactpy / find_available_port

Function find_available_port

src/py/reactpy/reactpy/backend/utils.py:51–68  ·  view source on GitHub ↗

Get a port that's available for the given host and port range

(host: str, port_min: int = 8000, port_max: int = 9000)

Source from the content-addressed store, hash-verified

49
50
51def find_available_port(host: str, port_min: int = 8000, port_max: int = 9000) -> int:
52 """Get a port that's available for the given host and port range"""
53 for port in range(port_min, port_max):
54 with closing(socket.socket()) as sock:
55 try:
56 if sys.platform in ("linux", "darwin"):
57 # Fixes bug on Unix-like systems where every time you restart the
58 # server you'll get a different port on Linux. This cannot be set
59 # on Windows otherwise address will always be reused.
60 # Ref: https://stackoverflow.com/a/19247688/3159288
61 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
62 sock.bind((host, port))
63 except OSError:
64 pass
65 else:
66 return port
67 msg = f"Host {host!r} has no available port in range {port_max}-{port_max}"
68 raise RuntimeError(msg)
69
70
71def all_implementations() -> Iterator[BackendType[Any]]:

Callers 5

test_automatic_reconnectFunction · 0.90
test_find_available_portFunction · 0.90
test_runFunction · 0.90
__init__Method · 0.90
runFunction · 0.85

Calls

no outgoing calls

Tested by 3

test_automatic_reconnectFunction · 0.72
test_find_available_portFunction · 0.72
test_runFunction · 0.72