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#
- From
pyfect.net:NetAddressError
Values#
| Attribute | Type | Description |
|---|---|---|
ScopedIpv6Literal | type[ScopedIpv6Literal] | An IPv6 address with a zone, |
ipv4_broadcast | IPv4Address | |
ipv4_loopback | IPv4Address | |
ipv4_unspecified | IPv4Address | |
ipv6_loopback | IPv6Address | |
ipv6_unspecified | IPv6Address | |
loopback_addresses | tuple[IPv4Address, IPv6Address] |
Types#
| Type | Definition | Description |
|---|---|---|
InetAddress | type InetAddress = InetAddressV4 | InetAddressV6 | |
InetAddressInput | type InetAddressInput = InetAddress | str | InetAddressParts | |
SocketAddress | type SocketAddress = InetAddress | UnixPathAddress | |
SocketAddressInput | type SocketAddressInput = SocketAddress | InetAddressInput | UnixPathAddressParts | |
IpAddress | type IpAddress = IPv4Address | IPv6Address | |
IpAddressInput | type IpAddressInput = Ipv4AddressInput | Ipv6AddressInput | |
IpFamily | type IpFamily = Literal['IPv4', 'IPv6'] | |
Ipv4AddressInput | type Ipv4AddressInput = IPv4Address | str | Ipv4Octets | Bytes | |
Ipv4Octets | type Ipv4Octets = tuple[int, int, int, int] | |
Ipv6AddressInput | type Ipv6AddressInput = IPv6Address | str | Ipv6Segments | Bytes | |
Ipv6Segments | type Ipv6Segments = tuple[int, int, int, int, int, int, int, int] | |
ScopedIpv6LiteralInput | type ScopedIpv6LiteralInput = ScopedIpv6Literal | str | |
MacAddressInput | type MacAddressInput = MacAddress | str | MacAddressOctets | |
MacAddressOctets | type MacAddressOctets = tuple[int, int, int, int, int, int] |
Classes#
Functions#
is_family#
is_family(address, family) -> boolWhether address (or a socket address's IP) is of family.
| Parameter | Type | Description |
|---|---|---|
address | IpAddress | InetAddress | |
family | IpFamily |
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) == familyformat_host#
format_host(address) -> strThe address's host: IPv6 with its numeric scope when it has one.
| Parameter | Type | Description |
|---|---|---|
address | InetAddress |
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) + scopeformat_inet#
format_inet(address) -> str| Parameter | Type | Description |
|---|---|---|
address | InetAddress |
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) -> strA 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).
| Parameter | Type | Description |
|---|---|---|
interface | IPv4Address | int | |
scope_ids | Mapping[str, int] | |
platform | str | 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) -> strThe host for a socket API: outside Windows, a scope named after the
first interface in scope_ids that has it.
| Parameter | Type | Description |
|---|---|---|
address | InetAddress | |
scope_ids | Mapping[str, int] | |
platform | str | 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| Parameter | Type | Description |
|---|---|---|
address | SocketAddress |
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| Parameter | Type | Description |
|---|---|---|
address | UnixPathAddress |
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.
| Parameter | Type | Description |
|---|---|---|
address | IpAddress | SocketAddress | |
scheme | str = '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) -> strA host string as a URL host: IPv6 text in brackets.
| Parameter | Type | Description |
|---|---|---|
host | str |
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 hostformat_url_unsafe#
format_url_unsafe(address, scheme='http') -> str| Parameter | Type | Description |
|---|---|---|
address | IpAddress | SocketAddress | |
scheme | str = '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]| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
host | str | |
port | int | |
scope_ids | Mapping[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": ...}.
| Parameter | Type | Description |
|---|---|---|
value | InetAddressInput |
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| Parameter | Type | Description |
|---|---|---|
value | InetAddressInput |
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]| Parameter | Type | Description |
|---|---|---|
address | str | |
port | int |
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| Parameter | Type | Description |
|---|---|---|
address | str | |
port | int |
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) -> InetAddressThe 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.
| Parameter | Type | Description |
|---|---|---|
host | str | |
port | int | |
scope_ids | Mapping[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.
| Parameter | Type | Description |
|---|---|---|
text | str |
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| Parameter | Type | Description |
|---|---|---|
text | str |
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| Parameter | Type | Description |
|---|---|---|
address | IpAddress | |
port | int |
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]| Parameter | Type | Description |
|---|---|---|
address | IPv4Address | |
port | int |
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]| Parameter | Type | Description |
|---|---|---|
address | IPv6Address | |
port | int | |
scope_id | int = 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 | NoneThe first positive IPv6 scope ID among an interface's addresses.
| Parameter | Type | Description |
|---|---|---|
addresses | Iterable[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 Nonescope_ids_from_interfaces#
scope_ids_from_interfaces(interfaces) -> dict[str, int]Each interface's first positive IPv6 scope ID, by name, as a snapshot.
| Parameter | Type | Description |
|---|---|---|
interfaces | Iterable[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_idssocket_address_from_input#
socket_address_from_input(value) -> Result[SocketAddress, NetAddressError]A socket address, its text, or its parts ({"path": ...} for a
Unix socket).
| Parameter | Type | Description |
|---|---|---|
value | SocketAddressInput |
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| Parameter | Type | Description |
|---|---|---|
value | SocketAddressInput |
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) -> InetAddressAn IPv4-mapped IPv6 address as the IPv4 address it holds (its port kept, its scope dropped); any other address unchanged (the same object).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
address | IpAddress | InetAddress | |
scheme | str = '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| Parameter | Type | Description |
|---|---|---|
path | str |
Returns UnixPathAddress
def unix_path_address(path: str) -> UnixPathAddress:
return UnixPathAddress(path)family_of#
family_of(address) -> IpFamily| Parameter | Type | Description |
|---|---|---|
address | IpAddress |
Returns IpFamily
def family_of(address: IpAddress) -> IpFamily:
return "IPv4" if isinstance(address, IPv4Address) else "IPv6"format_ip#
format_ip(address) -> strCanonical text: dotted decimal, or RFC 5952 IPv6 (the first longest run of two or more zero segments compressed; IPv4-mapped addresses dotted).
| Parameter | Type | Description |
|---|---|---|
address | IpAddress |
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) -> strThe address as a URL host: IPv6 in brackets.
| Parameter | Type | Description |
|---|---|---|
address | IpAddress |
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 | NoneThe IPv4 address an IPv4-mapped address holds, or None.
| Parameter | Type | Description |
|---|---|---|
address | IPv6Address |
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 Noneip_from_input#
ip_from_input(value) -> Result[IpAddress, NetAddressError]An address, its text, 4 octets, 8 segments, or 4 or 16 bytes.
| Parameter | Type | Description |
|---|---|---|
value | IpAddressInput |
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| Parameter | Type | Description |
|---|---|---|
value | IpAddressInput |
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.
| Parameter | Type | Description |
|---|---|---|
text | str |
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 parsedip_from_string_unsafe#
ip_from_string_unsafe(text) -> IpAddress| Parameter | Type | Description |
|---|---|---|
text | str |
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) -> IPv4AddressThe address of 4 bytes (copied).
| Parameter | Type | Description |
|---|---|---|
data | Bytes |
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]| Parameter | Type | Description |
|---|---|---|
value | Ipv4AddressInput |
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]| Parameter | Type | Description |
|---|---|---|
octets | Ipv4Octets |
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.
| Parameter | Type | Description |
|---|---|---|
text | str |
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| Parameter | Type | Description |
|---|---|---|
address | IPv4Address |
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) -> IPv6AddressThe address of 16 bytes (copied).
| Parameter | Type | Description |
|---|---|---|
data | Bytes |
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]| Parameter | Type | Description |
|---|---|---|
value | Ipv6AddressInput |
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]| Parameter | Type | Description |
|---|---|---|
segments | Ipv6Segments |
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.
| Parameter | Type | Description |
|---|---|---|
text | str |
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, ...]| Parameter | Type | Description |
|---|---|---|
address | IPv6Address |
Returns tuple[int, ...]
def ipv6_to_octets(address: IPv6Address) -> tuple[int, ...]:
return tuple(address.packed)ipv6_to_segments#
ipv6_to_segments(address) -> Ipv6Segments| Parameter | Type | Description |
|---|---|---|
address | IPv6Address |
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| Parameter | Type | Description |
|---|---|---|
address | IPv6Address |
Returns bool
def is_ipv4_mapped(address: IPv6Address) -> bool:
return int(address) >> 32 == 0xFFFFis_link_local#
is_link_local(address) -> bool| Parameter | Type | Description |
|---|---|---|
address | IpAddress |
Returns bool
def is_link_local(address: IpAddress) -> bool:
if isinstance(address, IPv4Address):
return int(address) >> 16 == 0xA9FE
return (int(address) >> 112) & 0xFFC0 == 0xFE80is_loopback#
is_loopback(address) -> bool| Parameter | Type | Description |
|---|---|---|
address | IpAddress |
Returns bool
def is_loopback(address: IpAddress) -> bool:
if isinstance(address, IPv4Address):
return int(address) >> 24 == 127
return int(address) == 1is_private#
is_private(address) -> boolRFC 1918: 10/8, 172.16/12, 192.168/16.
| Parameter | Type | Description |
|---|---|---|
address | IPv4Address |
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 == 0xC0A8is_scoped_ipv6_literal#
is_scoped_ipv6_literal(value) -> boolWhether value is already a normalized scoped IPv6 literal.
| Parameter | Type | Description |
|---|---|---|
value | object |
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) -> boolfc00::/7.
| Parameter | Type | Description |
|---|---|---|
address | IPv6Address |
Returns bool
def is_unique_local(address: IPv6Address) -> bool:
"""fc00::/7."""
return (int(address) >> 120) & 0xFE == 0xFCis_unspecified#
is_unspecified(address) -> bool| Parameter | Type | Description |
|---|---|---|
address | IpAddress |
Returns bool
def is_unspecified(address: IpAddress) -> bool:
return int(address) == 0scoped_ipv6_literal_from_input#
scoped_ipv6_literal_from_input(value) -> Result[ScopedIpv6Literal, NetAddressError]| Parameter | Type | Description |
|---|---|---|
value | ScopedIpv6LiteralInput |
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.
| Parameter | Type | Description |
|---|---|---|
text | str |
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| Parameter | Type | Description |
|---|---|---|
address | IPv4Address |
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.
| Parameter | Type | Description |
|---|---|---|
address | IpAddress |
Returns Literal[32, 128]
def width(address: IpAddress) -> Literal[32, 128]:
"""The address's bit width."""
return 32 if isinstance(address, IPv4Address) else 128format_mac_address#
format_mac_address(address) -> str| Parameter | Type | Description |
|---|---|---|
address | MacAddress |
Returns str
def format_mac_address(address: MacAddress) -> str:
return ":".join(f"{byte:02x}" for byte in address.packed)is_broadcast#
is_broadcast(address) -> bool255.255.255.255 or ff:ff:ff:ff:ff:ff.
| Parameter | Type | Description |
|---|---|---|
address | IPv4Address | 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) == 0xFFFFFFFFis_mac_broadcast#
is_mac_broadcast(address) -> bool| Parameter | Type | Description |
|---|---|---|
address | MacAddress |
Returns bool
def is_mac_broadcast(address: MacAddress) -> bool:
return address.packed == b"\xff" * 6is_mac_locally_administered#
is_mac_locally_administered(address) -> bool| Parameter | Type | Description |
|---|---|---|
address | MacAddress |
Returns bool
def is_mac_locally_administered(address: MacAddress) -> bool:
return address.packed[0] & 2 != 0is_mac_multicast#
is_mac_multicast(address) -> boolThe group bit (the low bit of the first octet) is set.
| Parameter | Type | Description |
|---|---|---|
address | MacAddress |
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 != 0is_mac_unicast#
is_mac_unicast(address) -> bool| Parameter | Type | Description |
|---|---|---|
address | MacAddress |
Returns bool
def is_mac_unicast(address: MacAddress) -> bool:
return address.packed[0] & 1 == 0is_mac_universally_administered#
is_mac_universally_administered(address) -> bool| Parameter | Type | Description |
|---|---|---|
address | MacAddress |
Returns bool
def is_mac_universally_administered(address: MacAddress) -> bool:
return address.packed[0] & 2 == 0is_multicast#
is_multicast(address) -> bool224/4, ff00::/8, or a MAC address with the group bit set.
| Parameter | Type | Description |
|---|---|---|
address | IpAddress | 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 == 0xFFis_unicast#
is_unicast(address) -> boolNot multicast, unspecified or the IPv4 broadcast address (which says nothing about reachability); a MAC address without the group bit.
| Parameter | Type | Description |
|---|---|---|
address | IpAddress | 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]| Parameter | Type | Description |
|---|---|---|
value | MacAddressInput |
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| Parameter | Type | Description |
|---|---|---|
value | MacAddressInput |
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]| Parameter | Type | Description |
|---|---|---|
octets | MacAddressOctets |
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.
| Parameter | Type | Description |
|---|---|---|
text | str |
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| Parameter | Type | Description |
|---|---|---|
text | str |
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| Parameter | Type | Description |
|---|---|---|
address | MacAddress |
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)On This Page
Re-exportsValuesTypesClassesFunctionsis_familyformat_hostformat_inetformat_multicast_interfaceformat_native_hostformat_socket_addressformat_unix_pathformat_urlformat_url_host_stringformat_url_unsafeinet_addressinet_address_from_host_stringinet_address_from_inputinet_address_from_input_unsafeinet_address_from_ip_stringinet_address_from_ip_string_unsafeinet_address_from_native_unsafeinet_address_from_stringinet_address_from_string_unsafeinet_address_unsafeinet_address_v4inet_address_v6scope_id_from_interfacescope_ids_from_interfacessocket_address_from_inputsocket_address_from_input_unsafeto_canonicalto_urlunix_path_addressfamily_offormat_ipformat_url_hostfrom_ipv4_mappedip_from_inputip_from_input_unsafeip_from_stringip_from_string_unsafeipv4_from_bytes_unsafeipv4_from_inputipv4_from_octetsipv4_from_stringipv4_to_octetsipv6_from_bytes_unsafeipv6_from_inputipv6_from_segmentsipv6_from_stringipv6_to_octetsipv6_to_segmentsis_ipv4_mappedis_link_localis_loopbackis_privateis_scoped_ipv6_literalis_unique_localis_unspecifiedscoped_ipv6_literal_from_inputscoped_ipv6_literal_from_stringto_ipv4_mappedwidthformat_mac_addressis_broadcastis_mac_broadcastis_mac_locally_administeredis_mac_multicastis_mac_unicastis_mac_universally_administeredis_multicastis_unicastmac_address_from_inputmac_address_from_input_unsafemac_address_from_octetsmac_address_from_stringmac_address_from_string_unsafemac_address_to_octets