-
Notifications
You must be signed in to change notification settings - Fork 0
/
discovery_mdns.go
94 lines (87 loc) · 1.86 KB
/
discovery_mdns.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package discovery
import (
"context"
"github.com/grandcat/zeroconf"
"github.com/iain17/logger"
"net"
"fmt"
)
type DiscoveryMDNS struct {
server *zeroconf.Server
resolver *zeroconf.Resolver
localNode *LocalNode
context context.Context
logger *logger.Logger
}
func (d *DiscoveryMDNS) String() string {
return "DiscoveryMDNS"
}
func (d *DiscoveryMDNS) init(ctx context.Context) (err error) {
defer func() {
if d.localNode.wg != nil {
d.localNode.wg.Done()
}
}()
d.logger = logger.New(d.String())
d.context = ctx
if err != nil {
return err
}
d.resolver, err = zeroconf.NewResolver(nil)
if err != nil {
return fmt.Errorf("failed to initialize resolver: %s", err.Error())
}
d.server, err = zeroconf.Register(d.localNode.id, SERVICE, "local.", d.localNode.port, []string{d.localNode.id}, nil)
if err != nil {
return err
}
return err
}
func (d *DiscoveryMDNS) Serve(ctx context.Context) {
defer d.Stop()
d.localNode.waitTilCoreReady()
if err := d.init(ctx); err != nil {
d.localNode.lastError = err
panic(err)
}
d.localNode.WaitTilReady()
entriesCh := make(chan *zeroconf.ServiceEntry)
err := d.resolver.Browse(d.context, SERVICE, "", entriesCh)
if err != nil {
panic(err)
}
for {
select {
case <-d.context.Done():
return
case entry, ok := <-entriesCh:
if !ok {
continue
}
if entry == nil {
continue
}
if len(entry.Text) != 1 || entry.Text[0] == d.localNode.id {
continue
}
var ip net.IP
if len(entry.AddrIPv4) > 0 {
ip = entry.AddrIPv4[0]
}
if ip == nil && len(entry.AddrIPv6) > 0 {
ip = entry.AddrIPv6[0]
}
addr := &net.TCPAddr{
IP: ip,
Port: entry.Port,
}
d.logger.Debugf("Discovered local peer %s %v", entry.HostName, addr)
d.localNode.netTableService.Discovered(addr)
}
}
}
func (d *DiscoveryMDNS) Stop() {
if d.server != nil {
d.server.Shutdown()
}
}