Debian Codegraph @

asynceapi/aio_portcheck.py

raw symbols SCIP
1 # Copyright (c) 2024-2026 Arista Networks, Inc.
2 # Use of this source code is governed by the Apache License 2.0
3 # that can be found in the LICENSE file.
4 # Initially written by Jeremy Schulman at https://github.com/jeremyschulman/aio-eapi
5 """Utility function to check if a port is open."""
6 # -----------------------------------------------------------------------------
7 # System Imports
8 # -----------------------------------------------------------------------------
9
10 from __future__ import annotations
11
12 import asyncio
13 import socket
14 from typing import TYPE_CHECKING
15
16 # -----------------------------------------------------------------------------
17 # Public Imports
18 # -----------------------------------------------------------------------------
19
20 if TYPE_CHECKING:
21 from httpx import URL
22
23 # -----------------------------------------------------------------------------
24 # Exports
25 # -----------------------------------------------------------------------------
26
27 __all__ = ["port_check_url"]
28
29 # -----------------------------------------------------------------------------
30 #
31 # CODE BEGINS
32 #
33 # -----------------------------------------------------------------------------
34
35
36 async def port_check_url(url: URL, timeout: int = 5) -> bool:
37 """Open the port designated by the URL given the timeout in seconds.
38
39 Parameters
40 ----------
41 url
42 The URL that provides the target system.
43 timeout
44 Time to await for the port to open in seconds.
45
46 Returns
47 -------
48 bool
49 If the port is available then return True; False otherwise.
50 """
51 port = url.port or socket.getservbyname(url.scheme)
52
53 try:
54 wr: asyncio.StreamWriter
55 _, wr = await asyncio.wait_for(asyncio.open_connection(host=url.host, port=port), timeout=timeout)
56
57 # MUST close if opened!
58 wr.close()
59
60 except TimeoutError:
61 return False
62 return True