Files
weave-scope/common/network/interface.go
2016-03-23 15:41:37 +00:00

34 lines
619 B
Go

package network
import (
"fmt"
"net"
)
// GetFirstAddressOf returns the first IPv4 address of the supplied interface name.
func GetFirstAddressOf(name string) (string, error) {
inf, err := net.InterfaceByName(name)
if err != nil {
return "", err
}
addrs, err := inf.Addrs()
if err != nil {
return "", err
}
if len(addrs) <= 0 {
return "", fmt.Errorf("No address found for %s", name)
}
for _, addr := range addrs {
switch v := addr.(type) {
case *net.IPNet:
if ip := v.IP.To4(); ip != nil {
return v.IP.String(), nil
}
}
}
return "", fmt.Errorf("No address found for %s", name)
}