Usage Guidelines
Example Quickstart
from ipprefixtrie import IPPrefixTrie
trie = IPPrefixTrie()
trie.insert("192.168.1.0/24", {"desc": "Private IPv4 range"})
trie.insert("2001:db8::/32", {"desc": "Documentation IPv6 range"})
# Lookup an exact prefix
print(trie.get_exact("192.168.1.0/24"))
# Get longest matching prefix
print(trie.get_longest("192.168.1.100"))
# Find all more specific prefixes
print(list(trie.get_orlonger("192.168.1.0/24")))
# Delete a prefix
trie.delete("192.168.1.0/24")
API Reference
- class ipprefixtrie.IPPrefixTrie[source]
A binary trie for storing and searching IP prefixes efficiently.
- delete(prefix: str, raise_error=True) bool[source]
Deletes the given prefix from the trie.
If it has no children it will clean up nodes up to the next valid prefix.
- Parameters:
- Raises:
InvalidPrefixError – If the prefix format is invalid.
PrefixNotFoundError – If the match is not found and raise_error is True.
- Returns:
True if deleted, false is not found.
- Return type:
- get_exact(prefix: str, raise_error=True) tuple[str, Any] | None[source]
Retrieves an exact prefix match.
- Parameters:
- Raises:
InvalidPrefixError – If the prefix format is invalid.
PrefixNotFoundError – If the prefix is not found and raise_error is True.
- Returns:
A tuple containing the prefix as a string and its associated metadata if found, otherwise None.
- Return type:
- get_longest(prefix: str, raise_error=True) tuple[str, Any] | None[source]
Finds the longest matching prefix.
- Parameters:
- Raises:
InvalidPrefixError – If the prefix format is invalid.
PrefixNotFoundError – If the match is not found and raise_error is True.
- Returns:
A tuple containing the prefix as a string and its associated metadata if found, otherwise None.
- Return type:
- get_orlonger(prefix: str) Generator[tuple[str, Any], None, None] | None[source]
Yields orlonger prefixes.
- Parameters:
prefix (str) – The IPv4 or Ipv6 prefix in CIDR notation.
- Raises:
InvalidPrefixError – If the prefix format is invalid.
- Yields:
tuple – (matching prefix as str, metadata)