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>
This commit is contained in:
Abhinav Agarwalla
2025-06-10 00:29:11 +05:30
committed by GitHub
parent c83fc1582d
commit 4e9fa87477
6 changed files with 24 additions and 60 deletions

View File

@ -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: