Created
August 21, 2018 23:26
-
-
Save yteraoka/b396682ddd3263de91fa26bcd76a1af4 to your computer and use it in GitHub Desktop.
mDNS client test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"flag" | |
"log" | |
"time" | |
"strings" | |
"github.com/grandcat/zeroconf" | |
) | |
var ( | |
service = flag.String("service", "_workstation._tcp", "Set the service category to look for devices.") | |
domain = flag.String("domain", "local", "Set the search domain. For local networks, default is fine.") | |
waitTime = flag.Int("wait", 10, "Duration in [s] to run discovery.") | |
) | |
func main() { | |
flag.Parse() | |
// Discover all services on the network (e.g. _workstation._tcp) | |
resolver, err := zeroconf.NewResolver(nil) | |
if err != nil { | |
log.Fatalln("Failed to initialize resolver:", err.Error()) | |
} | |
entries := make(chan *zeroconf.ServiceEntry) | |
go func(results <-chan *zeroconf.ServiceEntry) { | |
for entry := range results { | |
log.Println(entry) | |
log.Println("ServiceRecord.Instance:", entry.ServiceRecord.Instance) | |
log.Println("ServiceRecord.Service:", entry.ServiceRecord.Service) | |
log.Println("ServiceRecord.Domain:", entry.ServiceRecord.Domain) | |
log.Println("HostName:", entry.HostName) | |
log.Println("Port:", entry.Port) | |
log.Println("Text:", strings.Join(entry.Text, ",")) | |
log.Println("TTL:", entry.TTL) | |
log.Println("AddrIPv4:", entry.AddrIPv4) | |
log.Println("AddrIPv6:", entry.AddrIPv6) | |
for _, s := range entry.Text { | |
log.Println(s) | |
} | |
} | |
log.Println("No more entries.") | |
}(entries) | |
ctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(*waitTime)) | |
defer cancel() | |
err = resolver.Browse(ctx, *service, *domain, entries) | |
if err != nil { | |
log.Fatalln("Failed to browse:", err.Error()) | |
} | |
<-ctx.Done() | |
// Wait some additional time to see debug messages on go routine shutdown. | |
time.Sleep(1 * time.Second) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment