Listen on first link local unicast address

This commit is contained in:
Julian Kornberger 2017-02-01 18:37:39 +01:00
parent 2d43dda380
commit a67443b342
1 changed files with 27 additions and 3 deletions

View File

@ -8,6 +8,8 @@ import (
"net" "net"
"time" "time"
"fmt"
"github.com/FreifunkBremen/respond-collector/data" "github.com/FreifunkBremen/respond-collector/data"
"github.com/FreifunkBremen/respond-collector/database" "github.com/FreifunkBremen/respond-collector/database"
"github.com/FreifunkBremen/respond-collector/jsontime" "github.com/FreifunkBremen/respond-collector/jsontime"
@ -27,14 +29,16 @@ type Collector struct {
// NewCollector creates a Collector struct // NewCollector creates a Collector struct
func NewCollector(db *database.DB, nodes *models.Nodes, iface string) *Collector { func NewCollector(db *database.DB, nodes *models.Nodes, iface string) *Collector {
// Parse address linkLocalAddr, err := getLinkLocalAddr(iface)
addr, err := net.ResolveUDPAddr("udp", "[::]:0")
if err != nil { if err != nil {
log.Panic(err) log.Panic(err)
} }
// Open socket // Open socket
conn, err := net.ListenUDP("udp", addr) conn, err := net.ListenUDP("udp", &net.UDPAddr{
IP: linkLocalAddr,
Zone: iface,
})
if err != nil { if err != nil {
log.Panic(err) log.Panic(err)
} }
@ -59,6 +63,26 @@ func NewCollector(db *database.DB, nodes *models.Nodes, iface string) *Collector
return collector return collector
} }
// Returns the first link local unicast address for the given interface name
func getLinkLocalAddr(ifname string) (net.IP, error) {
iface, err := net.InterfaceByName(ifname)
if err != nil {
return nil, err
}
addresses, err := iface.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addresses {
if ipnet := addr.(*net.IPNet); ipnet.IP.IsLinkLocalUnicast() {
return ipnet.IP, nil
}
}
return nil, fmt.Errorf("unable to find link local unicast address for %s", ifname)
}
// Start Collector // Start Collector
func (coll *Collector) Start(interval time.Duration) { func (coll *Collector) Start(interval time.Duration) {
if coll.interval != 0 { if coll.interval != 0 {