cidr-trie

raw JSON →
3.1.2 verified Mon Apr 27 auth: no python

A Python library for storing and searching CIDR prefixes in a trie structure. It enables efficient longest-prefix matching of IP addresses against a set of CIDR blocks. The current version is 3.1.2. Release cadence is intermittent.

pip install cidr-trie
error ModuleNotFoundError: No module named 'cidr_trie'
cause Package name is 'cidr-trie' but import is 'cidr_trie'.
fix
Run pip install cidr-trie and import as from cidr_trie import CidrTrie.
error TypeError: 'CidrTrie' object does not support item assignment
cause Trying to insert using `trie['10.0.0.0/8'] = IpNetwork(...)` instead of `trie.insert()`
fix
Use trie.insert(IpNetwork('10.0.0.0/8')) to add prefixes.
deprecated The method `find_longest_prefix` is deprecated since v3.0.0; use `trie[ip]` instead.
fix Replace `trie.find_longest_prefix(ip)` with `trie[ip]`
breaking CidrTrie.no_prefix() was removed in v3.0.0. Use `trie[ip]` and catch KeyError or pre-check with `ip in trie`.
fix Replace `trie.no_prefix(ip)` with `try: result = trie[ip]; except KeyError: # handle missing`
gotcha CidrTrie is not threadsafe. Concurrent modifications may corrupt internal state.
fix Use a threading lock when modifying the trie from multiple threads.

Create a trie, insert CIDR prefixes, and perform longest-prefix matching.

from cidr_trie import CidrTrie, IpNetwork

trie = CidrTrie()
trie.insert(IpNetwork('10.0.0.0/8'))
trie.insert(IpNetwork('10.0.0.0/16'))
result = trie['10.0.0.5']
print(result)  # IpNetwork('10.0.0.0/16')