Skip to content

ClaimedPort(port, sockets, guards)

A port claimed on every address that localhost can mean on this machine.

Closing the claimed port, directly or by leaving its context, closes its sockets and the sockets that hold the port's wildcard addresses, and releases the port.

Create claimed ports only via claim_port, not by instantiating this class directly.

Create a claimed port.

Parameters:

Name Type Description Default
port int

Port that's claimed.

required
sockets list[socket]

Bound sockets, one for each loopback address.

required
guards list[socket]

Bound sockets that hold the port's wildcard addresses.

required
Source code in src/notwork/models/claimed_port.py
def __init__(
    self,
    port: int,
    sockets: list[socket],
    guards: list[socket],
) -> None:
    """
    Create a claimed port.

    Args:
        port: Port that's claimed.
        sockets: Bound sockets, one for each loopback address.
        guards: Bound sockets that hold the port's wildcard addresses.
    """
    self._guards = guards

    self.port = port
    """The port that's claimed."""

    self.sockets = sockets
    """
    The bound sockets, one for each loopback address, to listen on.

    Closing these doesn't release the port: close the claimed port instead.
    """

port = port instance-attribute

The port that's claimed.

sockets = sockets instance-attribute

The bound sockets, one for each loopback address, to listen on.

Closing these doesn't release the port: close the claimed port instead.

close()

Close every socket and release the port.

Source code in src/notwork/models/claimed_port.py
def close(self) -> None:
    """Close every socket and release the port."""
    with ExitStack() as stack:
        for sock in (*self.sockets, *self._guards):
            stack.callback(sock.close)