From 4e9fa87477419eb23abec635df1dee3f81679956 Mon Sep 17 00:00:00 2001 From: Abhinav Agarwalla <120122716+lla-dane@users.noreply.github.com> Date: Tue, 10 Jun 2025 00:29:11 +0530 Subject: [PATCH] Updated examples to automatically use random port (#661) * updated examples to automatically use random port * Refactor examples to use shared utils for port selection (#1) --------- Co-authored-by: acul71 <34693171+acul71@users.noreply.github.com> --- examples/chat/chat.py | 12 ++------ examples/echo/echo.py | 14 +++------ examples/identify/identify.py | 15 ++++------ .../identify_push_listener_dialer.py | 30 +++++-------------- examples/ping/ping.py | 12 ++------ newsfragments/661.docs.rst | 1 + 6 files changed, 24 insertions(+), 60 deletions(-) create mode 100644 newsfragments/661.docs.rst diff --git a/examples/chat/chat.py b/examples/chat/chat.py index 650c8aed..87e7a44a 100755 --- a/examples/chat/chat.py +++ b/examples/chat/chat.py @@ -40,7 +40,6 @@ async def write_data(stream: INetStream) -> None: async def run(port: int, destination: str) -> None: - localhost_ip = "127.0.0.1" listen_addr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}") host = new_host() async with host.run(listen_addrs=[listen_addr]), trio.open_nursery() as nursery: @@ -54,8 +53,8 @@ async def run(port: int, destination: str) -> None: print( "Run this from the same folder in another console:\n\n" - f"chat-demo -p {int(port) + 1} " - f"-d /ip4/{localhost_ip}/tcp/{port}/p2p/{host.get_id().pretty()}\n" + f"chat-demo " + f"-d {host.get_addrs()[0]}\n" ) print("Waiting for incoming connection...") @@ -87,9 +86,7 @@ def main() -> None: "/ip4/127.0.0.1/tcp/8000/p2p/QmQn4SwGkDZKkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q" ) parser = argparse.ArgumentParser(description=description) - parser.add_argument( - "-p", "--port", default=8000, type=int, help="source port number" - ) + parser.add_argument("-p", "--port", default=0, type=int, help="source port number") parser.add_argument( "-d", "--destination", @@ -98,9 +95,6 @@ def main() -> None: ) args = parser.parse_args() - if not args.port: - raise RuntimeError("was not able to determine a local port") - try: trio.run(run, *(args.port, args.destination)) except KeyboardInterrupt: diff --git a/examples/echo/echo.py b/examples/echo/echo.py index 382d4f27..535133fa 100644 --- a/examples/echo/echo.py +++ b/examples/echo/echo.py @@ -30,7 +30,6 @@ async def _echo_stream_handler(stream: INetStream) -> None: async def run(port: int, destination: str, seed: int | None = None) -> None: - localhost_ip = "127.0.0.1" listen_addr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}") if seed: @@ -53,8 +52,8 @@ async def run(port: int, destination: str, seed: int | None = None) -> None: print( "Run this from the same folder in another console:\n\n" - f"echo-demo -p {int(port) + 1} " - f"-d /ip4/{localhost_ip}/tcp/{port}/p2p/{host.get_id().pretty()}\n" + f"echo-demo " + f"-d {host.get_addrs()[0]}\n" ) print("Waiting for incoming connections...") await trio.sleep_forever() @@ -73,6 +72,7 @@ async def run(port: int, destination: str, seed: int | None = None) -> None: msg = b"hi, there!\n" await stream.write(msg) + # TODO: check why the stream is closed after the first write ??? # Notify the other side about EOF await stream.close() response = await stream.read() @@ -94,9 +94,7 @@ def main() -> None: "/ip4/127.0.0.1/tcp/8000/p2p/QmQn4SwGkDZKkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q" ) parser = argparse.ArgumentParser(description=description) - parser.add_argument( - "-p", "--port", default=8000, type=int, help="source port number" - ) + parser.add_argument("-p", "--port", default=0, type=int, help="source port number") parser.add_argument( "-d", "--destination", @@ -110,10 +108,6 @@ def main() -> None: help="provide a seed to the random number generator (e.g. to fix peer IDs across runs)", # noqa: E501 ) args = parser.parse_args() - - if not args.port: - raise RuntimeError("was not able to determine a local port") - try: trio.run(run, args.port, args.destination, args.seed) except KeyboardInterrupt: diff --git a/examples/identify/identify.py b/examples/identify/identify.py index ae4d0e53..78cf8805 100644 --- a/examples/identify/identify.py +++ b/examples/identify/identify.py @@ -61,20 +61,20 @@ async def run(port: int, destination: str) -> None: async with host_a.run(listen_addrs=[listen_addr]): print( "First host listening. Run this from another console:\n\n" - f"identify-demo -p {int(port) + 1} " - f"-d /ip4/{localhost_ip}/tcp/{port}/p2p/{host_a.get_id().pretty()}\n" + f"identify-demo " + f"-d {host_a.get_addrs()[0]}\n" ) print("Waiting for incoming identify request...") await trio.sleep_forever() else: # Create second host (dialer) - print(f"dialer (host_b) listening on /ip4/{localhost_ip}/tcp/{port}") listen_addr = multiaddr.Multiaddr(f"/ip4/{localhost_ip}/tcp/{port}") host_b = new_host() async with host_b.run(listen_addrs=[listen_addr]): # Connect to the first host + print(f"dialer (host_b) listening on {host_b.get_addrs()[0]}") maddr = multiaddr.Multiaddr(destination) info = info_from_p2p_addr(maddr) print(f"Second host connecting to peer: {info.peer_id}") @@ -104,13 +104,11 @@ def main() -> None: """ example_maddr = ( - "/ip4/127.0.0.1/tcp/8888/p2p/QmQn4SwGkDZkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q" + "/ip4/127.0.0.1/tcp/8888/p2p/QmQn4SwGkDZKkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q" ) parser = argparse.ArgumentParser(description=description) - parser.add_argument( - "-p", "--port", default=8888, type=int, help="source port number" - ) + parser.add_argument("-p", "--port", default=0, type=int, help="source port number") parser.add_argument( "-d", "--destination", @@ -119,9 +117,6 @@ def main() -> None: ) args = parser.parse_args() - if not args.port: - raise RuntimeError("failed to determine local port") - try: trio.run(run, *(args.port, args.destination)) except KeyboardInterrupt: diff --git a/examples/identify_push/identify_push_listener_dialer.py b/examples/identify_push/identify_push_listener_dialer.py index 7df222d7..294b0d17 100644 --- a/examples/identify_push/identify_push_listener_dialer.py +++ b/examples/identify_push/identify_push_listener_dialer.py @@ -56,9 +56,6 @@ from libp2p.peer.peerinfo import ( # Configure logging logger = logging.getLogger("libp2p.identity.identify-push-example") -# Default port configuration -DEFAULT_PORT = 8888 - def custom_identify_push_handler_for(host): """ @@ -241,25 +238,16 @@ def main() -> None: """Parse arguments and start the appropriate mode.""" description = """ This program demonstrates the libp2p identify/push protocol. - Without arguments, it runs as a listener on port 8888. - With -d parameter, it runs as a dialer on port 8889. + Without arguments, it runs as a listener on random port. + With -d parameter, it runs as a dialer on random port. """ example = ( - f"/ip4/127.0.0.1/tcp/{DEFAULT_PORT}/p2p/" - "QmQn4SwGkDZkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q" + "/ip4/127.0.0.1/tcp/8000/p2p/QmQn4SwGkDZKkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q" ) parser = argparse.ArgumentParser(description=description) - parser.add_argument( - "-p", - "--port", - type=int, - help=( - f"port to listen on (default: {DEFAULT_PORT} for listener, " - f"{DEFAULT_PORT + 1} for dialer)" - ), - ) + parser.add_argument("-p", "--port", default=0, type=int, help="source port number") parser.add_argument( "-d", "--destination", @@ -270,13 +258,11 @@ def main() -> None: try: if args.destination: - # Run in dialer mode with default port DEFAULT_PORT + 1 if not specified - port = args.port if args.port is not None else DEFAULT_PORT + 1 - trio.run(run_dialer, port, args.destination) + # Run in dialer mode with random available port if not specified + trio.run(run_dialer, args.port, args.destination) else: - # Run in listener mode with default port DEFAULT_PORT if not specified - port = args.port if args.port is not None else DEFAULT_PORT - trio.run(run_listener, port) + # Run in listener mode with random available port if not specified + trio.run(run_listener, args.port) except KeyboardInterrupt: print("\nInterrupted by user") logger.info("Interrupted by user") diff --git a/examples/ping/ping.py b/examples/ping/ping.py index cb1a4b4e..647a607b 100644 --- a/examples/ping/ping.py +++ b/examples/ping/ping.py @@ -55,7 +55,6 @@ async def send_ping(stream: INetStream) -> None: async def run(port: int, destination: str) -> None: - localhost_ip = "127.0.0.1" listen_addr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}") host = new_host(listen_addrs=[listen_addr]) @@ -65,8 +64,8 @@ async def run(port: int, destination: str) -> None: print( "Run this from the same folder in another console:\n\n" - f"ping-demo -p {int(port) + 1} " - f"-d /ip4/{localhost_ip}/tcp/{port}/p2p/{host.get_id().pretty()}\n" + f"ping-demo " + f"-d {host.get_addrs()[0]}\n" ) print("Waiting for incoming connection...") @@ -96,10 +95,8 @@ def main() -> None: ) parser = argparse.ArgumentParser(description=description) + parser.add_argument("-p", "--port", default=0, type=int, help="source port number") - parser.add_argument( - "-p", "--port", default=8000, type=int, help="source port number" - ) parser.add_argument( "-d", "--destination", @@ -108,9 +105,6 @@ def main() -> None: ) args = parser.parse_args() - if not args.port: - raise RuntimeError("failed to determine local port") - try: trio.run(run, *(args.port, args.destination)) except KeyboardInterrupt: diff --git a/newsfragments/661.docs.rst b/newsfragments/661.docs.rst new file mode 100644 index 00000000..917efa5d --- /dev/null +++ b/newsfragments/661.docs.rst @@ -0,0 +1 @@ +Updated examples to automatically use random port, when `-p` flag is not given