open-nomad/command/agent/util.go

47 lines
1 KiB
Go
Raw Normal View History

2015-08-16 21:34:38 +00:00
package agent
import (
2016-03-18 20:50:29 +00:00
"fmt"
"net"
2015-08-16 21:34:38 +00:00
)
2016-03-18 20:50:29 +00:00
// IpOfDevice returns a routable ip addr of a device
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)
}
// 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.
var ipv6Addrs []net.IP
2016-03-18 20:50:29 +00:00
for _, addr := range addrs {
var ip net.IP
2016-03-18 20:50:29 +00:00
switch v := (addr).(type) {
case *net.IPNet:
ip = v.IP
if ip.To4() != nil {
return ip, nil
}
if ip.To16() != nil {
ipv6Addrs = append(ipv6Addrs, ip)
continue
}
case *net.IPAddr:
continue
2016-03-18 20:50:29 +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)
}