IPAddress vs NetAddr in Python3

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 CIDR block and splits in it to 4 /20s:

#!/usr/bin/env python

import ipaddress

cidr = ""
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: splits in to 4 /20s:
  Subnet #1 =
  Subnet #2 =
  Subnet #3 =
  Subnet #4 =

2 thoughts on “IPAddress vs NetAddr in Python3

    • I agree the subnetting in netaddr is a bit easier because you can specify the prefix length directly:

      from netaddr import IPNetwork
      [IPNetwork(‘’), IPNetwork(‘’), IPNetwork(‘’), IPNetwork(‘’)]

      With ipaddress, it has to be specified in a power. The easy way to do this is take the desired prefix length minus the existing one.

      from ipaddress import ip_network
      [IPv4Network(‘’), IPv4Network(‘’), IPv4Network(‘’), IPv4Network(‘’)]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s