github.hscsec.cn/hashicorp/consul@v1.4.5/ipaddr/ipaddr.go (about)

     1  package ipaddr
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"reflect"
     7  )
     8  
     9  // IsAny checks if the given ip address is an IPv4 or IPv6 ANY address. ip
    10  // can be either a *net.IP or a string. It panics on another type.
    11  func IsAny(ip interface{}) bool {
    12  	return IsAnyV4(ip) || IsAnyV6(ip)
    13  }
    14  
    15  // IsAnyV4 checks if the given ip address is an IPv4 ANY address. ip
    16  // can be either a *net.IP or a string. It panics on another type.
    17  func IsAnyV4(ip interface{}) bool {
    18  	return iptos(ip) == "0.0.0.0"
    19  }
    20  
    21  // IsAnyV6 checks if the given ip address is an IPv6 ANY address. ip
    22  // can be either a *net.IP or a string. It panics on another type.
    23  func IsAnyV6(ip interface{}) bool {
    24  	ips := iptos(ip)
    25  	return ips == "::" || ips == "[::]"
    26  }
    27  
    28  func iptos(ip interface{}) string {
    29  	if ip == nil || reflect.TypeOf(ip).Kind() == reflect.Ptr && reflect.ValueOf(ip).IsNil() {
    30  		return ""
    31  	}
    32  	switch x := ip.(type) {
    33  	case string:
    34  		return x
    35  	case *string:
    36  		if x == nil {
    37  			return ""
    38  		}
    39  		return *x
    40  	case net.IP:
    41  		return x.String()
    42  	case *net.IP:
    43  		return x.String()
    44  	case *net.IPAddr:
    45  		return x.IP.String()
    46  	case *net.TCPAddr:
    47  		return x.IP.String()
    48  	case *net.UDPAddr:
    49  		return x.IP.String()
    50  	default:
    51  		panic(fmt.Sprintf("invalid type: %T", ip))
    52  	}
    53  }