I’d heard about netaddr a few weeks ago and had made a note to start. What I learned today as a similar library called ipaddress is included in Python 3, and offers most of netaddr’s functionality just with different syntax.

It is very handy for subnetting. Here’s some basic code that takes the 198.18.128.0/18 CIDR block and splits in it to 4 /20s:

#!/usr/bin/env python

import ipaddress

cidr = "198.18.128.0/18"
subnet_size = "/20"

[network_address, prefix_len] = cidr.split('/')
power = int(subnet_size[1:]) - int(prefix_len)
subnets = list(ipaddress.ip_network(cidr).subnets(power))

print("{} splits in to {} {}s:".format(cidr, len(subnets), subnet_size))
for _ in range(len(subnets)):
    print("  Subnet #{} = {}".format(_+1, subnets[_]))

Here’s the output:

198.18.128.0/18 splits in to 4 /20s:
  Subnet #1 = 198.18.128.0/20
  Subnet #2 = 198.18.144.0/20
  Subnet #3 = 198.18.160.0/20
  Subnet #4 = 198.18.176.0/20