Update examples to use dynamic host IP instead of hardcoded localhost

This commit is contained in:
yashksaini-coder
2025-09-18 02:09:51 +05:30
parent b01f2bd105
commit 4dd2454a46
15 changed files with 114 additions and 49 deletions

View File

@ -36,6 +36,9 @@ from libp2p.identity.identify_push import (
from libp2p.peer.peerinfo import (
info_from_p2p_addr,
)
from libp2p.utils.address_validation import (
get_available_interfaces,
)
# Configure logging
logger = logging.getLogger(__name__)
@ -207,13 +210,13 @@ async def main() -> None:
ID_PUSH, create_custom_identify_push_handler(host_2, "Host 2")
)
# Start listening on random ports using the run context manager
listen_addr_1 = multiaddr.Multiaddr("/ip4/127.0.0.1/tcp/0")
listen_addr_2 = multiaddr.Multiaddr("/ip4/127.0.0.1/tcp/0")
# Start listening on available interfaces using random ports
listen_addrs_1 = get_available_interfaces(0) # 0 for random port
listen_addrs_2 = get_available_interfaces(0) # 0 for random port
async with (
host_1.run([listen_addr_1]),
host_2.run([listen_addr_2]),
host_1.run(listen_addrs_1),
host_2.run(listen_addrs_2),
trio.open_nursery() as nursery,
):
# Start the peer-store cleanup task

View File

@ -14,7 +14,7 @@ Usage:
python identify_push_listener_dialer.py
# Then in another console, run as a dialer (default port 8889):
python identify_push_listener_dialer.py -d /ip4/127.0.0.1/tcp/8888/p2p/PEER_ID
python identify_push_listener_dialer.py -d /ip4/[HOST_IP]/tcp/8888/p2p/PEER_ID
(where PEER_ID is the peer ID displayed by the listener)
"""
@ -291,10 +291,12 @@ async def run_dialer(
identify_push_handler_for(host, use_varint_format=use_varint_format),
)
# Start listening on a different port
listen_addr = multiaddr.Multiaddr(f"/ip4/127.0.0.1/tcp/{port}")
# Start listening on available interfaces
from libp2p.utils.address_validation import get_available_interfaces
async with host.run([listen_addr]):
listen_addrs = get_available_interfaces(port)
async with host.run(listen_addrs):
logger.info("Dialer host ready!")
print("Dialer host ready!")