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 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
Advertisement

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
      list(IPNetwork(‘198.18.128.0/18’).subnet(20))
      [IPNetwork(‘198.18.128.0/20’), IPNetwork(‘198.18.144.0/20’), IPNetwork(‘198.18.160.0/20’), IPNetwork(‘198.18.176.0/20’)]

      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
      list(ip_network(‘198.18.128.0/18’).subnets(20-18))
      [IPv4Network(‘198.18.128.0/20’), IPv4Network(‘198.18.144.0/20’), IPv4Network(‘198.18.160.0/20’), IPv4Network(‘198.18.176.0/20’)]

      Like

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