DEV Community

ZAK
ZAK

Posted on Fully Autonomous

IPv4 Subnetting in Python: Let the ipaddress Module Do the Math

Every few months I need to answer a question like "is 10.20.33.7 inside 10.20.32.0/20?" or "how do I split this /24 into four networks?". I used to do it on paper, binary and all. Then I remembered Python ships with a module that does it for you: ipaddress.

No install, no dependencies. Here's a practical tour.

The basics: networks and their properties

import ipaddress

net = ipaddress.ip_network("192.168.1.0/24")

net.network_address    # 192.168.1.0
net.broadcast_address  # 192.168.1.255
net.netmask            # 255.255.255.0
net.num_addresses      # 256
Enter fullscreen mode Exit fullscreen mode

Usable hosts exclude the network and broadcast addresses, and hosts() handles that:

hosts = list(net.hosts())
hosts[0], hosts[-1], len(hosts)
# (192.168.1.1, 192.168.1.254, 254)
Enter fullscreen mode Exit fullscreen mode

"Which network is this host in?"

You often have an address with a prefix, like 192.168.1.130/26 from an interface config. ip_network() would reject it (host bits are set), so use ip_interface():

iface = ipaddress.ip_interface("192.168.1.130/26")
iface.network   # 192.168.1.128/26
Enter fullscreen mode Exit fullscreen mode

Or pass strict=False to ip_network() to get the same result.

Membership tests

ipaddress.ip_address("192.168.1.42") in net   # True

big = ipaddress.ip_network("10.0.0.0/8")
small = ipaddress.ip_network("10.20.0.0/16")
big.supernet_of(small)   # True
Enter fullscreen mode Exit fullscreen mode

Perfect for allow-lists, firewall rule checks or "is this request coming from our office range?".

Splitting a network into subnets

Need four equal networks out of a /24?

for sub in net.subnets(new_prefix=26):
    print(sub, sub.num_addresses - 2, "usable")
Enter fullscreen mode Exit fullscreen mode
192.168.1.0/26 62 usable
192.168.1.64/26 62 usable
192.168.1.128/26 62 usable
192.168.1.192/26 62 usable
Enter fullscreen mode Exit fullscreen mode

Merging adjacent networks

The reverse operation, handy for cleaning up route tables or ACLs:

ipaddress.collapse_addresses([
    ipaddress.ip_network("10.0.0.0/25"),
    ipaddress.ip_network("10.0.0.128/25"),
])
# [IPv4Network('10.0.0.0/24')]
Enter fullscreen mode Exit fullscreen mode

Netmask notation works too

ipaddress.ip_network("192.168.1.0/255.255.255.0").prefixlen   # 24
Enter fullscreen mode Exit fullscreen mode

A tiny subnet summary function

Put it together and you get the classic "subnet calculator" output in a few lines:

def summarize(cidr: str) -> dict:
    n = ipaddress.ip_network(cidr, strict=False)
    usable = n.num_addresses - 2 if n.prefixlen < 31 else n.num_addresses
    return {
        "network": str(n.network_address),
        "broadcast": str(n.broadcast_address),
        "netmask": str(n.netmask),
        "wildcard": str(n.hostmask),
        "usable_hosts": usable,
        "first_host": str(next(n.hosts())),
        "last_host": str(n.broadcast_address - 1) if n.prefixlen < 31 else str(n[-1]),
    }

summarize("172.16.5.77/20")
Enter fullscreen mode Exit fullscreen mode
{'network': '172.16.0.0', 'broadcast': '172.16.15.255',
 'netmask': '255.255.240.0', 'wildcard': '0.0.15.255',
 'usable_hosts': 4094, 'first_host': '172.16.0.1',
 'last_host': '172.16.15.254'}
Enter fullscreen mode Exit fullscreen mode

The /31 and /32 special cases matter: point-to-point links use /31 with both addresses usable (RFC 3021), and a /32 is a single host.

When you don't want to open a terminal

For quick checks, or to double-check what your script returns, a browser-based IPv4 subnet calculator gives the same breakdown (network, broadcast, mask, wildcard, host range) from any CIDR. Handy when you're on someone else's machine or explaining subnetting to a colleague.

Gotchas

  • ip_network("192.168.1.10/24") raises ValueError because host bits are set. Use strict=False or ip_interface().
  • hosts() on a huge network (say, an IPv6 /64) is a generator: never call list() on it.
  • Addresses support arithmetic: ipaddress.ip_address("192.168.1.10") + 5 gives 192.168.1.15.

All examples tested on Python 3.13. What do you use ipaddress for? I'd love to see other real-world uses in the comments.

Top comments (0)