2015-08-16 21:34:38 +00:00
|
|
|
package agent
|
|
|
|
|
|
|
|
import (
|
2016-03-18 20:50:29 +00:00
|
|
|
"fmt"
|
2015-08-16 21:34:38 +00:00
|
|
|
"math/rand"
|
2016-03-18 20:50:29 +00:00
|
|
|
"net"
|
2015-08-16 21:34:38 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Returns a random stagger interval between 0 and the duration
|
|
|
|
func randomStagger(intv time.Duration) time.Duration {
|
|
|
|
return time.Duration(uint64(rand.Int63()) % uint64(intv))
|
|
|
|
}
|
2016-03-18 20:50:29 +00:00
|
|
|
|
|
|
|
// IpOfDevice returns a routable ip addr of a device
|
2016-03-19 04:44:22 +00:00
|
|
|
func ipOfDevice(name string) (net.IP, error) {
|
2016-03-18 20:50:29 +00:00
|
|
|
intf, err := net.InterfaceByName(name)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
addrs, err := intf.Addrs()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if len(addrs) == 0 {
|
|
|
|
return nil, fmt.Errorf("no ips were detected on the interface: %v", name)
|
|
|
|
}
|
2016-03-21 06:17:56 +00:00
|
|
|
|
|
|
|
// Iterating through the IPs configured for that device and returning the
|
|
|
|
// the first ipv4 address configured. If no ipv4 addresses are configured,
|
|
|
|
// we return the first ipv6 addr if any ipv6 addr is configured.
|
2016-03-19 04:44:22 +00:00
|
|
|
var ipv6Addrs []net.IP
|
2016-03-18 20:50:29 +00:00
|
|
|
for _, addr := range addrs {
|
2016-03-19 04:44:22 +00:00
|
|
|
var ip net.IP
|
2016-03-18 20:50:29 +00:00
|
|
|
switch v := (addr).(type) {
|
|
|
|
case *net.IPNet:
|
2016-03-19 04:44:22 +00:00
|
|
|
ip = v.IP
|
|
|
|
if ip.To4() != nil {
|
2016-03-21 06:17:56 +00:00
|
|
|
return ip, nil
|
2016-03-19 04:44:22 +00:00
|
|
|
}
|
|
|
|
if ip.To16() != nil {
|
|
|
|
ipv6Addrs = append(ipv6Addrs, ip)
|
|
|
|
continue
|
|
|
|
}
|
2016-03-19 05:26:13 +00:00
|
|
|
case *net.IPAddr:
|
|
|
|
continue
|
2016-03-18 20:50:29 +00:00
|
|
|
}
|
|
|
|
}
|
2016-03-19 04:44:22 +00:00
|
|
|
if len(ipv6Addrs) > 0 {
|
|
|
|
return ipv6Addrs[0], nil
|
|
|
|
}
|
2016-03-18 20:50:29 +00:00
|
|
|
return nil, fmt.Errorf("no ips were detected on the interface: %v", name)
|
|
|
|
}
|