github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/ip.go (about)

     1  package utils
     2  
     3  import (
     4  	"net"
     5  	"strings"
     6  )
     7  
     8  // IsLocalIP 判断是否为本地IP
     9  func IsLocalIP(ipString string) bool {
    10  	var ip = net.ParseIP(ipString)
    11  	if ip == nil {
    12  		return false
    13  	}
    14  
    15  	// IPv6
    16  	if strings.Contains(ipString, ":") {
    17  		return ip.String() == "::1"
    18  	}
    19  
    20  	// IPv4
    21  	ip = ip.To4()
    22  	if ip == nil {
    23  		return false
    24  	}
    25  	if ip[0] == 127 ||
    26  		ip[0] == 10 ||
    27  		(ip[0] == 172 && ip[1]&0xf0 == 16) ||
    28  		(ip[0] == 192 && ip[1] == 168) {
    29  		return true
    30  	}
    31  
    32  	return false
    33  }
    34  
    35  // IsIPv4 是否为IPv4
    36  func IsIPv4(ip string) bool {
    37  	var data = net.ParseIP(ip)
    38  	if data == nil {
    39  		return false
    40  	}
    41  	if strings.Contains(ip, ":") {
    42  		return false
    43  	}
    44  	return data.To4() != nil
    45  }
    46  
    47  // IsIPv6 是否为IPv6
    48  func IsIPv6(ip string) bool {
    49  	var data = net.ParseIP(ip)
    50  	if data == nil {
    51  		return false
    52  	}
    53  	return !IsIPv4(ip)
    54  }
    55  
    56  // IsWildIP 宽泛地判断一个数据是否为IP
    57  func IsWildIP(v string) bool {
    58  	var l = len(v)
    59  	if l == 0 {
    60  		return false
    61  	}
    62  
    63  	// for [IPv6]
    64  	if v[0] == '[' && v[l-1] == ']' {
    65  		return IsWildIP(v[1 : l-1])
    66  	}
    67  
    68  	return net.ParseIP(v) != nil
    69  }