GitHub

net_address

API reference for net_address.

Network addresses (Effect's NetAddress).

IP addresses are the standard library's ipaddress.IPv4Address and IPv6Address, parsed strictly (four decimal octets without leading zeros; IPv6 without brackets or zones) and written canonically by format_ip. MacAddress, InetAddressV4 / InetAddressV6 (an address and port, the latter with a scope ID) and UnixPathAddress are frozen dataclasses whose str is their canonical text::

from pyfect.net import net_address as na

address = na.inet_address_from_string("[fe80::1%2]:80").get_or_raise()
na.format_inet(address)                       # "[fe80::1%2]:80"
na.ip_from_string("01.2.3.4")                 # Err(NetAddressError(...))

Checked parsers return Ok / Err(NetAddressError); the _unsafe ones raise the error. Classifications (is_loopback, is_multicast, ...) are Effect's bit tests and return bool.

Re-exports

Values

AttributeTypeDescription
ScopedIpv6Literaltype[ScopedIpv6Literal]

An IPv6 address with a zone, fe80::1%eth0: canonical address text, a numeric zone without leading zeros.

ipv4_broadcastIPv4Address
ipv4_loopbackIPv4Address
ipv4_unspecifiedIPv4Address
ipv6_loopbackIPv6Address
ipv6_unspecifiedIPv6Address
loopback_addressestuple[IPv4Address, IPv6Address]

Types

TypeDefinitionDescription
InetAddresstype InetAddress = InetAddressV4 | InetAddressV6
InetAddressInputtype InetAddressInput = InetAddress | str | InetAddressParts
SocketAddresstype SocketAddress = InetAddress | UnixPathAddress
SocketAddressInputtype SocketAddressInput = SocketAddress | InetAddressInput | UnixPathAddressParts
IpAddresstype IpAddress = IPv4Address | IPv6Address
IpAddressInputtype IpAddressInput = Ipv4AddressInput | Ipv6AddressInput
IpFamilytype IpFamily = Literal['IPv4', 'IPv6']
Ipv4AddressInputtype Ipv4AddressInput = IPv4Address | str | Ipv4Octets | Bytes
Ipv4Octetstype Ipv4Octets = tuple[int, int, int, int]
Ipv6AddressInputtype Ipv6AddressInput = IPv6Address | str | Ipv6Segments | Bytes
Ipv6Segmentstype Ipv6Segments = tuple[int, int, int, int, int, int, int, int]
ScopedIpv6LiteralInputtype ScopedIpv6LiteralInput = ScopedIpv6Literal | str
MacAddressInputtype MacAddressInput = MacAddress | str | MacAddressOctets
MacAddressOctetstype MacAddressOctets = tuple[int, int, int, int, int, int]

Classes

Functions

is_family

is_family(address, family) -> bool

Whether address (or a socket address's IP) is of family.

ParameterTypeDescription
addressIpAddress | InetAddress
familyIpFamily

Returns bool

def is_family(address: IpAddress | InetAddress, family: IpFamily) -> bool:
    """Whether ``address`` (or a socket address's IP) is of ``family``."""
    ip = address.address if isinstance(address, (InetAddressV4, InetAddressV6)) else address
    return family_of(ip) == family

format_host

format_host(address) -> str

The address's host: IPv6 with its numeric scope when it has one.

ParameterTypeDescription
addressInetAddress

Returns str

def format_host(address: InetAddress) -> str:
    """The address's host: IPv6 with its numeric scope when it has one."""
    scope = (
        f"%{address.scope_id}"
        if isinstance(address, InetAddressV6) and address.scope_id != 0
        else ""
    )
    return format_ip(address.address) + scope

format_inet

format_inet(address) -> str
ParameterTypeDescription
addressInetAddress

Returns str

def format_inet(address: InetAddress) -> str:
    host = format_host(address)
    return (
        f"{host}:{address.port}"
        if isinstance(address, InetAddressV4)
        else f"[{host}]:{address.port}"
    )

format_multicast_interface

format_multicast_interface(interface, scope_ids, platform=None) -> str

A multicast interface for a socket API: an IPv4 address, or an IPv6 interface index as ::%name (::%index on Windows or when no interface has it, :: for 0).

ParameterTypeDescription
interfaceIPv4Address | int
scope_idsMapping[str, int]
platformstr | None = None

Returns str

def format_multicast_interface(
    interface: IPv4Address | int, scope_ids: Mapping[str, int], platform: str | None = None
) -> str:
    """A multicast interface for a socket API: an IPv4 address, or an IPv6
    interface index as ``::%name`` (``::%index`` on Windows or when no
    interface has it, ``::`` for ``0``)."""
    if isinstance(interface, IPv4Address):
        return format_ip(interface)
    if interface == 0:
        return "::"
    if platform != "win32":
        for name, scope_id in scope_ids.items():
            if scope_id == interface:
                return f"::%{name}"
    return f"::%{interface}"

format_native_host

format_native_host(address, scope_ids, platform=None) -> str

The host for a socket API: outside Windows, a scope named after the first interface in scope_ids that has it.

ParameterTypeDescription
addressInetAddress
scope_idsMapping[str, int]
platformstr | None = None

Returns str

def format_native_host(
    address: InetAddress, scope_ids: Mapping[str, int], platform: str | None = None
) -> str:
    """The host for a socket API: outside Windows, a scope named after the
    first interface in ``scope_ids`` that has it."""
    if platform != "win32" and isinstance(address, InetAddressV6) and address.scope_id != 0:
        for name, scope_id in scope_ids.items():
            if scope_id == address.scope_id:
                return f"{format_ip(address.address)}%{name}"
    return format_host(address)

format_socket_address

format_socket_address(address) -> str
ParameterTypeDescription
addressSocketAddress

Returns str

def format_socket_address(address: SocketAddress) -> str:
    return address.path if isinstance(address, UnixPathAddress) else format_inet(address)

format_unix_path

format_unix_path(address) -> str
ParameterTypeDescription
addressUnixPathAddress

Returns str

def format_unix_path(address: UnixPathAddress) -> str:
    return f"unix://{address.path}"

format_url

format_url(address, scheme='http') -> Result[str, NetAddressError]

scheme://host[:port] without a trailing slash or default port; a Unix path as unix://path.

ParameterTypeDescription
addressIpAddress | SocketAddress
schemestr = 'http'

Returns Result[str, NetAddressError]

def format_url(
    address: IpAddress | SocketAddress, scheme: str = "http"
) -> Result[str, NetAddressError]:
    """``scheme://host[:port]`` without a trailing slash or default port; a
    Unix path as ``unix://path``."""
    if isinstance(address, UnixPathAddress):
        return Ok(format_unix_path(address))
    return to_url(address, scheme).map(lambda u: f"{u.protocol}//{u.host}")

format_url_host_string

format_url_host_string(host) -> str

A host string as a URL host: IPv6 text in brackets.

ParameterTypeDescription
hoststr

Returns str

def format_url_host_string(host: str) -> str:
    """A host string as a URL host: IPv6 text in brackets."""
    return f"[{host}]" if ":" in host and not host.startswith("[") else host

format_url_unsafe

format_url_unsafe(address, scheme='http') -> str
ParameterTypeDescription
addressIpAddress | SocketAddress
schemestr = 'http'

Returns str

def format_url_unsafe(address: IpAddress | SocketAddress, scheme: str = "http") -> str:
    return format_url(address, scheme).get_or_raise()

inet_address

inet_address(address: IPv4Address, port: int) -> Result[InetAddressV4, NetAddressError]
inet_address(address: IPv6Address, port: int) -> Result[InetAddressV6, NetAddressError]
inet_address(address: IpAddress, port: int) -> Result[InetAddress, NetAddressError]
ParameterTypeDescription
address
port
@overload
def inet_address(address: IPv4Address, port: int) -> Result[InetAddressV4, NetAddressError]: ...
@overload
def inet_address(address: IPv6Address, port: int) -> Result[InetAddressV6, NetAddressError]: ...
@overload
def inet_address(address: IpAddress, port: int) -> Result[InetAddress, NetAddressError]: ...
def inet_address(address: IpAddress, port: int) -> Result[InetAddress, NetAddressError]:
    if isinstance(address, IPv4Address):
        return inet_address_v4(address, port)
    return inet_address_v6(address, port)

inet_address_from_host_string

inet_address_from_host_string(host, port, scope_ids=None) -> Result[InetAddress, NetAddressError]

A host as format_host or format_native_host writes it, and a port; a named zone is resolved only through scope_ids.

ParameterTypeDescription
hoststr
portint
scope_idsMapping[str, int] | None = None

Returns Result[InetAddress, NetAddressError]

def inet_address_from_host_string(
    host: str, port: int, scope_ids: Mapping[str, int] | None = None
) -> Result[InetAddress, NetAddressError]:
    """A host as ``format_host`` or ``format_native_host`` writes it, and a
    port; a named zone is resolved only through ``scope_ids``."""
    head, separator, zone = host.partition("%")
    if separator:
        if not zone or "%" in zone:
            return address_error(host, "invalid IPv6 scope identifier")
        if not is_digits(zone):
            scope_id = (scope_ids or {}).get(zone)
            if scope_id is None:
                return address_error(host, f"unknown IPv6 interface: {zone}")
            host = f"{head}%{scope_id}"
    return inet_address_from_string(f"[{host}]:{port}" if ":" in host else f"{host}:{port}")

inet_address_from_input

inet_address_from_input(value) -> Result[InetAddress, NetAddressError]

An address, its text, or {"address": ..., "port": ..., "scope_id": ...}.

ParameterTypeDescription
valueInetAddressInput

Returns Result[InetAddress, NetAddressError]

def inet_address_from_input(value: InetAddressInput) -> Result[InetAddress, NetAddressError]:
    """An address, its text, or ``{"address": ..., "port": ..., "scope_id":
    ...}``."""
    match value:
        case InetAddressV4() | InetAddressV6():
            return Ok(value)
        case str():
            return inet_address_from_string(value)
        case _:
            pass
    port, scope_id = value["port"], value.get("scope_id", 0)

    def build(address: IpAddress) -> Result[InetAddress, NetAddressError]:
        if isinstance(address, IPv6Address):
            return inet_address_v6(address, port, scope_id=scope_id)
        if scope_id != 0:
            return address_error(value, "scopeId requires an IPv6 address")
        return inet_address_v4(address, port)

    return ip_from_input(value["address"]).flat_map(build)

inet_address_from_input_unsafe

inet_address_from_input_unsafe(value) -> InetAddress
ParameterTypeDescription
valueInetAddressInput

Returns InetAddress

def inet_address_from_input_unsafe(value: InetAddressInput) -> InetAddress:
    return inet_address_from_input(value).get_or_raise()

inet_address_from_ip_string

inet_address_from_ip_string(address, port) -> Result[InetAddress, NetAddressError]
ParameterTypeDescription
addressstr
portint

Returns Result[InetAddress, NetAddressError]

def inet_address_from_ip_string(address: str, port: int) -> Result[InetAddress, NetAddressError]:
    return ip_from_string(address).flat_map(lambda ip: inet_address(ip, port))

inet_address_from_ip_string_unsafe

inet_address_from_ip_string_unsafe(address, port) -> InetAddress
ParameterTypeDescription
addressstr
portint

Returns InetAddress

def inet_address_from_ip_string_unsafe(address: str, port: int) -> InetAddress:
    return inet_address_from_ip_string(address, port).get_or_raise()

inet_address_from_native_unsafe

inet_address_from_native_unsafe(host, port, scope_ids=None) -> InetAddress

The address a socket API reported ('::ffff:1.2.3.4', 'fe80::1%en0'), trusted; a named zone is looked up in scope_ids and raises ValueError when unknown.

ParameterTypeDescription
hoststr
portint
scope_idsMapping[str, int] | None = None

Returns InetAddress

def inet_address_from_native_unsafe(
    host: str, port: int, scope_ids: Mapping[str, int] | None = None
) -> InetAddress:
    """The address a socket API reported (``'::ffff:1.2.3.4'``,
    ``'fe80::1%en0'``), trusted; a named zone is looked up in
    ``scope_ids`` and raises ``ValueError`` when unknown."""
    text, _, zone = host.partition("%")
    address = ip_address(text)
    if isinstance(address, IPv4Address):
        return InetAddressV4(address, port)
    scope_id = 0
    if zone:
        found = parse_digits(zone) if is_digits(zone) else (scope_ids or {}).get(zone)
        if found is None:
            raise ValueError(f"unknown IPv6 interface: {zone}")
        scope_id = found
    return InetAddressV6(address, port, scope_id)

inet_address_from_string

inet_address_from_string(text) -> Result[InetAddress, NetAddressError]

1.2.3.4:80 or [::1]:80 / [fe80::1%2]:80: numeric hosts only, an unpadded decimal port.

ParameterTypeDescription
textstr

Returns Result[InetAddress, NetAddressError]

def inet_address_from_string(text: str) -> Result[InetAddress, NetAddressError]:
    """``1.2.3.4:80`` or ``[::1]:80`` / ``[fe80::1%2]:80``: numeric hosts
    only, an unpadded decimal port."""
    match _split_inet(text):
        case Err() as error:
            return error
        case Ok((host, port_text, scope_id, bracketed)):
            pass
    port = parse_digits(port_text, unpadded=True)
    if port is None:
        return address_error(text, "port must be an unpadded decimal integer")

    def build(address: IpAddress) -> Result[InetAddress, NetAddressError]:
        if bracketed != isinstance(address, IPv6Address):
            return address_error(text, "only IPv6 addresses use brackets")
        if isinstance(address, IPv6Address):
            return inet_address_v6(address, port, scope_id=scope_id)
        return inet_address_v4(address, port)

    return ip_from_string(host).flat_map(build)

inet_address_from_string_unsafe

inet_address_from_string_unsafe(text) -> InetAddress
ParameterTypeDescription
textstr

Returns InetAddress

def inet_address_from_string_unsafe(text: str) -> InetAddress:
    return inet_address_from_string(text).get_or_raise()

inet_address_unsafe

inet_address_unsafe(address, port) -> InetAddress
ParameterTypeDescription
addressIpAddress
portint

Returns InetAddress

def inet_address_unsafe(address: IpAddress, port: int) -> InetAddress:
    return inet_address(address, port).get_or_raise()

inet_address_v4

inet_address_v4(address, port) -> Result[InetAddressV4, NetAddressError]
ParameterTypeDescription
addressIPv4Address
portint

Returns Result[InetAddressV4, NetAddressError]

def inet_address_v4(address: IPv4Address, port: int) -> Result[InetAddressV4, NetAddressError]:
    if not _check_port(port):
        return address_error(address, "port must be an integer from 0 through 65535")
    return Ok(InetAddressV4(address, port))

inet_address_v6

inet_address_v6(address, port, *, scope_id=0) -> Result[InetAddressV6, NetAddressError]
ParameterTypeDescription
addressIPv6Address
portint
scope_idint = 0

Returns Result[InetAddressV6, NetAddressError]

def inet_address_v6(
    address: IPv6Address, port: int, *, scope_id: int = 0
) -> Result[InetAddressV6, NetAddressError]:
    if not _check_port(port):
        return address_error(address, "port must be an integer from 0 through 65535")
    if not _check_scope(scope_id):
        return address_error(address, "scopeId must be an unsigned 32-bit integer")
    return Ok(InetAddressV6(address, port, scope_id))

scope_id_from_interface

scope_id_from_interface(addresses) -> int | None

The first positive IPv6 scope ID among an interface's addresses.

ParameterTypeDescription
addressesIterable[NetworkInterfaceAddress] | None

Returns int | None

def scope_id_from_interface(
    addresses: Iterable[NetworkInterfaceAddress] | None,
) -> int | None:
    """The first positive IPv6 scope ID among an interface's addresses."""
    for address in addresses or ():
        scope = address.get("scopeid")
        if address["family"] == "IPv6" and isinstance(scope, int) and scope > 0:
            return scope
    return None

scope_ids_from_interfaces

scope_ids_from_interfaces(interfaces) -> dict[str, int]

Each interface's first positive IPv6 scope ID, by name, as a snapshot.

ParameterTypeDescription
interfacesIterable[tuple[str, Iterable[NetworkInterfaceAddress] | None]]

Returns dict[str, int]

def scope_ids_from_interfaces(
    interfaces: Iterable[tuple[str, Iterable[NetworkInterfaceAddress] | None]],
) -> dict[str, int]:
    """Each interface's first positive IPv6 scope ID, by name, as a
    snapshot."""
    scope_ids: dict[str, int] = {}
    for name, addresses in interfaces:
        scope_id = scope_id_from_interface(addresses)
        if scope_id is not None:
            scope_ids[name] = scope_id
    return scope_ids

socket_address_from_input

socket_address_from_input(value) -> Result[SocketAddress, NetAddressError]

A socket address, its text, or its parts ({"path": ...} for a Unix socket).

ParameterTypeDescription
valueSocketAddressInput

Returns Result[SocketAddress, NetAddressError]

def socket_address_from_input(value: SocketAddressInput) -> Result[SocketAddress, NetAddressError]:
    """A socket address, its text, or its parts (``{"path": ...}`` for a
    Unix socket)."""
    if isinstance(value, UnixPathAddress):
        return Ok(value)
    if isinstance(value, Mapping) and "path" in value:
        return Ok(UnixPathAddress(value["path"]))
    return inet_address_from_input(value)

socket_address_from_input_unsafe

socket_address_from_input_unsafe(value) -> SocketAddress
ParameterTypeDescription
valueSocketAddressInput

Returns SocketAddress

def socket_address_from_input_unsafe(value: SocketAddressInput) -> SocketAddress:
    return socket_address_from_input(value).get_or_raise()

to_canonical

to_canonical(address: IPv4Address) -> IPv4Address
to_canonical(address: IPv6Address) -> IpAddress
to_canonical(address: InetAddressV4) -> InetAddressV4
to_canonical(address: InetAddressV6) -> InetAddress

An IPv4-mapped IPv6 address as the IPv4 address it holds (its port kept, its scope dropped); any other address unchanged (the same object).

ParameterTypeDescription
address
@overload
def to_canonical(address: IPv4Address) -> IPv4Address: ...
@overload
def to_canonical(address: IPv6Address) -> IpAddress: ...
@overload
def to_canonical(address: InetAddressV4) -> InetAddressV4: ...
@overload
def to_canonical(address: InetAddressV6) -> InetAddress: ...
def to_canonical(
    address: IpAddress | InetAddress,
) -> IpAddress | InetAddress:
    """An IPv4-mapped IPv6 address as the IPv4 address it holds (its port
    kept, its scope dropped); any other address unchanged (the same
    object)."""
    if isinstance(address, (InetAddressV4, InetAddressV6)):
        ip = canonical_ip(address.address)
        return address if ip is address.address else inet_address_unsafe(ip, address.port)
    return canonical_ip(address)

to_url

to_url(address, scheme='http') -> Result[Url, NetAddressError]

The address as a WHATWG-normalized URL (pyfect.http.url); scoped IPv6 addresses have no URL form.

ParameterTypeDescription
addressIpAddress | InetAddress
schemestr = 'http'

Returns Result[Url, NetAddressError]

def to_url(address: IpAddress | InetAddress, scheme: str = "http") -> Result[Url, NetAddressError]:
    """The address as a WHATWG-normalized URL (``pyfect.http.url``); scoped
    IPv6 addresses have no URL form."""
    from pyfect.http import url

    if isinstance(address, InetAddressV6) and address.scope_id != 0:
        return address_error(address, "scoped IPv6 addresses are not supported by WHATWG URLs")
    authority = (
        format_inet(address)
        if isinstance(address, (InetAddressV4, InetAddressV6))
        else format_url_host(address)
    )
    try:
        return Ok(url.parse(f"{scheme}://{authority}"))
    except ValueError as cause:
        return Err(NetAddressError("failed to construct URL", address, cause))

unix_path_address

unix_path_address(path) -> UnixPathAddress
ParameterTypeDescription
pathstr

Returns UnixPathAddress

def unix_path_address(path: str) -> UnixPathAddress:
    return UnixPathAddress(path)

family_of

family_of(address) -> IpFamily
ParameterTypeDescription
addressIpAddress

Returns IpFamily

def family_of(address: IpAddress) -> IpFamily:
    return "IPv4" if isinstance(address, IPv4Address) else "IPv6"

format_ip

format_ip(address) -> str

Canonical text: dotted decimal, or RFC 5952 IPv6 (the first longest run of two or more zero segments compressed; IPv4-mapped addresses dotted).

ParameterTypeDescription
addressIpAddress

Returns str

def format_ip(address: IpAddress) -> str:
    """Canonical text: dotted decimal, or RFC 5952 IPv6 (the first longest
    run of two or more zero segments compressed; IPv4-mapped addresses
    dotted)."""
    if isinstance(address, IPv4Address):
        return ".".join(str(o) for o in address.packed)
    segments = ipv6_to_segments(address)
    if is_ipv4_mapped(address):
        return "::ffff:" + ".".join(str(o) for o in address.packed[12:])
    best_start, best_length, start = -1, 0, -1
    for index in range(9):
        if index < 8 and segments[index] == 0:
            if start == -1:
                start = index
        elif start != -1:
            if index - start > best_length:
                best_start, best_length = start, index - start
            start = -1
    if best_length < 2:
        return ":".join(f"{s:x}" for s in segments)
    head = ":".join(f"{s:x}" for s in segments[:best_start])
    tail = ":".join(f"{s:x}" for s in segments[best_start + best_length :])
    return f"{head}::{tail}"

format_url_host

format_url_host(address) -> str

The address as a URL host: IPv6 in brackets.

ParameterTypeDescription
addressIpAddress

Returns str

def format_url_host(address: IpAddress) -> str:
    """The address as a URL host: IPv6 in brackets."""
    return format_ip(address) if isinstance(address, IPv4Address) else f"[{format_ip(address)}]"

from_ipv4_mapped

from_ipv4_mapped(address) -> IPv4Address | None

The IPv4 address an IPv4-mapped address holds, or None.

ParameterTypeDescription
addressIPv6Address

Returns IPv4Address | None

def from_ipv4_mapped(address: IPv6Address) -> IPv4Address | None:
    """The IPv4 address an IPv4-mapped address holds, or ``None``."""
    return IPv4Address(int(address) & 0xFFFFFFFF) if is_ipv4_mapped(address) else None

ip_from_input

ip_from_input(value) -> Result[IpAddress, NetAddressError]

An address, its text, 4 octets, 8 segments, or 4 or 16 bytes.

ParameterTypeDescription
valueIpAddressInput

Returns Result[IpAddress, NetAddressError]

def ip_from_input(value: IpAddressInput) -> Result[IpAddress, NetAddressError]:
    """An address, its text, 4 octets, 8 segments, or 4 or 16 bytes."""
    if isinstance(value, (IPv4Address, IPv6Address)):
        return Ok(value)
    if isinstance(value, str):
        return ip_from_string(value)
    if isinstance(value, (bytes, bytearray, memoryview)):
        if len(value) == 4:
            return Ok(ipv4_from_bytes_unsafe(value))
        if len(value) == 16:
            return Ok(ipv6_from_bytes_unsafe(value))
    else:
        parsed = _octets_or_segments(value)
        if parsed is not None:
            return parsed
    return address_error(
        value, "expected an IP address, string, 4 octets, 8 segments, or 4 or 16 bytes"
    )

ip_from_input_unsafe

ip_from_input_unsafe(value) -> IpAddress
ParameterTypeDescription
valueIpAddressInput

Returns IpAddress

def ip_from_input_unsafe(value: IpAddressInput) -> IpAddress:
    return ip_from_input(value).get_or_raise()

ip_from_string

ip_from_string(text) -> Result[IpAddress, NetAddressError]

IPv6 when the text holds a colon, else IPv4.

ParameterTypeDescription
textstr

Returns Result[IpAddress, NetAddressError]

def ip_from_string(text: str) -> Result[IpAddress, NetAddressError]:
    """IPv6 when the text holds a colon, else IPv4."""
    parsed: Result[IpAddress, NetAddressError] = (
        ipv6_from_string(text) if ":" in text else ipv4_from_string(text)
    )
    return parsed

ip_from_string_unsafe

ip_from_string_unsafe(text) -> IpAddress
ParameterTypeDescription
textstr

Returns IpAddress

def ip_from_string_unsafe(text: str) -> IpAddress:
    return ip_from_string(text).get_or_raise()

ipv4_from_bytes_unsafe

ipv4_from_bytes_unsafe(data) -> IPv4Address

The address of 4 bytes (copied).

ParameterTypeDescription
dataBytes

Returns IPv4Address

def ipv4_from_bytes_unsafe(data: Bytes) -> IPv4Address:
    """The address of 4 bytes (copied)."""
    return IPv4Address(bytes(data[:4]))

ipv4_from_input

ipv4_from_input(value) -> Result[IPv4Address, NetAddressError]
ParameterTypeDescription
valueIpv4AddressInput

Returns Result[IPv4Address, NetAddressError]

def ipv4_from_input(value: Ipv4AddressInput) -> Result[IPv4Address, NetAddressError]:
    if isinstance(value, IPv4Address):
        return Ok(value)
    if isinstance(value, str):
        return ipv4_from_string(value)
    if len(value) == 4:
        if isinstance(value, (bytes, bytearray, memoryview)):
            return Ok(ipv4_from_bytes_unsafe(value))
        return ipv4_from_octets(value)
    return address_error(value, "expected an IPv4 address, string, 4 octets, or 4 bytes")

ipv4_from_octets

ipv4_from_octets(octets) -> Result[IPv4Address, NetAddressError]
ParameterTypeDescription
octetsIpv4Octets

Returns Result[IPv4Address, NetAddressError]

def ipv4_from_octets(octets: Ipv4Octets) -> Result[IPv4Address, NetAddressError]:
    if len(octets) != 4 or not all_in_range(octets, 255):
        return address_error(octets, "octets must be integers from 0 through 255")
    return Ok(IPv4Address(bytes(octets)))

ipv4_from_string

ipv4_from_string(text) -> Result[IPv4Address, NetAddressError]

Strict dotted decimal: four octets, no leading zeros.

ParameterTypeDescription
textstr

Returns Result[IPv4Address, NetAddressError]

def ipv4_from_string(text: str) -> Result[IPv4Address, NetAddressError]:
    """Strict dotted decimal: four octets, no leading zeros."""
    parts = text.split(".")
    if len(parts) != 4 or not all(_DECIMAL_OCTET.fullmatch(p) for p in parts):
        return address_error(text, "expected exactly four decimal octets")
    if any(len(p) > 1 and p[0] == "0" for p in parts):
        return address_error(text, "leading zeroes are not allowed")
    octets = [int(p) for p in parts]
    if any(o > 255 for o in octets):
        return address_error(text, "octets must be at most 255")
    return Ok(IPv4Address(bytes(octets)))

ipv4_to_octets

ipv4_to_octets(address) -> Ipv4Octets
ParameterTypeDescription
addressIPv4Address

Returns Ipv4Octets

def ipv4_to_octets(address: IPv4Address) -> Ipv4Octets:
    a, b, c, d = address.packed
    return (a, b, c, d)

ipv6_from_bytes_unsafe

ipv6_from_bytes_unsafe(data) -> IPv6Address

The address of 16 bytes (copied).

ParameterTypeDescription
dataBytes

Returns IPv6Address

def ipv6_from_bytes_unsafe(data: Bytes) -> IPv6Address:
    """The address of 16 bytes (copied)."""
    return IPv6Address(bytes(data[:16]))

ipv6_from_input

ipv6_from_input(value) -> Result[IPv6Address, NetAddressError]
ParameterTypeDescription
valueIpv6AddressInput

Returns Result[IPv6Address, NetAddressError]

def ipv6_from_input(value: Ipv6AddressInput) -> Result[IPv6Address, NetAddressError]:
    if isinstance(value, IPv6Address):
        return Ok(value)
    if isinstance(value, str):
        return ipv6_from_string(value)
    if isinstance(value, (bytes, bytearray, memoryview)):
        if len(value) == 16:
            return Ok(ipv6_from_bytes_unsafe(value))
    elif len(value) == 8:
        return ipv6_from_segments(value)
    return address_error(value, "expected an IPv6 address, string, 8 segments, or 16 bytes")

ipv6_from_segments

ipv6_from_segments(segments) -> Result[IPv6Address, NetAddressError]
ParameterTypeDescription
segmentsIpv6Segments

Returns Result[IPv6Address, NetAddressError]

def ipv6_from_segments(segments: Ipv6Segments) -> Result[IPv6Address, NetAddressError]:
    if len(segments) != 8 or not all_in_range(segments, 0xFFFF):
        return address_error(segments, "segments must be integers from 0 through 65535")
    value = 0
    for segment in segments:
        value = (value << 16) | segment
    return Ok(IPv6Address(value))

ipv6_from_string

ipv6_from_string(text) -> Result[IPv6Address, NetAddressError]

IPv6 text, compressed or not, with an optional trailing embedded IPv4 address; no brackets or zone.

ParameterTypeDescription
textstr

Returns Result[IPv6Address, NetAddressError]

def ipv6_from_string(text: str) -> Result[IPv6Address, NetAddressError]:
    """IPv6 text, compressed or not, with an optional trailing embedded
    IPv4 address; no brackets or zone."""

    def to_address(segments: list[int]) -> IPv6Address:
        return IPv6Address(sum(s << (16 * (7 - i)) for i, s in enumerate(segments)))

    return _parse_ipv6_segments(text).map(to_address)

ipv6_to_octets

ipv6_to_octets(address) -> tuple[int, ...]
ParameterTypeDescription
addressIPv6Address

Returns tuple[int, ...]

def ipv6_to_octets(address: IPv6Address) -> tuple[int, ...]:
    return tuple(address.packed)

ipv6_to_segments

ipv6_to_segments(address) -> Ipv6Segments
ParameterTypeDescription
addressIPv6Address

Returns Ipv6Segments

def ipv6_to_segments(address: IPv6Address) -> Ipv6Segments:
    value = int(address)
    s = [(value >> (16 * (7 - i))) & 0xFFFF for i in range(8)]
    return (s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7])

is_ipv4_mapped

is_ipv4_mapped(address) -> bool
ParameterTypeDescription
addressIPv6Address

Returns bool

def is_ipv4_mapped(address: IPv6Address) -> bool:
    return int(address) >> 32 == 0xFFFF
is_link_local(address) -> bool
ParameterTypeDescription
addressIpAddress

Returns bool

def is_link_local(address: IpAddress) -> bool:
    if isinstance(address, IPv4Address):
        return int(address) >> 16 == 0xA9FE
    return (int(address) >> 112) & 0xFFC0 == 0xFE80

is_loopback

is_loopback(address) -> bool
ParameterTypeDescription
addressIpAddress

Returns bool

def is_loopback(address: IpAddress) -> bool:
    if isinstance(address, IPv4Address):
        return int(address) >> 24 == 127
    return int(address) == 1

is_private

is_private(address) -> bool

RFC 1918: 10/8, 172.16/12, 192.168/16.

ParameterTypeDescription
addressIPv4Address

Returns bool

def is_private(address: IPv4Address) -> bool:
    """RFC 1918: 10/8, 172.16/12, 192.168/16."""
    value = int(address)
    return value >> 24 == 10 or (value >> 16) & 0xFFF0 == 0xAC10 or value >> 16 == 0xC0A8

is_scoped_ipv6_literal

is_scoped_ipv6_literal(value) -> bool

Whether value is already a normalized scoped IPv6 literal.

ParameterTypeDescription
valueobject

Returns bool

def is_scoped_ipv6_literal(value: object) -> bool:
    """Whether ``value`` is already a normalized scoped IPv6 literal."""
    if not isinstance(value, str) or "%" not in value:
        return False
    return scoped_ipv6_literal_from_string(value) == Ok(value)

is_unique_local

is_unique_local(address) -> bool

fc00::/7.

ParameterTypeDescription
addressIPv6Address

Returns bool

def is_unique_local(address: IPv6Address) -> bool:
    """fc00::/7."""
    return (int(address) >> 120) & 0xFE == 0xFC

is_unspecified

is_unspecified(address) -> bool
ParameterTypeDescription
addressIpAddress

Returns bool

def is_unspecified(address: IpAddress) -> bool:
    return int(address) == 0

scoped_ipv6_literal_from_input

scoped_ipv6_literal_from_input(value) -> Result[ScopedIpv6Literal, NetAddressError]
ParameterTypeDescription
valueScopedIpv6LiteralInput

Returns Result[ScopedIpv6Literal, NetAddressError]

def scoped_ipv6_literal_from_input(
    value: ScopedIpv6LiteralInput,
) -> Result[ScopedIpv6Literal, NetAddressError]:
    return scoped_ipv6_literal_from_string(value)

scoped_ipv6_literal_from_string

scoped_ipv6_literal_from_string(text) -> Result[ScopedIpv6Literal, NetAddressError]

address%zone, normalized: canonical address text, a numeric zone without leading zeros.

ParameterTypeDescription
textstr

Returns Result[ScopedIpv6Literal, NetAddressError]

def scoped_ipv6_literal_from_string(text: str) -> Result[ScopedIpv6Literal, NetAddressError]:
    """``address%zone``, normalized: canonical address text, a numeric zone
    without leading zeros."""
    address, separator, zone = text.partition("%")
    if not separator:
        return address_error(text, "expected an IPv6 zone")
    if not zone or _ZONE_FORBIDDEN.search(zone):
        return address_error(text, "invalid IPv6 scope identifier")
    if is_digits(zone):
        number = parse_digits(zone)
        if number is None or number > 0xFFFFFFFF:
            return address_error(text, "scope identifier must be an unsigned 32-bit integer")
        zone = str(number)
    return ipv6_from_string(address).map(lambda ip: ScopedIpv6Literal(f"{format_ip(ip)}%{zone}"))

to_ipv4_mapped

to_ipv4_mapped(address) -> IPv6Address
ParameterTypeDescription
addressIPv4Address

Returns IPv6Address

def to_ipv4_mapped(address: IPv4Address) -> IPv6Address:
    return IPv6Address((0xFFFF << 32) | int(address))

width

width(address) -> Literal[32, 128]

The address's bit width.

ParameterTypeDescription
addressIpAddress

Returns Literal[32, 128]

def width(address: IpAddress) -> Literal[32, 128]:
    """The address's bit width."""
    return 32 if isinstance(address, IPv4Address) else 128

format_mac_address

format_mac_address(address) -> str
ParameterTypeDescription
addressMacAddress

Returns str

def format_mac_address(address: MacAddress) -> str:
    return ":".join(f"{byte:02x}" for byte in address.packed)

is_broadcast

is_broadcast(address) -> bool

255.255.255.255 or ff:ff:ff:ff:ff:ff.

ParameterTypeDescription
addressIPv4Address | MacAddress

Returns bool

def is_broadcast(address: IPv4Address | MacAddress) -> bool:
    """255.255.255.255 or ff:ff:ff:ff:ff:ff."""
    if isinstance(address, MacAddress):
        return is_mac_broadcast(address)
    return int(address) == 0xFFFFFFFF

is_mac_broadcast

is_mac_broadcast(address) -> bool
ParameterTypeDescription
addressMacAddress

Returns bool

def is_mac_broadcast(address: MacAddress) -> bool:
    return address.packed == b"\xff" * 6

is_mac_locally_administered

is_mac_locally_administered(address) -> bool
ParameterTypeDescription
addressMacAddress

Returns bool

def is_mac_locally_administered(address: MacAddress) -> bool:
    return address.packed[0] & 2 != 0

is_mac_multicast

is_mac_multicast(address) -> bool

The group bit (the low bit of the first octet) is set.

ParameterTypeDescription
addressMacAddress

Returns bool

def is_mac_multicast(address: MacAddress) -> bool:
    """The group bit (the low bit of the first octet) is set."""
    return address.packed[0] & 1 != 0

is_mac_unicast

is_mac_unicast(address) -> bool
ParameterTypeDescription
addressMacAddress

Returns bool

def is_mac_unicast(address: MacAddress) -> bool:
    return address.packed[0] & 1 == 0

is_mac_universally_administered

is_mac_universally_administered(address) -> bool
ParameterTypeDescription
addressMacAddress

Returns bool

def is_mac_universally_administered(address: MacAddress) -> bool:
    return address.packed[0] & 2 == 0

is_multicast

is_multicast(address) -> bool

224/4, ff00::/8, or a MAC address with the group bit set.

ParameterTypeDescription
addressIpAddress | MacAddress

Returns bool

def is_multicast(address: IpAddress | MacAddress) -> bool:
    """224/4, ff00::/8, or a MAC address with the group bit set."""
    if isinstance(address, MacAddress):
        return is_mac_multicast(address)
    if isinstance(address, IPv4Address):
        return int(address) >> 28 == 0xE
    return int(address) >> 120 == 0xFF

is_unicast

is_unicast(address) -> bool

Not multicast, unspecified or the IPv4 broadcast address (which says nothing about reachability); a MAC address without the group bit.

ParameterTypeDescription
addressIpAddress | MacAddress

Returns bool

def is_unicast(address: IpAddress | MacAddress) -> bool:
    """Not multicast, unspecified or the IPv4 broadcast address (which says
    nothing about reachability); a MAC address without the group bit."""
    if isinstance(address, MacAddress):
        return is_mac_unicast(address)
    if is_multicast(address) or is_unspecified(address):
        return False
    return not (isinstance(address, IPv4Address) and is_broadcast(address))

mac_address_from_input

mac_address_from_input(value) -> Result[MacAddress, NetAddressError]
ParameterTypeDescription
valueMacAddressInput

Returns Result[MacAddress, NetAddressError]

def mac_address_from_input(value: MacAddressInput) -> Result[MacAddress, NetAddressError]:
    if isinstance(value, MacAddress):
        return Ok(value)
    if isinstance(value, str):
        return mac_address_from_string(value)
    return mac_address_from_octets(value)

mac_address_from_input_unsafe

mac_address_from_input_unsafe(value) -> MacAddress
ParameterTypeDescription
valueMacAddressInput

Returns MacAddress

def mac_address_from_input_unsafe(value: MacAddressInput) -> MacAddress:
    return mac_address_from_input(value).get_or_raise()

mac_address_from_octets

mac_address_from_octets(octets) -> Result[MacAddress, NetAddressError]
ParameterTypeDescription
octetsMacAddressOctets

Returns Result[MacAddress, NetAddressError]

def mac_address_from_octets(octets: MacAddressOctets) -> Result[MacAddress, NetAddressError]:
    if len(octets) != 6 or not all_in_range(octets, 255):
        return address_error(octets, "octets must be integers from 0 through 255")
    return Ok(MacAddress(bytes(octets)))

mac_address_from_string

mac_address_from_string(text) -> Result[MacAddress, NetAddressError]

Six two-digit hexadecimal octets separated by colons, any case.

ParameterTypeDescription
textstr

Returns Result[MacAddress, NetAddressError]

def mac_address_from_string(text: str) -> Result[MacAddress, NetAddressError]:
    """Six two-digit hexadecimal octets separated by colons, any case."""
    if not _MAC.fullmatch(text):
        return address_error(text, "expected six two-digit hexadecimal octets separated by colons")
    return Ok(MacAddress(bytes(int(part, 16) for part in text.split(":"))))

mac_address_from_string_unsafe

mac_address_from_string_unsafe(text) -> MacAddress
ParameterTypeDescription
textstr

Returns MacAddress

def mac_address_from_string_unsafe(text: str) -> MacAddress:
    return mac_address_from_string(text).get_or_raise()

mac_address_to_octets

mac_address_to_octets(address) -> MacAddressOctets
ParameterTypeDescription
addressMacAddress

Returns MacAddressOctets

def mac_address_to_octets(address: MacAddress) -> MacAddressOctets:
    a, b, c, d, e, f = address.packed
    return (a, b, c, d, e, f)