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

@ -125,7 +125,7 @@ def main() -> None:
where <DESTINATION> is the multiaddress of the previous listener host.
"""
example_maddr = (
"/ip4/127.0.0.1/tcp/8000/p2p/QmQn4SwGkDZKkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q"
"/ip4/[HOST_IP]/tcp/8000/p2p/QmQn4SwGkDZKkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q"
)
parser = argparse.ArgumentParser(description=description)
parser.add_argument("-p", "--port", default=0, type=int, help="source port number")

View File

@ -43,13 +43,22 @@ async def _echo_stream_handler(stream: INetStream) -> None:
async def run_server(port: int, seed: int | None = None) -> None:
"""Run echo server with QUIC transport."""
from libp2p.utils.address_validation import find_free_port
from libp2p.utils.address_validation import (
find_free_port,
get_available_interfaces,
get_optimal_binding_address,
)
if port <= 0:
port = find_free_port()
# For QUIC, we need to use UDP addresses - use loopback for security
listen_addr = Multiaddr(f"/ip4/127.0.0.1/udp/{port}/quic")
# For QUIC, we need UDP addresses - use the new address paradigm
tcp_addrs = get_available_interfaces(port)
# Convert TCP addresses to QUIC addresses
quic_addrs = []
for addr in tcp_addrs:
addr_str = str(addr).replace("/tcp/", "/udp/") + "/quic"
quic_addrs.append(Multiaddr(addr_str))
if seed:
import random
@ -69,7 +78,7 @@ async def run_server(port: int, seed: int | None = None) -> None:
)
# Server mode: start listener
async with host.run(listen_addrs=[listen_addr]):
async with host.run(listen_addrs=quic_addrs):
try:
print(f"I am {host.get_id().to_string()}")
host.set_stream_handler(PROTOCOL_ID, _echo_stream_handler)
@ -81,11 +90,13 @@ async def run_server(port: int, seed: int | None = None) -> None:
for addr in all_addrs:
print(f"{addr}")
# Use the first address as the default for the client command
default_addr = all_addrs[0]
# Use optimal address for the client command
optimal_tcp = get_optimal_binding_address(port)
optimal_quic_str = str(optimal_tcp).replace("/tcp/", "/udp/") + "/quic"
optimal_quic_with_peer = f"{optimal_quic_str}/p2p/{host.get_id().to_string()}"
print(
f"\nRun this from the same folder in another console:\n\n"
f"python3 ./examples/echo/echo_quic.py -d {default_addr}\n"
f"python3 ./examples/echo/echo_quic.py -d {optimal_quic_with_peer}\n"
)
print("Waiting for incoming QUIC connections...")
await trio.sleep_forever()
@ -167,7 +178,7 @@ def main() -> None:
where <DESTINATION> is the QUIC multiaddress of the previous listener host.
"""
example_maddr = "/ip4/127.0.0.1/udp/8000/quic/p2p/QmQn4SwGkDZKkUEpBRBv"
example_maddr = "/ip4/[HOST_IP]/udp/8000/quic/p2p/QmQn4SwGkDZKkUEpBRBv"
parser = argparse.ArgumentParser(description=description)
parser.add_argument("-p", "--port", default=0, type=int, help="UDP port number")