Skip to content
Edit this page

ictdesigntools.network.subnet

Subnet calculations for IPv4 and IPv6, built on the stdlib ipaddress module.

SubnetError

Bases: ValueError

Raised when the input cannot be parsed as an address or network.

parse

parse(query: str) -> Interface

Parse 10.0.0.1/24, 10.0.0.1 255.255.255.0, 2001:db8::/32 and similar.

An address without a prefix is treated as a single host (/32 or /128).

Source code in src/ictdesigntools/network/subnet.py
def parse(query: str) -> Interface:
    """Parse ``10.0.0.1/24``, ``10.0.0.1 255.255.255.0``, ``2001:db8::/32`` and similar.

    An address without a prefix is treated as a single host (/32 or /128).
    """
    text = " ".join(query.split())
    if not text:
        raise SubnetError("Enter an IP address or network.")
    parts = text.replace(" /", "/").replace("/ ", "/").split(" ")
    if len(parts) > 2:
        raise SubnetError("Use the form address/prefix, e.g. 192.168.1.10/24.")
    text = "/".join(parts)
    try:
        return ipaddress.ip_interface(text)
    except ValueError as exc:
        raise SubnetError(f"“{query.strip()}” is not a valid IP address or network.") from exc

calculate

calculate(query: str | Interface) -> SubnetResult

Details of an address and its network, from text (see parse) or an interface.

Source code in src/ictdesigntools/network/subnet.py
def calculate(query: str | Interface) -> SubnetResult:
    """Details of an address and its network, from text (see ``parse``) or an interface."""
    if isinstance(query, str):
        iface = parse(query)
    else:
        iface, query = query, str(query)
    net = iface.network
    total = net.num_addresses

    if net.version == 4 and net.prefixlen < 31:
        first, last = net.network_address + 1, net.broadcast_address - 1
        usable = total - 2
    else:
        # /31 point-to-point (RFC 3021), /32 host routes, and all IPv6 prefixes
        # have no reserved network/broadcast addresses.
        first, last = net.network_address, net.broadcast_address
        usable = total

    is_v4 = net.version == 4
    return SubnetResult(
        query=query.strip(),
        version=net.version,
        address=str(iface.ip),
        network=str(net),
        prefixlen=net.prefixlen,
        netmask=str(net.netmask),
        hostmask=str(net.hostmask),
        broadcast=str(net.broadcast_address) if is_v4 else None,
        first_host=str(first),
        last_host=str(last),
        total_addresses=total,
        usable_hosts=usable,
        address_type=_address_type(iface.ip),
        reverse_zone=_reverse_zone(net),
        address_binary=_binary(iface.ip) if is_v4 else None,
        netmask_binary=_binary(net.netmask) if is_v4 else None,
        compressed=None if is_v4 else iface.ip.compressed,
        exploded=None if is_v4 else iface.ip.exploded,
    )