skip to navigation
skip to content

pysubnettree 0.26

The PySubnetTree package provides a Python data structure SubnetTreethat maps subnets given in CIDR notation (incl. corresponding IPv6versions) to Python objects. Lookups are performed by longest-prefixmatching.


The PySubnetTree package provides a Python data structure SubnetTree which maps subnets given in CIDR notation (incl. corresponding IPv6 versions) to Python objects. Lookups are performed by longest-prefix matching.


You can find the latest PySubnetTree release for download at

PySubnetTree’s git repository is located at git:// You can browse the repository here.

This document describes PySubnetTree 0.26. See the CHANGES file for version history.


A simple example which associates CIDR prefixes with strings:

>>> import SubnetTree
>>> t = SubnetTree.SubnetTree()
>>> t[""] = "Network 1"
>>> t[""] = "Network 1, Subnet 42"
>>> print("" in t)
>>> print(t[""])
Network 1, Subnet 42
>>> print(t[""])
Network 1
>>> print("" in t)
>>> try:
...     print(t[""])
... except KeyError as err:
...     print("Error: %s not found" % err)
Error: '' not found

PySubnetTree also supports IPv6 addresses and prefixes:

>>> import SubnetTree
>>> t = SubnetTree.SubnetTree()
>>> t["2001:db8::/32"] = "Company 1"
>>> t["2001:db8:4000::/48"] = "Company 1, Site 1"
>>> t["2001:db8:4000:abcd::"]
Company 1, Site 1
>>> t["2001:db8:fe:1234::"]
Company 1

By default, CIDR prefixes and IP addresses are given as strings. Alternatively, a SubnetTree object can be switched into binary mode, in which single addresses are passed in the form of packed binary strings as, e.g., returned by socket.inet_aton:

>>> t.get_binary_lookup_mode()
>>> t.set_binary_lookup_mode(True)
>>> t.get_binary_lookup_mode()
>>> import socket
>>> print(t[socket.inet_aton("")])
Network 1, Subnet 42

A SubnetTree also provides methods insert(prefix,object=None) for insertion of prefixes (object can be skipped to use the tree like a set), and remove(prefix) for removing entries (remove performs an _exact_ match rather than longest-prefix).

Internally, the CIDR prefixes of a SubnetTree are managed by a Patricia tree data structure and lookups are therefore efficient even with a large number of prefixes.

PySubnetTree comes with a BSD license.


This package requires Python 2.4 or newer.


Installation is pretty simple:

> python install
File Type Py Version Uploaded on Size
pysubnettree-0.26.tar.gz (md5, pgp) Source 2017-04-28 49KB