2017-05-15 20:10:36 +00:00
|
|
|
package ipaddr
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net"
|
2017-09-25 18:40:42 +00:00
|
|
|
"reflect"
|
2019-06-04 14:02:38 +00:00
|
|
|
"strconv"
|
2017-05-15 20:10:36 +00:00
|
|
|
)
|
|
|
|
|
2019-06-04 14:02:38 +00:00
|
|
|
// FormatAddressPort Helper for net.JoinHostPort that takes int for port
|
|
|
|
func FormatAddressPort(address string, port int) string {
|
|
|
|
return net.JoinHostPort(address, strconv.Itoa(port))
|
|
|
|
}
|
|
|
|
|
2017-05-15 20:10:36 +00:00
|
|
|
// IsAny checks if the given ip address is an IPv4 or IPv6 ANY address. ip
|
|
|
|
// can be either a *net.IP or a string. It panics on another type.
|
|
|
|
func IsAny(ip interface{}) bool {
|
|
|
|
return IsAnyV4(ip) || IsAnyV6(ip)
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsAnyV4 checks if the given ip address is an IPv4 ANY address. ip
|
|
|
|
// can be either a *net.IP or a string. It panics on another type.
|
|
|
|
func IsAnyV4(ip interface{}) bool {
|
|
|
|
return iptos(ip) == "0.0.0.0"
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsAnyV6 checks if the given ip address is an IPv6 ANY address. ip
|
|
|
|
// can be either a *net.IP or a string. It panics on another type.
|
|
|
|
func IsAnyV6(ip interface{}) bool {
|
|
|
|
ips := iptos(ip)
|
|
|
|
return ips == "::" || ips == "[::]"
|
|
|
|
}
|
|
|
|
|
|
|
|
func iptos(ip interface{}) string {
|
2017-09-25 18:40:42 +00:00
|
|
|
if ip == nil || reflect.TypeOf(ip).Kind() == reflect.Ptr && reflect.ValueOf(ip).IsNil() {
|
2017-05-15 20:10:36 +00:00
|
|
|
return ""
|
|
|
|
}
|
|
|
|
switch x := ip.(type) {
|
|
|
|
case string:
|
|
|
|
return x
|
2017-09-25 18:40:42 +00:00
|
|
|
case *string:
|
|
|
|
if x == nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return *x
|
2017-05-15 20:10:36 +00:00
|
|
|
case net.IP:
|
|
|
|
return x.String()
|
|
|
|
case *net.IP:
|
|
|
|
return x.String()
|
2017-09-25 18:40:42 +00:00
|
|
|
case *net.IPAddr:
|
|
|
|
return x.IP.String()
|
|
|
|
case *net.TCPAddr:
|
|
|
|
return x.IP.String()
|
|
|
|
case *net.UDPAddr:
|
|
|
|
return x.IP.String()
|
2017-05-15 20:10:36 +00:00
|
|
|
default:
|
|
|
|
panic(fmt.Sprintf("invalid type: %T", ip))
|
|
|
|
}
|
|
|
|
}
|