hbutils.system.network.port

Network port availability and allocation utilities.

This module provides lightweight helpers to check whether a TCP port is available on localhost and to allocate a free port within a given range. For safety and common OS restrictions, only ports greater than or equal to 1024 are considered in range-based allocation.

The module contains the following public functions:

Note

Port allocation is performed on localhost (127.0.0.1) using TCP sockets.

Example:

>>> from hbutils.system.network.port import is_free_port, get_free_port
>>> is_free_port(8080)
True
>>> get_free_port(range(8000, 8100))
8000

__all__

hbutils.system.network.port.__all__ = ['is_free_port', 'get_free_port']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

is_free_port

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

Check if a port is currently not in use and can be allocated.

This function attempts to connect to the given port on localhost. If the connection fails, the port is considered free.

Parameters:

port (int) – Port to be checked.

Returns:

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

Return type:

bool

Example:

>>> from hbutils.system.network.port import is_free_port
>>> is_free_port(22)
False
>>> is_free_port(8080)
True

get_free_port

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

Get an allocatable port inside the given ports range.

This function searches for an available port within the specified iterable. For security reasons, only ports numbered 1024 and above are considered. When strict is True and no usable port is available, an OSError is raised. When strict is False, a free port will be allocated by the OS even if it is not in the provided range.

If ports is None or contains no ports >= 1024 while strict is True, strict mode is automatically disabled and a warning is emitted.

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

  • strict (bool) – Strictly use the ports in ports. 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.

Note

Due to OS safety considerations, only ports >= 1024 are used.

Warning

If no usable ports are provided while strict is True, a warnings.warn() call is triggered and strict mode is disabled.

Example:

>>> from hbutils.system.network.port 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
>>> get_free_port()
49152