github.com/zooyer/miskit@v1.0.71/utils/ip.go (about)

     1  /**
     2   * @Author: zzy
     3   * @Email: zhangzhongyuan@didiglobal.com
     4   * @Description:
     5   * @File: ip.go
     6   * @Package: utils
     7   * @Version: 1.0.0
     8   * @Date: 2022/6/13 15:57
     9   */
    10  
    11  package utils
    12  
    13  import "net"
    14  
    15  // IsPrivateIP 判断是否是内网ip
    16  func IsPrivateIP(ip string) bool {
    17  	return !IsPublicIP(ip)
    18  }
    19  
    20  // IsPublicIP 判断是否是公网IP
    21  func IsPublicIP(ipaddr string) bool {
    22  	var ip = net.ParseIP(ipaddr)
    23  	if ip.IsLoopback() || ip.IsLinkLocalMulticast() || ip.IsLinkLocalUnicast() {
    24  		return false
    25  	}
    26  	if ip4 := ip.To4(); ip4 != nil {
    27  		switch {
    28  		case ip4[0] == 10:
    29  			return false
    30  		case ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31:
    31  			return false
    32  		case ip4[0] == 192 && ip4[1] == 168:
    33  			return false
    34  		}
    35  		return true
    36  	}
    37  	return false
    38  }