github.com/turingchain2020/turingchain@v1.1.21/system/p2p/dht/protocol/peer/ip.go (about) 1 package peer 2 3 import ( 4 "net" 5 ) 6 7 /* 8 tcp/ip协议中,专门保留了三个IP地址区域作为私有地址,其地址范围如下: 9 10.0.0.0/8:10.0.0.0~10.255.255.255 10 172.16.0.0/12:172.16.0.0~172.31.255.255 11 192.168.0.0/16:192.168.0.0~192.168.255.255 12 */ 13 func isPublicIP(ip string) bool { 14 IP := net.ParseIP(ip) 15 if IP == nil || IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() { 16 return false 17 } 18 if ip4 := IP.To4(); ip4 != nil { 19 switch true { 20 case ip4[0] == 10: 21 return false 22 case ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31: 23 return false 24 case ip4[0] == 192 && ip4[1] == 168: 25 return false 26 default: 27 return true 28 } 29 } 30 return false 31 } 32 33 // LocalIPs return all non-loopback IPv4 addresses 34 func localIPv4s() ([]string, error) { 35 var ips []string 36 addrs, err := net.InterfaceAddrs() 37 if err != nil { 38 return ips, err 39 } 40 41 for _, a := range addrs { 42 if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil { 43 ips = append(ips, ipnet.IP.String()) 44 } 45 } 46 47 return ips, nil 48 }