Python ipaddress — Networks, Hosts, and Subnets
Network scripts work with addresses as data: is this host inside that subnet, what does this range split into, and which of these networks overlap. The ipaddress module gives those questions typed answers with no package to install: an address is an object, a network knows its first and last address, and membership, splitting, and overlap are methods instead of string work. This guide takes those parts in turn, then IPv6, sorting, collapsing ranges, and the errors a malformed address raises.
Written November 16, 2026 · Tested with Python 3.12.3 · 11 min read
- The main program: address, network, and interface
- What a network knows
- Membership, overlap, and containment
- Splitting: subnets and supernets
Written November 16, 2026
Tested with Python 3.12.3
What this guide is
The ipaddress module turns IP addresses and networks into objects. An address object knows its version and whether it is private, a network object knows its network address, broadcast address, and how many addresses it holds, and an interface object pairs an address with the network it sits in. The factory functions ip_address, ip_network, and ip_interface pick the IPv4 or IPv6 class from the value itself, so the same code handles both families until a step is family-specific.
The main program: address, network, and interface
The three factory functions answer three different questions. ip_address builds one host address, ip_network builds the network a prefix describes, and ip_interface builds an address together with its prefix, keeping the host bits the network form rejects:
import ipaddress
addr = ipaddress.ip_address("192.168.1.10")
print(type(addr).__name__, addr.version, addr.is_private)
net = ipaddress.ip_network("192.168.1.0/24")
print(type(net).__name__, net)
iface = ipaddress.ip_interface("192.168.1.10/24")
print(type(iface).__name__, iface, iface.network)
print(iface.ip == addr)
The exact output:
IPv4Address 4 True
IPv4Network 192.168.1.0/24
IPv4Interface 192.168.1.10/24 192.168.1.0/24
True
The interface carries that address plus its network: the interface itself does not compare equal to the plain address, but its ip attribute does, as the last line shows. The network form is the strict one: it describes the network itself, so an address with host bits set inside the prefix is an error there, covered in the traps section. Code that starts from a host and a prefix length, the form a configuration file usually holds, wants the interface.
What a network knows
A network object carries the arithmetic a subnet calculation does by hand. The network address is the first address, the broadcast address is the last in an IPv4 network, the netmask and hostmask spell the prefix out as addresses, and num_addresses counts every address in the range, usable or not:
import ipaddress
net = ipaddress.ip_network("192.168.1.0/24")
print(net.network_address, net.broadcast_address)
print(net.netmask, net.hostmask, net.prefixlen)
print(net.num_addresses)
print(net.with_prefixlen, net.with_netmask)
small = ipaddress.ip_network("10.0.0.0/30")
print(small.num_addresses, list(small.hosts()))
print(list(ipaddress.ip_network("10.0.0.0/31").hosts()))
print(list(ipaddress.ip_network("10.0.0.0/32").hosts()))
The exact output:
192.168.1.0 192.168.1.255
255.255.255.0 0.0.0.255 24
256
192.168.1.0/24 192.168.1.0/255.255.255.0
4 [IPv4Address('10.0.0.1'), IPv4Address('10.0.0.2')]
[IPv4Address('10.0.0.0'), IPv4Address('10.0.0.1')]
[IPv4Address('10.0.0.0')]
Two details in that output save debugging time. hosts() omits the network and broadcast addresses in a normal IPv4 network, which is why the /30 lists two hosts from four addresses. The two smallest networks are the exceptions: a /31, the point-to-point form, returns both of its addresses, and a /32 returns the single address itself, where there is no separate network address to omit. Iterating a network directly, rather than through hosts(), yields every address including the network and broadcast ones.
Membership, overlap, and containment
Three tests cover most of the questions a script asks about two ranges. The in operator tests whether an address sits inside a network; it does not test one network against another, and a network on the left of in returns False even when the containment holds. Network against network is what subnet_of and supernet_of are for, and overlaps reports whether two networks share any address:
import ipaddress
net = ipaddress.ip_network("192.168.1.0/24")
print(ipaddress.ip_address("192.168.1.42") in net)
print(ipaddress.ip_address("192.168.2.42") in net)
a = ipaddress.ip_network("10.0.0.0/8")
b = ipaddress.ip_network("10.1.0.0/16")
print(b.subnet_of(a), a.supernet_of(b))
print(a.overlaps(b))
print(ipaddress.ip_network("172.16.0.0/12").overlaps(b))
print(ipaddress.ip_address("8.8.8.8").is_private)
print(ipaddress.ip_address("192.168.1.1").is_private)
The exact output:
True
False
True True
True
False
False
True
The membership test works on the address value, not on its text, so a script never compares address strings or splits them on dots. overlaps is symmetric, while the subnet and supernet tests are not: calling them the wrong way round returns False rather than raising, so a script that needs the direction has to ask for it, as the program does by asking both ways on the same pair.
Splitting: subnets and supernets
A network splits into equal smaller networks with subnets, which takes either how much longer the new prefix should be or the new prefix length itself. supernet runs the other way and returns the larger network that contains this one. address_exclude returns the pieces of a network that remain after a smaller network inside it is removed:
import ipaddress
net = ipaddress.ip_network("192.168.1.0/24")
print(list(net.subnets()))
print(list(net.subnets(new_prefix=26)))
print(list(net.subnets(prefixlen_diff=2)))
print(net.supernet())
print(list(ipaddress.ip_network("10.0.0.0/8").address_exclude(ipaddress.ip_network("10.0.0.0/9"))))
The exact output:
[IPv4Network('192.168.1.0/25'), IPv4Network('192.168.1.128/25')]
[IPv4Network('192.168.1.0/26'), IPv4Network('192.168.1.64/26'), IPv4Network('192.168.1.128/26'), IPv4Network('192.168.1.192/26')]
[IPv4Network('192.168.1.0/26'), IPv4Network('192.168.1.64/26'), IPv4Network('192.168.1.128/26'), IPv4Network('192.168.1.192/26')]
192.168.0.0/23
[IPv4Network('10.128.0.0/9')]
The default split adds one to the prefix length, which doubles the count and halves the size each time it is applied. Asking for a new prefix that is shorter than the network's own raises an error instead of returning a partial list. The exclude call returns an iterator, which the program lists, because removing a network from the middle of a larger one can leave pieces of different sizes; removing the lower half here leaves exactly one.
IPv6: the same objects, a longer address
The factory functions return the IPv6 classes for an IPv6 value, and the network methods work the same way. What changes is the text form and the extra properties: an IPv6 address prints compressed, exploded spells every group out, and a link-local address carries the idea of a scope, which the address records as scope_id when the text supplies one after a percent sign:
import ipaddress
addr = ipaddress.ip_address("2001:db8::1")
print(type(addr).__name__, addr.version)
print(addr.compressed, addr.exploded)
net = ipaddress.ip_network("2001:db8::/32")
print(addr in net, net.num_addresses)
print(net.network_address)
local = ipaddress.ip_address("fe80::1%eth0")
print(local.is_link_local, local.scope_id)
print(ipaddress.ip_address("::1").is_loopback)
The exact output:
IPv6Address 6
2001:db8::1 2001:0db8:0000:0000:0000:0000:0000:0001
True 79228162514264337593543950336
2001:db8::
True eth0
True
The size line is the one to plan around: a /32 IPv6 network holds 2 to the 96th power addresses, so code that lists or counts hosts in IPv4 needs a different shape in IPv6, where a script samples or calculates rather than enumerating. The classification properties, such as is_link_local and is_loopback, exist on both families and answer from the address value alone.
Sorting, ranges, and collapsing networks
Addresses compare as numbers, so a plain sort puts them in network order, which a sort of their text forms does not. Two module functions work on collections: summarize_address_range turns a first and last address into the networks that cover exactly that range, and collapse_addresses merges a list of networks into the smallest list that covers the same addresses, dropping any network that a larger one already contains:
import ipaddress
addrs = [ipaddress.ip_address(x) for x in ("10.0.0.10", "10.0.0.2", "10.0.0.1")]
print([str(a) for a in sorted(addrs)])
first = ipaddress.ip_address("192.168.1.0")
last = ipaddress.ip_address("192.168.1.130")
print(list(ipaddress.summarize_address_range(first, last)))
nets = [ipaddress.ip_network(x) for x in ("192.168.0.0/24", "192.168.1.0/24", "192.168.0.0/25")]
print(list(ipaddress.collapse_addresses(nets)))
The exact output:
['10.0.0.1', '10.0.0.2', '10.0.0.10']
[IPv4Network('192.168.1.0/25'), IPv4Network('192.168.1.128/31'), IPv4Network('192.168.1.130/32')]
[IPv4Network('192.168.0.0/23')]
The text sort trap is worth naming: as strings, 10.0.0.10 sorts before 10.0.0.2, because the character 1 sorts before 2. Sorting the objects avoids it with no extra key. The collapse step is the tidy-up a firewall or routing script needs after collecting networks from several places: adjacent networks that join cleanly merge, and a network contained in another disappears from the result.
The traps: host bits, bad addresses, and mixed versions
ip_network raises ValueError when the address has host bits set for the prefix given, because the value then names a host, not the network. Passing strict=False masks the host bits off and returns the network, and ip_interface is the other answer when the host part is the point. A malformed address raises ValueError — the family classes give more specific errors — and mixing an IPv4 and an IPv6 value in one comparison raises TypeError:import ipaddress
for text in ("192.168.1.1/24", "not-an-address"):
try:
ipaddress.ip_network(text)
except ValueError as e:
print(type(e).__name__ + ":", e)
for fn in (lambda: ipaddress.IPv4Address("256.0.0.1"),
lambda: ipaddress.IPv4Network("192.168.1.0/33")):
try:
fn()
except ValueError as e:
print(type(e).__name__ + ":", e)
print(ipaddress.ip_network("192.168.1.1/24", strict=False))
try:
ipaddress.ip_address("10.0.0.1") < ipaddress.ip_address("::1")
except TypeError as e:
print("TypeError:", e)
The exact output:
ValueError: 192.168.1.1/24 has host bits set
ValueError: 'not-an-address' does not appear to be an IPv4 or IPv6 network
AddressValueError: Octet 256 (> 255) not permitted in '256.0.0.1'
NetmaskValueError: '33' is not a valid netmask
192.168.1.0/24
TypeError: 10.0.0.1 and ::1 are not of the same version
The error types split the failures usefully. The factory functions try both families, so a value neither family accepts draws the plain ValueError in the second line, while the host-bits failure names its own cause. Asking a family class directly, as the middle two calls do, gives the specific subclasses: a bad address raises AddressValueError and a bad netmask raises NetmaskValueError, both under ValueError, so one except ValueError clause catches every parse failure in the module while a program that wants to tell a bad address from a bad prefix can catch the subclasses apart. The version rule is stricter: the module does not order or compare across families at all, so code that holds both sorts and tests each family on its own.
Which choice for which job
| Job | Choice | Why |
|---|---|---|
| One host address | ip_address |
Builds the right family class from the value |
| The network a prefix describes | ip_network |
Strict: the value must be the network itself |
| A host together with its prefix | ip_interface |
Keeps the host bits and exposes the network |
| The usable hosts in an IPv4 network | hosts() |
Omits the network and broadcast addresses, except in /31 and /32 networks |
| Every address in a network | Iterate the network | Includes the network and broadcast addresses |
| A larger network split evenly | subnets |
Takes a prefix difference or a new prefix |
| Networks covering a first-to-last range | summarize_address_range |
Returns exactly the networks that cover the range |
| A collected list of networks tidied | collapse_addresses |
Merges neighbors and drops contained networks |
Checklist
- Build addresses and networks with the factory functions, and let the value pick the family class.
- Use
ip_interfacefor a host with a prefix, and expectip_networkto reject that same value. - Read size from
num_addresses, and never plan to enumerate a large IPv6 network. - Test membership with
inand overlap withoverlaps, not with string work on the text form. - Sort address objects, not their strings, so
10.0.0.2lands before10.0.0.10. - Catch
ValueErroraround parsing, and keep IPv4 and IPv6 values apart in comparisons.
Related guides on this site
- Python subprocess — run, capture, and check — running the system network tools whose output this module then parses and tests.
- Python sorting — sorted, sort, and key functions — the sort and key machinery behind ordering addresses and networks.
- Python files — open, read, and write — reading the address lists and configuration files a network script starts from.
Sources
- Python Standard Library,
ipaddress— the factory functions, network and interface properties,hosts,subnets,supernet, andaddress_exclude, the IPv6 text forms and scope,summarize_address_rangeandcollapse_addresses, and the error classes.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.