forked from MortezaBashsiz/CFScanner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.py
More file actions
40 lines (35 loc) · 1.13 KB
/
socket.py
File metadata and controls
40 lines (35 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import socket
import socketserver
import time
def get_free_port() -> int:
"""returns a free port
Returns:
int: free port
"""
with socketserver.TCPServer(("localhost", 0), None) as s:
free_port = s.server_address[1]
return free_port
def wait_for_port(
port: int,
host: str = 'localhost',
timeout: float = 5.0
) -> None:
"""Wait until a port starts accepting TCP connections.
Args:
port: Port number.
host: Host address on which the port should exist.
timeout: In seconds. How long to wait before raising errors.
Raises:
TimeoutError: The port isn't accepting connection after time specified in `timeout`.
"""
start_time = time.perf_counter()
while True:
try:
with socket.create_connection((host, port), timeout=timeout):
break
except OSError as ex:
time.sleep(0.01)
if time.perf_counter() - start_time >= timeout:
raise TimeoutError(
f'Timeout exceeded for the port {port} on host {host} to start accepting connections.'
) from ex