Multiaddr Python Implementation
Multiaddr is a Python library that provides an implementation of jbenet's multiaddr specification, designed for future-proof, composable, and efficient network addresses. It aims to solve ambiguities in traditional network addressing by making addresses self-describing, specifying both protocol and network address. The library supports various protocols like IPv4, IPv6, TCP, UDP, DNS, and more, offering both human-readable and machine-readable representations. It is currently at version 0.2.0 and receives active development and releases.
Warnings
- breaking Support for Python versions prior to 3.10 was dropped starting from version 0.0.10. Attempting to use `multiaddr` on older Python environments (e.g., Python 3.4-3.9) will result in incompatibility errors.
- deprecated The `bytes_addr` keyword argument for `Multiaddr` constructor when creating an instance from bytes is deprecated. Instead of `Multiaddr(bytes_addr=some_bytes)`, pass the bytes directly: `Multiaddr(some_bytes)`.
- gotcha Asynchronous DNS resolution (via the DNSADDR protocol) requires the optional `trio` library. If you intend to use this feature, ensure `trio` is installed alongside `multiaddr`. Without it, attempts to resolve DNS-based multiaddrs might fail or lack async capabilities.
Install
-
pip install multiaddr
Imports
- Multiaddr
from multiaddr import Multiaddr
Quickstart
from multiaddr import Multiaddr
# Construct a Multiaddr from a string
addr_str = "/ip4/127.0.0.1/tcp/8080"
m1 = Multiaddr(addr_str)
print(f"Multiaddr from string: {m1}")
print(f"Protocols: {[p.name for p in m1.protocols()]}")
# Construct from bytes
m2 = Multiaddr(m1.to_bytes())
print(f"Multiaddr from bytes: {m2}")
# Encapsulate another Multiaddr
websocket_addr = Multiaddr("/ws")
encapsulated_addr = m1.encapsulate(websocket_addr)
print(f"Encapsulated Multiaddr: {encapsulated_addr}")
# Decapsulate a protocol
decapsulated_addr = encapsulated_addr.decapsulate(websocket_addr)
print(f"Decapsulated Multiaddr: {decapsulated_addr}")
assert str(m1) == str(decapsulated_addr)