mdns.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. Copyright © 2021-2022 Ettore Di Giacinto <[email protected]>
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package discovery
  14. import (
  15. "context"
  16. "github.com/ipfs/go-log"
  17. "github.com/libp2p/go-libp2p"
  18. "github.com/libp2p/go-libp2p/core/host"
  19. "github.com/libp2p/go-libp2p/core/peer"
  20. "github.com/libp2p/go-libp2p/p2p/discovery/mdns"
  21. )
  22. type MDNS struct {
  23. DiscoveryServiceTag string
  24. }
  25. // discoveryNotifee gets notified when we find a new peer via mDNS discovery
  26. type discoveryNotifee struct {
  27. h host.Host
  28. c log.StandardLogger
  29. }
  30. // HandlePeerFound connects to peers discovered via mDNS. Once they're connected,
  31. // the PubSub system will automatically start interacting with them if they also
  32. // support PubSub.
  33. func (n *discoveryNotifee) HandlePeerFound(pi peer.AddrInfo) {
  34. //n.c.Infof("mDNS: discovered new peer %s\n", pi.ID.String())
  35. err := n.h.Connect(context.Background(), pi)
  36. if err != nil {
  37. n.c.Debugf("mDNS: error connecting to peer %s: %s\n", pi.ID.String(), err)
  38. }
  39. }
  40. func (d *MDNS) Option(ctx context.Context) func(c *libp2p.Config) error {
  41. return func(*libp2p.Config) error { return nil }
  42. }
  43. func (d *MDNS) Run(l log.StandardLogger, ctx context.Context, host host.Host) error {
  44. // setup mDNS discovery to find local peers
  45. disc := mdns.NewMdnsService(host, d.DiscoveryServiceTag, &discoveryNotifee{h: host, c: l})
  46. return disc.Start()
  47. }