Type stubs for the Python ipaddress module
npx @tessl/cli install tessl/pypi-types-ipaddress@1.0.0Type stubs for Python's built-in ipaddress module, providing comprehensive type annotations for IP address and network manipulation operations. These stubs enable static type checking for IPv4 and IPv6 address operations, network calculations, and various IP address utilities.
pip install types-ipaddressimport ipaddress
import sys
from typing_extensions import SelfCommon imports for specific functionality:
from ipaddress import (
ip_address, ip_network, ip_interface,
IPv4Address, IPv6Address,
IPv4Network, IPv6Network,
IPv4Interface, IPv6Interface,
AddressValueError, NetmaskValueError
)import ipaddress
# Create IP addresses
ipv4_addr = ipaddress.ip_address('192.168.1.1')
ipv6_addr = ipaddress.ip_address('2001:db8::1')
# Create networks
network = ipaddress.ip_network('192.168.1.0/24')
print(f"Network: {network}")
print(f"Broadcast: {network.broadcast_address}")
print(f"Hosts: {list(network.hosts())[:5]}") # First 5 hosts
# Check if address is in network
if ipv4_addr in network:
print(f"{ipv4_addr} is in {network}")
# Create interfaces (address with network info)
interface = ipaddress.ip_interface('192.168.1.100/24')
print(f"Interface IP: {interface.ip}")
print(f"Interface Network: {interface.network}")Primary functions for creating IP address, network, and interface objects from various input types.
def ip_address(address: int | str | bytes | IPv4Address | IPv6Address) -> IPv4Address | IPv6Address:
"""
Create an IP address object from a string, integer, or bytes.
Args:
address: IP address in various formats
Returns:
IPv4Address or IPv6Address object
Raises:
AddressValueError: If address format is invalid
"""
def ip_network(
address: int | str | bytes | IPv4Address | IPv6Address | IPv4Network | IPv6Network | IPv4Interface | IPv6Interface | tuple[int | str | bytes | IPv4Address | IPv6Address] | tuple[int | str | bytes | IPv4Address | IPv6Address, int],
strict: bool = True
) -> IPv4Network | IPv6Network:
"""
Create a network object from address/netmask or CIDR notation.
Args:
address: Network address in various formats, can include netmask
strict: If False, accept host bits set in network address
Returns:
IPv4Network or IPv6Network object
Raises:
AddressValueError: If network format is invalid
NetmaskValueError: If netmask is invalid
"""
def ip_interface(
address: int | str | bytes | IPv4Address | IPv6Address | IPv4Network | IPv6Network | IPv4Interface | IPv6Interface | tuple[int | str | bytes | IPv4Address | IPv6Address] | tuple[int | str | bytes | IPv4Address | IPv6Address, int]
) -> IPv4Interface | IPv6Interface:
"""
Create an interface object representing an address on a network.
Args:
address: Interface address in various formats, can include netmask
Returns:
IPv4Interface or IPv6Interface object
Raises:
AddressValueError: If address format is invalid
NetmaskValueError: If netmask is invalid
"""Operations specific to IPv4 addresses with 32-bit addressing.
class IPv4Address:
"""
IPv4 address representation with validation and utility methods.
"""
def __init__(self, address: object) -> None:
"""
Create IPv4 address from string, integer, or bytes.
Args:
address: IPv4 address representation
Raises:
AddressValueError: If address is invalid
"""
def __add__(self, other: int) -> IPv4Address:
"""Add integer to address."""
def __sub__(self, other: int) -> IPv4Address:
"""Subtract integer from address."""
def __int__(self) -> int:
"""Convert to integer representation."""
def __format__(self, fmt: str) -> str:
"""Format address as string."""
def __eq__(self, other: object) -> bool:
"""Check equality with another address."""
def __lt__(self, other: Self) -> bool:
"""Compare addresses (less than)."""
if sys.version_info >= (3, 11):
def __ge__(self, other: Self) -> bool:
"""Compare addresses (greater than or equal)."""
def __gt__(self, other: Self) -> bool:
"""Compare addresses (greater than)."""
def __le__(self, other: Self) -> bool:
"""Compare addresses (less than or equal)."""
else:
def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool:
"""Compare addresses (greater than or equal)."""
def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool:
"""Compare addresses (greater than)."""
def __le__(self, other: Self, NotImplemented: Any = ...) -> bool:
"""Compare addresses (less than or equal)."""
def __hash__(self) -> int:
"""Hash function for use in sets/dicts."""
@property
def compressed(self) -> str:
"""Compressed string representation."""
@property
def exploded(self) -> str:
"""Exploded string representation."""
@property
def packed(self) -> bytes:
"""Packed binary representation."""
@property
def reverse_pointer(self) -> str:
"""Reverse DNS pointer domain."""
if sys.version_info >= (3, 14):
version: Final = 4
max_prefixlen: Final = 32
else:
@property
def version(self) -> Literal[4]:
"""IP version (4)."""
@property
def max_prefixlen(self) -> Literal[32]:
"""Maximum prefix length (32)."""
@property
def is_global(self) -> bool:
"""True if address is global."""
@property
def is_link_local(self) -> bool:
"""True if address is link-local."""
@property
def is_loopback(self) -> bool:
"""True if address is loopback."""
@property
def is_multicast(self) -> bool:
"""True if address is multicast."""
@property
def is_private(self) -> bool:
"""True if address is private."""
@property
def is_reserved(self) -> bool:
"""True if address is reserved."""
@property
def is_unspecified(self) -> bool:
"""True if address is unspecified (0.0.0.0)."""
if sys.version_info >= (3, 13):
@property
def ipv6_mapped(self) -> IPv6Address:
"""Convert to IPv6-mapped address."""Operations specific to IPv6 addresses with 128-bit addressing and additional IPv6-specific features.
class IPv6Address:
"""
IPv6 address representation with validation and utility methods.
"""
def __init__(self, address: object) -> None:
"""
Create IPv6 address from string, integer, or bytes.
Args:
address: IPv6 address representation
Raises:
AddressValueError: If address is invalid
"""
def __add__(self, other: int) -> IPv6Address:
"""Add integer to address."""
def __sub__(self, other: int) -> IPv6Address:
"""Subtract integer from address."""
def __int__(self) -> int:
"""Convert to integer representation."""
def __format__(self, fmt: str) -> str:
"""Format address as string."""
def __eq__(self, other: object) -> bool:
"""Check equality with another address."""
def __lt__(self, other: Self) -> bool:
"""Compare addresses (less than)."""
if sys.version_info >= (3, 11):
def __ge__(self, other: Self) -> bool:
"""Compare addresses (greater than or equal)."""
def __gt__(self, other: Self) -> bool:
"""Compare addresses (greater than)."""
def __le__(self, other: Self) -> bool:
"""Compare addresses (less than or equal)."""
else:
def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool:
"""Compare addresses (greater than or equal)."""
def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool:
"""Compare addresses (greater than)."""
def __le__(self, other: Self, NotImplemented: Any = ...) -> bool:
"""Compare addresses (less than or equal)."""
def __hash__(self) -> int:
"""Hash function for use in sets/dicts."""
@property
def compressed(self) -> str:
"""Compressed string representation."""
@property
def exploded(self) -> str:
"""Exploded string representation."""
@property
def packed(self) -> bytes:
"""Packed binary representation."""
@property
def reverse_pointer(self) -> str:
"""Reverse DNS pointer domain."""
if sys.version_info >= (3, 14):
version: Final = 6
max_prefixlen: Final = 128
else:
@property
def version(self) -> Literal[6]:
"""IP version (6)."""
@property
def max_prefixlen(self) -> Literal[128]:
"""Maximum prefix length (128)."""
@property
def is_global(self) -> bool:
"""True if address is global."""
@property
def is_link_local(self) -> bool:
"""True if address is link-local."""
@property
def is_loopback(self) -> bool:
"""True if address is loopback."""
@property
def is_multicast(self) -> bool:
"""True if address is multicast."""
@property
def is_private(self) -> bool:
"""True if address is private."""
@property
def is_reserved(self) -> bool:
"""True if address is reserved."""
@property
def is_unspecified(self) -> bool:
"""True if address is unspecified (::)."""
@property
def is_site_local(self) -> bool:
"""True if address is site-local."""
@property
def ipv4_mapped(self) -> IPv4Address | None:
"""Extract IPv4 address if this is IPv4-mapped."""
@property
def sixtofour(self) -> IPv4Address | None:
"""Extract IPv4 address if this is 6to4."""
@property
def teredo(self) -> tuple[IPv4Address, IPv4Address] | None:
"""Extract Teredo server and client addresses."""
@property
def scope_id(self) -> str | None:
"""IPv6 scope identifier."""Operations for working with IP networks, including subnet calculations and network analysis.
class IPv4Network:
"""
IPv4 network representation with subnet and host operations.
"""
def __init__(self, address: object, strict: bool = True) -> None:
"""
Create IPv4 network from CIDR or address/netmask.
Args:
address: Network specification
strict: If False, accept host bits in network address
Raises:
AddressValueError: If network address is invalid
NetmaskValueError: If netmask is invalid
"""
def __contains__(self, other: object) -> bool:
"""Check if address/network is contained in this network."""
def __getitem__(self, n: int) -> IPv4Address:
"""Get nth address in network."""
def __iter__(self) -> Iterator[IPv4Address]:
"""Iterate over all addresses in network."""
def __eq__(self, other: object) -> bool:
"""Check network equality."""
def __hash__(self) -> int:
"""Hash function for use in sets/dicts."""
def __lt__(self, other: Self) -> bool:
"""Compare networks (less than)."""
if sys.version_info >= (3, 11):
def __ge__(self, other: Self) -> bool:
"""Compare networks (greater than or equal)."""
def __gt__(self, other: Self) -> bool:
"""Compare networks (greater than)."""
def __le__(self, other: Self) -> bool:
"""Compare networks (less than or equal)."""
else:
def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool:
"""Compare networks (greater than or equal)."""
def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool:
"""Compare networks (greater than)."""
def __le__(self, other: Self, NotImplemented: Any = ...) -> bool:
"""Compare networks (less than or equal)."""
@property
def network_address(self) -> IPv4Address:
"""First address in network."""
@property
def broadcast_address(self) -> IPv4Address:
"""Last address in network."""
@property
def netmask(self) -> IPv4Address:
"""Network mask."""
@property
def hostmask(self) -> IPv4Address:
"""Host mask (inverse of netmask)."""
@property
def num_addresses(self) -> int:
"""Total number of addresses in network."""
@property
def prefixlen(self) -> int:
"""Network prefix length."""
@property
def with_prefixlen(self) -> str:
"""Network as CIDR string."""
@property
def with_netmask(self) -> str:
"""Network with explicit netmask."""
@property
def with_hostmask(self) -> str:
"""Network with explicit hostmask."""
@property
def is_global(self) -> bool:
"""True if network is global."""
@property
def is_link_local(self) -> bool:
"""True if network is link-local."""
@property
def is_loopback(self) -> bool:
"""True if network is loopback."""
@property
def is_multicast(self) -> bool:
"""True if network is multicast."""
@property
def is_private(self) -> bool:
"""True if network is private."""
@property
def is_reserved(self) -> bool:
"""True if network is reserved."""
@property
def is_unspecified(self) -> bool:
"""True if network is unspecified."""
def hosts(self) -> Iterator[IPv4Address] | list[IPv4Address]:
"""Iterate over usable host addresses (returns Iterator or list depending on network size)."""
def subnets(self, prefixlen_diff: int = 1, new_prefix: int | None = None) -> Iterator[IPv4Network]:
"""Generate subnets of this network."""
def supernet(self, prefixlen_diff: int = 1, new_prefix: int | None = None) -> IPv4Network:
"""Generate supernet containing this network."""
def subnet_of(self, other: IPv4Network) -> bool:
"""Check if this network is a subnet of another."""
def supernet_of(self, other: IPv4Network) -> bool:
"""Check if this network is a supernet of another."""
def overlaps(self, other: IPv4Network | IPv6Network) -> bool:
"""Check if networks overlap."""
def address_exclude(self, other: IPv4Network) -> Iterator[IPv4Network]:
"""Generate networks that exclude the other network."""
def compare_networks(self, other: IPv4Network) -> int:
"""Compare networks returning -1, 0, or 1."""
class IPv6Network:
"""
IPv6 network representation with subnet and host operations.
"""
def __init__(self, address: object, strict: bool = True) -> None:
"""
Create IPv6 network from CIDR or address/netmask.
Args:
address: Network specification
strict: If False, accept host bits in network address
Raises:
AddressValueError: If network address is invalid
NetmaskValueError: If netmask is invalid
"""
def __contains__(self, other: object) -> bool:
"""Check if address/network is contained in this network."""
def __getitem__(self, n: int) -> IPv6Address:
"""Get nth address in network."""
def __iter__(self) -> Iterator[IPv6Address]:
"""Iterate over all addresses in network."""
def __eq__(self, other: object) -> bool:
"""Check network equality."""
def __hash__(self) -> int:
"""Hash function for use in sets/dicts."""
def __lt__(self, other: Self) -> bool:
"""Compare networks (less than)."""
if sys.version_info >= (3, 11):
def __ge__(self, other: Self) -> bool:
"""Compare networks (greater than or equal)."""
def __gt__(self, other: Self) -> bool:
"""Compare networks (greater than)."""
def __le__(self, other: Self) -> bool:
"""Compare networks (less than or equal)."""
else:
def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool:
"""Compare networks (greater than or equal)."""
def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool:
"""Compare networks (greater than)."""
def __le__(self, other: Self, NotImplemented: Any = ...) -> bool:
"""Compare networks (less than or equal)."""
@property
def network_address(self) -> IPv6Address:
"""First address in network."""
@property
def broadcast_address(self) -> IPv6Address:
"""Last address in network."""
@property
def netmask(self) -> IPv6Address:
"""Network mask."""
@property
def hostmask(self) -> IPv6Address:
"""Host mask (inverse of netmask)."""
@property
def num_addresses(self) -> int:
"""Total number of addresses in network."""
@property
def prefixlen(self) -> int:
"""Network prefix length."""
@property
def with_prefixlen(self) -> str:
"""Network as CIDR string."""
@property
def with_netmask(self) -> str:
"""Network with explicit netmask."""
@property
def with_hostmask(self) -> str:
"""Network with explicit hostmask."""
@property
def is_global(self) -> bool:
"""True if network is global."""
@property
def is_link_local(self) -> bool:
"""True if network is link-local."""
@property
def is_loopback(self) -> bool:
"""True if network is loopback."""
@property
def is_multicast(self) -> bool:
"""True if network is multicast."""
@property
def is_private(self) -> bool:
"""True if network is private."""
@property
def is_reserved(self) -> bool:
"""True if network is reserved."""
@property
def is_unspecified(self) -> bool:
"""True if network is unspecified."""
@property
def is_site_local(self) -> bool:
"""True if network is site-local."""
def hosts(self) -> Iterator[IPv6Address] | list[IPv6Address]:
"""Iterate over usable host addresses (returns Iterator or list depending on network size)."""
def subnets(self, prefixlen_diff: int = 1, new_prefix: int | None = None) -> Iterator[IPv6Network]:
"""Generate subnets of this network."""
def supernet(self, prefixlen_diff: int = 1, new_prefix: int | None = None) -> IPv6Network:
"""Generate supernet containing this network."""
def subnet_of(self, other: IPv6Network) -> bool:
"""Check if this network is a subnet of another."""
def supernet_of(self, other: IPv6Network) -> bool:
"""Check if this network is a supernet of another."""
def overlaps(self, other: IPv4Network | IPv6Network) -> bool:
"""Check if networks overlap."""
def address_exclude(self, other: IPv6Network) -> Iterator[IPv6Network]:
"""Generate networks that exclude the other network."""
def compare_networks(self, other: IPv6Network) -> int:
"""Compare networks returning -1, 0, or 1."""Operations for IP interfaces, which combine an address with its associated network information.
class IPv4Interface(IPv4Address):
"""
IPv4 interface representing an address on a network.
"""
# Direct attributes (not properties)
netmask: IPv4Address
network: IPv4Network
def __eq__(self, other: object) -> bool:
"""Check equality with another interface."""
def __hash__(self) -> int:
"""Hash function for use in sets/dicts."""
@property
def ip(self) -> IPv4Address:
"""The address portion of the interface."""
@property
def hostmask(self) -> IPv4Address:
"""Host mask of the interface."""
@property
def with_prefixlen(self) -> str:
"""Interface as CIDR string."""
@property
def with_netmask(self) -> str:
"""Interface with explicit netmask."""
@property
def with_hostmask(self) -> str:
"""Interface with explicit hostmask."""
class IPv6Interface(IPv6Address):
"""
IPv6 interface representing an address on a network.
"""
# Direct attributes (not properties)
netmask: IPv6Address
network: IPv6Network
def __eq__(self, other: object) -> bool:
"""Check equality with another interface."""
def __hash__(self) -> int:
"""Hash function for use in sets/dicts."""
@property
def ip(self) -> IPv6Address:
"""The address portion of the interface."""
@property
def hostmask(self) -> IPv6Address:
"""Host mask of the interface."""
@property
def with_prefixlen(self) -> str:
"""Interface as CIDR string."""
@property
def with_netmask(self) -> str:
"""Interface with explicit netmask."""
@property
def with_hostmask(self) -> str:
"""Interface with explicit hostmask."""Helper functions for address conversion, network summarization, and mixed-type operations.
def v4_int_to_packed(address: int) -> bytes:
"""
Convert IPv4 integer to 4-byte packed representation.
Args:
address: IPv4 address as integer
Returns:
4-byte packed representation
"""
def v6_int_to_packed(address: int) -> bytes:
"""
Convert IPv6 integer to 16-byte packed representation.
Args:
address: IPv6 address as integer
Returns:
16-byte packed representation
"""
# Overloaded function with multiple signatures
def summarize_address_range(first: IPv4Address, last: IPv4Address) -> Iterator[IPv4Network]: ...
def summarize_address_range(first: IPv6Address, last: IPv6Address) -> Iterator[IPv6Network]: ...
def summarize_address_range(
first: IPv4Address | IPv6Address,
last: IPv4Address | IPv6Address
) -> Iterator[IPv4Network] | Iterator[IPv6Network]:
"""
Summarize a range of addresses into the minimal set of networks.
Args:
first: First address in range
last: Last address in range
Returns:
Iterator of networks covering the range
Raises:
TypeError: If addresses are different versions
ValueError: If first > last
"""
def collapse_addresses(addresses: Iterable[_N]) -> Iterator[_N]:
"""
Collapse overlapping and adjacent networks.
Args:
addresses: Iterable of network objects (IPv4Network or IPv6Network)
Returns:
Iterator of collapsed networks of the same type
"""
# Overloaded function with multiple signatures
def get_mixed_type_key(obj: IPv4Address | IPv6Address) -> tuple[int, IPv4Address | IPv6Address]: ...
def get_mixed_type_key(obj: IPv4Network) -> tuple[int, IPv4Address, IPv4Address]: ...
def get_mixed_type_key(obj: IPv6Network) -> tuple[int, IPv6Address, IPv6Address]: ...
def get_mixed_type_key(
obj: IPv4Address | IPv6Address | IPv4Network | IPv6Network
) -> tuple[int, IPv4Address | IPv6Address] | tuple[int, IPv4Address, IPv4Address] | tuple[int, IPv6Address, IPv6Address]:
"""
Generate sorting key for mixed IPv4/IPv6 objects.
Args:
obj: Address or network object
Returns:
Tuple for sorting mixed-type collections
"""IPV4LENGTH: int = 32
"""Length of IPv4 addresses in bits."""
IPV6LENGTH: int = 128
"""Length of IPv6 addresses in bits."""class AddressValueError(ValueError):
"""
Exception raised when an invalid IP address is provided.
"""
class NetmaskValueError(ValueError):
"""
Exception raised when an invalid netmask is provided.
"""import sys
from typing import Any, Final, Generic, Literal, TypeVar, overload
from typing_extensions import Self, TypeAlias
from collections.abc import Iterable, Iterator
# Type variables used throughout the module
_A = TypeVar("_A", IPv4Address, IPv6Address)
_N = TypeVar("_N", IPv4Network, IPv6Network)
# Type aliases for flexible input types
_RawIPAddress: TypeAlias = int | str | bytes | IPv4Address | IPv6Address
_RawNetworkPart: TypeAlias = IPv4Network | IPv6Network | IPv4Interface | IPv6Interface