Refactor echo example to use optimal binding address

- Replaced hardcoded listen address with `get_optimal_binding_address` for improved flexibility.
- Imported address validation utilities in `echo.py` and updated `__init__.py` to include new functions.
This commit is contained in:
yashksaini-coder
2025-08-09 01:22:17 +05:30
parent b840eaa7e1
commit fa174230ba
2 changed files with 17 additions and 2 deletions

View File

@ -19,6 +19,11 @@ from libp2p.peer.peerinfo import (
info_from_p2p_addr,
)
from libp2p.utils.address_validation import (
get_optimal_binding_address,
get_available_interfaces,
)
PROTOCOL_ID = TProtocol("/echo/1.0.0")
MAX_READ_LEN = 2**32 - 1
@ -31,8 +36,9 @@ async def _echo_stream_handler(stream: INetStream) -> None:
async def run(port: int, destination: str, seed: int | None = None) -> None:
listen_addr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}")
# CHANGED: previously hardcoded 0.0.0.0
listen_addr = get_optimal_binding_address(port)
if seed:
import random

View File

@ -15,6 +15,12 @@ from libp2p.utils.version import (
get_agent_version,
)
from libp2p.utils.address_validation import (
get_available_interfaces,
get_optimal_binding_address,
expand_wildcard_address,
)
__all__ = [
"decode_uvarint_from_stream",
"encode_delim",
@ -26,4 +32,7 @@ __all__ = [
"decode_varint_from_bytes",
"decode_varint_with_size",
"read_length_prefixed_protobuf",
"get_available_interfaces",
"get_optimal_binding_address",
"expand_wildcard_address",
]