mirror of
https://github.com/varun-r-mallya/py-libp2p.git
synced 2025-12-31 20:36:24 +00:00
refactor: update examples to use available interfaces for listening addresses and improve logging configuration
This commit is contained in:
@ -1,4 +1,5 @@
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
import multiaddr
|
||||
import trio
|
||||
@ -16,6 +17,11 @@ from libp2p.peer.peerinfo import (
|
||||
info_from_p2p_addr,
|
||||
)
|
||||
|
||||
# Configure minimal logging
|
||||
logging.basicConfig(level=logging.WARNING)
|
||||
logging.getLogger("multiaddr").setLevel(logging.WARNING)
|
||||
logging.getLogger("libp2p").setLevel(logging.WARNING)
|
||||
|
||||
PING_PROTOCOL_ID = TProtocol("/ipfs/ping/1.0.0")
|
||||
PING_LENGTH = 32
|
||||
RESP_TIMEOUT = 60
|
||||
@ -55,20 +61,33 @@ async def send_ping(stream: INetStream) -> None:
|
||||
|
||||
|
||||
async def run(port: int, destination: str) -> None:
|
||||
listen_addr = multiaddr.Multiaddr(f"/ip4/127.0.0.1/tcp/{port}")
|
||||
host = new_host(listen_addrs=[listen_addr])
|
||||
from libp2p.utils.address_validation import find_free_port, get_available_interfaces
|
||||
|
||||
async with host.run(listen_addrs=[listen_addr]), trio.open_nursery() as nursery:
|
||||
if port <= 0:
|
||||
port = find_free_port()
|
||||
|
||||
listen_addrs = get_available_interfaces(port)
|
||||
host = new_host(listen_addrs=listen_addrs)
|
||||
|
||||
async with host.run(listen_addrs=listen_addrs), trio.open_nursery() as nursery:
|
||||
# Start the peer-store cleanup task
|
||||
nursery.start_soon(host.get_peerstore().start_cleanup_task, 60)
|
||||
|
||||
if not destination:
|
||||
host.set_stream_handler(PING_PROTOCOL_ID, handle_ping)
|
||||
|
||||
# Get all available addresses with peer ID
|
||||
all_addrs = host.get_addrs()
|
||||
|
||||
print("Listener ready, listening on:\n")
|
||||
for addr in all_addrs:
|
||||
print(f"{addr}")
|
||||
|
||||
# Use the first address as the default for the client command
|
||||
default_addr = all_addrs[0]
|
||||
print(
|
||||
"Run this from the same folder in another console:\n\n"
|
||||
f"ping-demo "
|
||||
f"-d {host.get_addrs()[0]}\n"
|
||||
f"\nRun this from the same folder in another console:\n\n"
|
||||
f"ping-demo -d {default_addr}\n"
|
||||
)
|
||||
print("Waiting for incoming connection...")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user