hbutils.system.network

Overview:

This module provides useful tools for network operations, including:

  • Host management utilities

  • Port utilities for network connections

  • Telnet connection helpers

  • URL parsing and manipulation tools

All utilities are imported and exposed at the package level for convenient access.

Main Components:

  • Host file management and localhost IP retrieval

  • Port availability checking and allocation

  • Telnet-like connectivity checks

  • URL parsing and splitting utilities

The module aggregates functionality from multiple submodules to provide a comprehensive set of network-related utilities for common tasks such as checking port availability, parsing URLs, managing host files, and testing network connectivity.

hostfile

hbutils.system.network.hostfile() str[source]

Get host file path in this operating system.

Returns:

Host file path in this os.

Return type:

str

Note

This should be /etc/hosts on Linux and macOS, but c:\windows\system32\drivers\etc\hosts on Windows.

Examples::
>>> from hbutils.system import hostfile
>>> hostfile()  # On Linux/macOS
'/etc/hosts'
>>> hostfile()  # On Windows
'c:\windows\system32\drivers\etc\hosts'

get_hosts

hbutils.system.network.get_hosts() Dict[str, str][source]

Get hosts content in form of dictionary.

This function parses the system hosts file and returns a dictionary mapping hostnames to their corresponding IP addresses. Comments and empty lines are automatically ignored during parsing.

Returns:

A dictionary of the hosts file where keys are hostnames and values are IP addresses.

Return type:

Dict[str, str]

Examples::
>>> from hbutils.system import get_hosts
>>> get_hosts()
{'hansbug-VirtualBox': '127.0.0.1', 'localhost': '127.0.0.1'}

get_localhost_ip

hbutils.system.network.get_localhost_ip() str[source]

Get IP address of localhost.

This function retrieves the IP address associated with ‘localhost’ from the system hosts file. If ‘localhost’ is not found in the hosts file, it returns the default localhost IP address 127.0.0.1.

Returns:

IP address of localhost.

Return type:

str

Examples::
>>> from hbutils.system import get_localhost_ip
>>> get_localhost_ip()
'127.0.0.1'

is_free_port

hbutils.system.network.is_free_port(port: int) bool[source]

Check if given port is currently not in use and able to be allocated.

Parameters:

port (int) – Port to be checked.

Returns:

True if the port is free, False if it is in use.

Return type:

bool

Examples::
>>> from hbutils.system import is_free_port
>>> is_free_port(22)
False
>>> is_free_port(80)
False
>>> is_free_port(8080)
True
>>> is_free_port(35022)
True

get_free_port

hbutils.system.network.get_free_port(ports: Iterable[int] | None = None, strict: bool = True) int[source]

Get allocatable port inside the given ports range.

This function searches for an available port within the specified range. For security reasons, only ports numbered 1024 and above are considered. If strict mode is disabled and no port in the range is available, the system will allocate any available port.

Parameters:
  • ports (Optional[Iterable[int]]) – Range of ports to select from. If None, behavior depends on strict parameter.

  • strict (bool) – Strictly use the ports in ports. Default is True. If False, ports not in ports may be used when no port in range is available.

Returns:

A usable port number.

Return type:

int

Raises:

OSError – Raised when no ports can be allocated in strict mode.

Examples::
>>> from hbutils.system import get_free_port
>>> get_free_port(range(22, 1060))
1024
>>> get_free_port(range(1080, 2080, 10))  # assume that 1080 is in use
1090
>>> get_free_port(range(22, 80))
OSError: No free port can be allocated with in range(22, 80).
>>> get_free_port(range(22, 80), strict=False)
44317

Note

Due to the safety consideration of OS, only ports over 1024 will be used.

telnet

hbutils.system.network.telnet(host: str, port: int, timeout: float = 5.0) bool[source]

Perform a telnet operation on the given port and return True if a response is received within the timeout period, otherwise return False.

Parameters:
  • host (str) – Host address to connect to, e.g. 127.0.0.1.

  • port (int) – Port number to test, e.g. 32768.

  • timeout (float) – Maximum timeout duration in seconds, defaults to 5.0.

Returns:

True if port is online and responding, False otherwise.

Return type:

bool

Example::
>>> telnet('127.0.0.1', 8080, timeout=3.0)  # Check if port 8080 is available
True
>>> telnet('127.0.0.1', 9999, timeout=1.0)  # Check unavailable port
False

wait_for_port_online

hbutils.system.network.wait_for_port_online(host: str, port: int, timeout: float | None = 5, interval: float = 0.3)[source]

Wait for the given interface to be in an online state.

This function continuously checks if a port is available by performing telnet operations at regular intervals until the port comes online or the timeout is reached.

Parameters:
  • host (str) – Host address to connect to, e.g. 127.0.0.1.

  • port (int) – Port number to test, e.g. 32768.

  • timeout (Optional[float]) – Maximum timeout duration in seconds. None means wait forever, defaults to 5.

  • interval (float) – Time interval between consecutive telnet checks in seconds, defaults to 0.3.

Raises:

TimeoutError – Raised when timeout is reached and the port is still offline.

Example::
>>> wait_for_port_online('127.0.0.1', 8080, timeout=10, interval=0.5)  # Wait up to 10 seconds
>>> wait_for_port_online('localhost', 3306, timeout=None)  # Wait indefinitely

urlsplit

hbutils.system.network.urlsplit(url: str) SplitURL[source]

Split a URL into its constituent components.

This function parses a URL string and returns a SplitURL object containing the scheme, host, path, query parameters, and fragment. It provides enhanced functionality over urllib.parse.urlsplit by offering convenient properties for accessing parsed query parameters and path segments.

Parameters:

url (str) – The URL string to split.

Returns:

A SplitURL object containing the parsed URL components.

Return type:

SplitURL

Examples::
>>> from hbutils.system import urlsplit
>>>
>>> sp = urlsplit('https://www.baidu.com/dslkjf/sdfhk/asdasd.png?q=1&v=kdjf&q=2#fff')
>>> sp
SplitURL(scheme='https', host='www.baidu.com', path='/dslkjf/sdfhk/asdasd.png', query={'q': ['1', '2'], 'v': 'kdjf'}, fragment='fff')
>>> repr(sp)
"SplitURL(scheme='https', host='www.baidu.com', path='/dslkjf/sdfhk/asdasd.png', query={'q': ['1', '2'], 'v': 'kdjf'}, fragment='fff')"
>>>
>>> sp.scheme
'https'
>>> sp.host
'www.baidu.com'
>>> sp.path
'/dslkjf/sdfhk/asdasd.png'
>>> sp.query
'q=1&v=kdjf&q=2'
>>> sp.fragment
'fff'
>>>
>>> sp.query_dict
{'q': ['1', '2'], 'v': 'kdjf'}
>>> sp.path_segments
['', 'dslkjf', 'sdfhk', 'asdasd.png']
>>> sp.filename
'asdasd.png'

SplitURL

class hbutils.system.network.SplitURL(url: str, scheme: str, host: str, path: str, query: str, fragment: str)[source]

A dataclass representing a parsed URL with its constituent components.

This class provides convenient access to URL components and additional properties for working with query parameters and path segments.

Variables:
  • url (str) – The original URL string.

  • scheme (str) – The URL scheme (e.g., ‘http’, ‘https’, ‘ftp’).

  • host (str) – The host/netloc part of the URL.

  • path (str) – The path component of the URL.

  • query (str) – The query string (without the leading ‘?’).

  • fragment (str) – The fragment identifier (without the leading ‘#’).

__repr__()[source]

Get a detailed string representation of the SplitURL object.

Returns:

A string representation showing all non-empty components.

Return type:

str

Example::
>>> sp = urlsplit('https://example.com/path?q=1#frag')
>>> repr(sp)
"SplitURL(scheme='https', host='example.com', path='/path', query={'q': '1'}, fragment='frag')"
__str__()[source]

Get the original URL string.

Returns:

The original URL.

Return type:

str

property filename: str | None

Get the filename from the URL path.

Returns the last segment of the path, or None if the path is empty.

Returns:

The filename, or None if no path exists.

Return type:

Optional[str]

Example::
>>> sp = urlsplit('https://example.com/path/to/file.txt')
>>> sp.filename
'file.txt'
>>> sp = urlsplit('https://example.com')
>>> sp.filename
''
property path_segments: List[str]

Get the path split into individual segments.

The path is split by ‘/’ and each segment is URL-decoded.

Returns:

A list of decoded path segments.

Return type:

List[str]

Example::
>>> sp = urlsplit('https://example.com/path/to/file.txt')
>>> sp.path_segments
['', 'path', 'to', 'file.txt']
property query_dict

Parse the query string into a dictionary.

When a query parameter appears multiple times, its values are stored as a list. Single-occurrence parameters are stored as single values.

Returns:

A dictionary mapping parameter names to their values (or lists of values).

Return type:

dict

Example::
>>> sp = urlsplit('https://example.com?q=1&v=kdjf&q=2')
>>> sp.query_dict
{'q': ['1', '2'], 'v': 'kdjf'}