Skip to content

Commit

Permalink
More reliable way to find free ports for testing
Browse files Browse the repository at this point in the history
  • Loading branch information
danijar committed Sep 9, 2024
1 parent 459b63d commit c359b54
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions portal/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,16 +78,16 @@ def eachproc(fn, procs):
if p.status() != psutil.STATUS_ZOMBIE else None), procs)


def free_port(low=10000, high=50000):
def free_port():
# Return a port that is currently free. This function is not thread or
# process safe, because there is no way to guarantee that the port will still
# be free at the time it will be used.
rng = np.random.default_rng()
while True:
port = int(rng.integers(low, high))
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
if s.connect_ex(('', port)):
return port
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('localhost', 0))
port = sock.getsockname()[1]
sock.close()
return port


def style(color=None, background=None, bold=None, underline=None, reset=None):
Expand Down

0 comments on commit c359b54

Please sign in to comment.