Skip to content

Commit 67bcad1

Browse files
committed
Refactored mDNS example and added script for example
1 parent 3b53120 commit 67bcad1

File tree

6 files changed

+133
-50
lines changed

6 files changed

+133
-50
lines changed

docs/examples.mDNS.rst

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
mDNS Peer Discovery Example
2+
==========================
3+
4+
This example demonstrates how to use mDNS (Multicast DNS) for peer discovery in py-libp2p.
5+
6+
Prerequisites
7+
-------------
8+
9+
First, ensure you have py-libp2p installed and your environment is activated:
10+
11+
.. code-block:: console
12+
13+
$ python -m pip install libp2p
14+
15+
Running the Example
16+
-------------------
17+
18+
The mDNS demo script allows you to discover peers on your local network using mDNS. To start a peer, run:
19+
20+
.. code-block:: console
21+
22+
$ mdns-demo
23+
24+
You should see output similar to:
25+
26+
.. code-block:: console
27+
28+
Run this from another console to start another peer on a different port:
29+
30+
python mdns-demo -p <ANOTHER_PORT>
31+
32+
Waiting for mDNS peer discovery events...
33+
34+
2025-06-20 23:28:12,052 - libp2p.example.discovery.mdns - INFO - Starting peer Discovery
35+
36+
To discover peers, open another terminal and run the same command with a different port:
37+
38+
.. code-block:: console
39+
40+
$ python mdns-demo -p 9001
41+
42+
You should see output indicating that a new peer has been discovered:
43+
44+
.. code-block:: console
45+
46+
Run this from the same folder in another console to start another peer on a different port:
47+
48+
python mdns-demo -p <ANOTHER_PORT>
49+
50+
Waiting for mDNS peer discovery events...
51+
52+
2025-06-20 23:43:43,786 - libp2p.example.discovery.mdns - INFO - Starting peer Discovery
53+
2025-06-20 23:43:43,790 - libp2p.example.discovery.mdns - INFO - Discovered: 16Uiu2HAmGxy5NdQEjZWtrYUMrzdp3Syvg7MB2E5Lx8weA9DanYxj
54+
55+
When a new peer is discovered, its peer ID will be printed in the console output.
56+
57+
How it Works
58+
------------
59+
60+
- Each node advertises itself on the local network using mDNS.
61+
- When a new peer is discovered, the handler prints its peer ID.
62+
- This is useful for local peer discovery without requiring a DHT or bootstrap nodes.
63+
64+
You can modify the script to perform additional actions when peers are discovered, such as opening streams or exchanging messages.

docs/examples.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@ Examples
1313
examples.pubsub
1414
examples.circuit_relay
1515
examples.kademlia
16+
examples.mDNS

examples/discovery/__init__.py

Whitespace-only changes.

examples/discovery/mDNS/mDNS.py

Lines changed: 0 additions & 50 deletions
This file was deleted.

examples/mDNS/mDNS.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import argparse
2+
import logging
3+
import secrets
4+
5+
import multiaddr
6+
import trio
7+
8+
from libp2p import (
9+
new_host,
10+
)
11+
from libp2p.abc import PeerInfo
12+
from libp2p.crypto.secp256k1 import (
13+
create_new_key_pair,
14+
)
15+
from libp2p.discovery.events.peerDiscovery import peerDiscovery
16+
17+
logger = logging.getLogger("libp2p.example.discovery.mdns")
18+
logger.setLevel(logging.INFO)
19+
handler = logging.StreamHandler()
20+
handler.setFormatter(
21+
logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
22+
)
23+
logger.addHandler(handler)
24+
25+
26+
def onPeerDiscovery(peerinfo: PeerInfo):
27+
logger.info(f"Discovered: {peerinfo.peer_id}")
28+
29+
30+
async def run(port: int) -> None:
31+
secret = secrets.token_bytes(32)
32+
key_pair = create_new_key_pair(secret)
33+
listen_addr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}")
34+
35+
peerDiscovery.register_peer_discovered_handler(onPeerDiscovery)
36+
37+
print(
38+
"Run this from the same folder in another console to "
39+
"start another peer on a different port:\n\n"
40+
"python mdns-demo -p <ANOTHER_PORT>\n"
41+
)
42+
print("Waiting for mDNS peer discovery events...\n")
43+
44+
logger.info("Starting peer Discovery")
45+
host = new_host(key_pair=key_pair, enable_mDNS=True)
46+
async with host.run(listen_addrs=[listen_addr]):
47+
await trio.sleep_forever()
48+
49+
50+
def main() -> None:
51+
description = """
52+
This program demonstrates mDNS peer discovery using libp2p.
53+
To use it, run 'mdns-demo -p <PORT>', where <PORT> is the port number.
54+
Start multiple peers on different ports to see discovery in action.
55+
"""
56+
parser = argparse.ArgumentParser(description=description)
57+
parser.add_argument("-p", "--port", default=0, type=int, help="source port number")
58+
59+
args = parser.parse_args()
60+
try:
61+
trio.run(run, args.port)
62+
except KeyboardInterrupt:
63+
logger.info("Exiting...")
64+
65+
66+
if __name__ == "__main__":
67+
main()

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ identify-demo = "examples.identify.identify:main"
5555
identify-push-demo = "examples.identify_push.identify_push_demo:run_main"
5656
identify-push-listener-dialer-demo = "examples.identify_push.identify_push_listener_dialer:main"
5757
pubsub-demo = "examples.pubsub.pubsub:main"
58+
mdns-demo = "examples.mDNS.mDNS:main"
5859

5960
[project.optional-dependencies]
6061
dev = [

0 commit comments

Comments
 (0)