mdns query

This commit is contained in:
christian 2024-07-17 07:37:56 +02:00
parent 89ebd5ca41
commit 669a5c7d57
2 changed files with 22 additions and 17 deletions

View File

@ -3,34 +3,30 @@ package main
import (
"fmt"
"log"
"os"
"net"
"time"
"github.com/grandcat/zeroconf"
"golang.org/x/net/context"
)
func main() {
// Create or open a log file
logFile, err := os.OpenFile("program.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("Failed to open log file: %v", err)
}
defer logFile.Close()
type Device struct {
IP net.IP
Name string
}
// Set log output to the file
log.SetOutput(logFile)
// Log a startup message
log.Println("Starting mDNS query for 'hue-bridge'")
func discoverHueBridge() ([]Device, error) {
// Create a new resolver
resolver, err := zeroconf.NewResolver(nil)
if err != nil {
log.Fatalf("Failed to initialize resolver: %v", err)
}
// Instantiate a new devices slice
devices := make([]Device, 0)
// Set up a context with a timeout
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
// Channel to recive the results
@ -47,13 +43,21 @@ func main() {
// Process the results
go func() {
for entry := range entries {
fmt.Printf("Found Device: %s\n", entry.HostName)
fmt.Printf("IP Addresses: %v\n", entry.AddrIPv4)
devices = append(devices, Device{IP: entry.AddrIPv4[0], Name: entry.HostName})
}
fmt.Printf("Number of devices found: %d\n", len(entries))
}()
// Wait for the context to expire
<-ctx.Done()
fmt.Println("mDNS query finished")
fmt.Printf("Number of devices found: %d\n", len(devices))
for _, device := range devices {
fmt.Printf("Device: %s\n", device.Name)
fmt.Printf("IP Address: %s\n", device.IP)
}
return devices, nil
}
func main() {
discoverHueBridge()
}

View File

@ -1 +1,2 @@
2024/07/16 23:58:30 Starting mDNS query for 'hue-bridge'
2024/07/17 07:00:24 Starting mDNS query for 'hue-bridge'