mdns.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package discovery
  2. import (
  3. "context"
  4. "github.com/ipfs/go-log"
  5. "github.com/libp2p/go-libp2p"
  6. "github.com/libp2p/go-libp2p-core/host"
  7. "github.com/libp2p/go-libp2p-core/peer"
  8. mdns "github.com/libp2p/go-libp2p/p2p/discovery/mdns"
  9. )
  10. type MDNS struct {
  11. DiscoveryServiceTag string
  12. }
  13. // discoveryNotifee gets notified when we find a new peer via mDNS discovery
  14. type discoveryNotifee struct {
  15. h host.Host
  16. c log.StandardLogger
  17. }
  18. // HandlePeerFound connects to peers discovered via mDNS. Once they're connected,
  19. // the PubSub system will automatically start interacting with them if they also
  20. // support PubSub.
  21. func (n *discoveryNotifee) HandlePeerFound(pi peer.AddrInfo) {
  22. //n.c.Infof("mDNS: discovered new peer %s\n", pi.ID.Pretty())
  23. err := n.h.Connect(context.Background(), pi)
  24. if err != nil {
  25. n.c.Debugf("mDNS: error connecting to peer %s: %s\n", pi.ID.Pretty(), err)
  26. }
  27. }
  28. func (d *MDNS) Option(ctx context.Context) func(c *libp2p.Config) error {
  29. return func(*libp2p.Config) error { return nil }
  30. }
  31. func (d *MDNS) Run(l log.StandardLogger, ctx context.Context, host host.Host) error {
  32. // setup mDNS discovery to find local peers
  33. disc := mdns.NewMdnsService(host, d.DiscoveryServiceTag, &discoveryNotifee{h: host, c: l})
  34. return disc.Start()
  35. }