util/addr: check ip addrs before return

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2020-03-07 21:05:00 +03:00
parent 9a7a65f05e
commit 077063c212

View File

@ -79,8 +79,8 @@ func Extract(addr string) (string, error) {
}
addrs = append(addrs, loAddrs...)
var ipAddr []byte
var publicIP []byte
var ipAddr string
var publicIP string
for _, rawAddr := range addrs {
var ip net.IP
@ -94,22 +94,30 @@ func Extract(addr string) (string, error) {
}
if !isPrivateIP(ip.String()) {
publicIP = ip
publicIP = ip.String()
continue
}
ipAddr = ip
ipAddr = ip.String()
break
}
// return private ip
if ipAddr != nil {
return net.IP(ipAddr).String(), nil
if len(ipAddr) > 0 {
a := net.ParseIP(ipAddr)
if a == nil {
return "", fmt.Errorf("ip addr %s is invalid", ipAddr)
}
return a.String(), nil
}
// return public or virtual ip
if publicIP != nil {
return net.IP(publicIP).String(), nil
if len(publicIP) > 0 {
a := net.ParseIP(publicIP)
if a == nil {
return "", fmt.Errorf("ip addr %s is invalid", publicIP)
}
return a.String(), nil
}
return "", fmt.Errorf("No IP address found, and explicit IP not provided")