blob: 326bd248044da9314d57cf79f8074689c82081c0 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
# Copyright (c) 2023 Egor Tensin <Egor.Tensin@gmail.com>
# This file is part of the "cimple" project.
# For details, see https://github.com/egor-tensin/cimple.
# Distributed under the MIT License.
from contextlib import closing
import socket
def random_unused_port():
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('0.0.0.0', 0))
port = sock.getsockname()[1]
return port
|