Skip to content

Commit 3a391b4

Browse files
authored
add error handling for port process check (#5540)
1 parent eb67f75 commit 3a391b4

1 file changed

Lines changed: 25 additions & 10 deletions

File tree

reflex/utils/processes.py

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,26 @@ def get_num_workers() -> int:
5353
return (os.cpu_count() or 1) * 2 + 1
5454

5555

56+
def _is_address_responsive(
57+
address_family: socket.AddressFamily | int, address: str, port: int
58+
) -> bool:
59+
"""Check if a given address and port are responsive.
60+
61+
Args:
62+
address_family: The address family (e.g., socket.AF_INET or socket.AF_INET6).
63+
address: The address to check.
64+
port: The port to check.
65+
66+
Returns:
67+
Whether the address and port are responsive.
68+
"""
69+
try:
70+
with closing(socket.socket(address_family, socket.SOCK_STREAM)) as sock:
71+
return sock.connect_ex((address, port)) == 0
72+
except OSError:
73+
return False
74+
75+
5676
def is_process_on_port(port: int) -> bool:
5777
"""Check if a process is running on the given port.
5878
@@ -62,16 +82,11 @@ def is_process_on_port(port: int) -> bool:
6282
Returns:
6383
Whether a process is running on the given port.
6484
"""
65-
# Test IPv4 localhost (127.0.0.1)
66-
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
67-
ipv4_result = sock.connect_ex(("127.0.0.1", port)) == 0
68-
69-
# Test IPv6 localhost (::1)
70-
with closing(socket.socket(socket.AF_INET6, socket.SOCK_STREAM)) as sock:
71-
ipv6_result = sock.connect_ex(("::1", port)) == 0
72-
73-
# Port is in use if either IPv4 or IPv6 is listening
74-
return ipv4_result or ipv6_result
85+
return _is_address_responsive( # Test IPv4 localhost (127.0.0.1)
86+
socket.AF_INET, "127.0.0.1", port
87+
) or _is_address_responsive(
88+
socket.AF_INET6, "::1", port
89+
) # Test IPv6 localhost (::1)
7590

7691

7792
def change_port(port: int, _type: str) -> int:

0 commit comments

Comments
 (0)