-
Notifications
You must be signed in to change notification settings - Fork 80
/
dns.go
109 lines (94 loc) · 2.28 KB
/
dns.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package dns
import (
"fmt"
"io/ioutil"
"log"
"net"
"sort"
"strings"
"time"
"github.com/hashicorp/mdns"
)
func init() {
// Disable mdns annoying and verbose logging
log.SetOutput(ioutil.Discard)
}
const (
maxEntries = 20
)
// CastDNSEntry is the interface that satisfies a Cast type.
type CastDNSEntry interface {
GetName() string
GetUUID() string
GetAddr() string
GetPort() int
}
// CastEntry is the concrete cast entry type.
type CastEntry struct {
AddrV4 net.IP
AddrV6 net.IP
Port int
Name string
Host string
UUID string
Device string
Status string
DeviceName string
InfoFields map[string]string
}
// GetUUID returns a unqiue id of a cast entry.
func (e CastEntry) GetUUID() string {
return e.UUID
}
// GetName returns the identified name of a cast entry.
func (e CastEntry) GetName() string {
return e.DeviceName
}
// GetAddr returns the IPV4 of a cast entry.
func (e CastEntry) GetAddr() string {
return fmt.Sprintf("%s", e.AddrV4)
}
// GetPort returns the port of a cast entry.
func (e CastEntry) GetPort() int {
return e.Port
}
// FindCastDNSEntries returns all found cast entries.
func FindCastDNSEntries() []CastEntry {
entriesCh := make(chan *mdns.ServiceEntry, maxEntries)
go func() {
// This will find any and all google products, including chromecast, home mini, etc.
mdns.Query(&mdns.QueryParam{
Service: "_googlecast._tcp",
Domain: "local",
Timeout: time.Second * 3,
Entries: entriesCh,
})
close(entriesCh)
}()
entries := make([]CastEntry, 0)
for entry := range entriesCh {
infoFields := make(map[string]string, len(entry.InfoFields))
for _, infoField := range entry.InfoFields {
splitField := strings.Split(infoField, "=")
if len(splitField) != 2 {
continue
}
infoFields[splitField[0]] = splitField[1]
}
entries = append(entries, CastEntry{
AddrV4: entry.AddrV4,
AddrV6: entry.AddrV6,
Port: entry.Port,
Name: entry.Name,
Host: entry.Host,
InfoFields: infoFields,
UUID: infoFields["id"],
Device: infoFields["md"],
DeviceName: infoFields["fn"],
Status: infoFields["rs"],
})
}
// Always return entries in deterministic order.
sort.Slice(entries, func(i, j int) bool { return entries[i].DeviceName < entries[j].DeviceName })
return entries
}