mdns.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright © 2021 Ettore Di Giacinto <[email protected]>
  2. //
  3. // This program is free software; you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation; either version 2 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program; if not, see <http://www.gnu.org/licenses/>.
  15. package discovery
  16. import (
  17. "context"
  18. "time"
  19. "github.com/ipfs/go-log"
  20. "github.com/libp2p/go-libp2p"
  21. "github.com/libp2p/go-libp2p-core/host"
  22. "github.com/libp2p/go-libp2p-core/peer"
  23. mdns "github.com/libp2p/go-libp2p/p2p/discovery/mdns_legacy"
  24. )
  25. type MDNS struct {
  26. DiscoveryServiceTag string
  27. }
  28. // discoveryNotifee gets notified when we find a new peer via mDNS discovery
  29. type discoveryNotifee struct {
  30. h host.Host
  31. c log.StandardLogger
  32. }
  33. // HandlePeerFound connects to peers discovered via mDNS. Once they're connected,
  34. // the PubSub system will automatically start interacting with them if they also
  35. // support PubSub.
  36. func (n *discoveryNotifee) HandlePeerFound(pi peer.AddrInfo) {
  37. //n.c.Infof("mDNS: discovered new peer %s\n", pi.ID.Pretty())
  38. err := n.h.Connect(context.Background(), pi)
  39. if err != nil {
  40. n.c.Debugf("mDNS: error connecting to peer %s: %s\n", pi.ID.Pretty(), err)
  41. }
  42. }
  43. func (d *MDNS) Option(ctx context.Context) func(c *libp2p.Config) error {
  44. return func(*libp2p.Config) error { return nil }
  45. }
  46. func (d *MDNS) Run(l log.StandardLogger, ctx context.Context, host host.Host) error {
  47. // setup mDNS discovery to find local peers
  48. // XXX: Valid for new mdns
  49. // disc := mdns.NewMdnsService(host, d.DiscoveryServiceTag, &discoveryNotifee{h: host, c: l})
  50. // return disc.Start()
  51. // We stick to legacy atm as mdns 0.15 is kinda of broken
  52. // see: https://github.com/libp2p/go-libp2p/pull/1192
  53. disc, err := mdns.NewMdnsService(ctx, host, time.Hour, d.DiscoveryServiceTag)
  54. if err != nil {
  55. return err
  56. }
  57. n := &discoveryNotifee{h: host, c: l}
  58. disc.RegisterNotifee(n)
  59. return nil
  60. }