github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/ipdb/ipdb.go (about) 1 // Unless explicitly stated otherwise all files in this repository are licensed 2 // under the MIT License. 3 // This product includes software developed at Guance Cloud (https://www.guance.com/). 4 // Copyright 2021-present Guance, Inc. 5 6 // Package ipdb define the interface for ip location or isp. 7 package ipdb 8 9 import ( 10 "fmt" 11 "strconv" 12 "strings" 13 ) 14 15 type IPdb interface { 16 Init(dataDir string, config map[string]string) 17 Geo(ip string) (*IPdbRecord, error) 18 SearchIsp(ip string) string 19 } 20 21 type IPdbRecord struct { 22 Country string 23 Region string 24 City string 25 Isp string 26 Latitude float32 27 Longitude float32 28 Timezone string 29 Areacode string 30 } 31 32 func (record *IPdbRecord) CheckData() *IPdbRecord { 33 switch record.Country { // #issue 354 34 case "TW": 35 record.Country = "CN" 36 record.Region = "Taiwan" 37 case "MO": 38 record.Country = "CN" 39 record.Region = "Macao" 40 case "HK": 41 record.Country = "CN" 42 record.Region = "Hong Kong" 43 } 44 return record 45 } 46 47 func ParseIPCIDR(ipCidr string) (string, error) { 48 var err error 49 var cidrLen int64 = 32 50 51 ipCidrs := strings.Split(ipCidr, "/") 52 if len(ipCidrs) == 2 { 53 cidrLen, err = strconv.ParseInt(ipCidrs[1], 10, 8) 54 if err != nil { 55 return "", err 56 } 57 } 58 59 ipBytes := strings.Split(ipCidrs[0], ".") 60 if len(ipBytes) != 4 { 61 return "", fmt.Errorf("invalid ip address") 62 } 63 ipBitStr := "" 64 for _, ipByteStr := range ipBytes { 65 ip, err := strconv.ParseInt(ipByteStr, 10, 16) 66 if err != nil { 67 return "", err 68 } 69 if ip >= int64(len(BitConvTemplate)) { 70 return "", fmt.Errorf("invalid ip number: %s", ipByteStr) 71 } 72 if cidrLen >= 8 { 73 ipBitStr += BitConvTemplate[ip] 74 } else { 75 ipBitStr += BitConvTemplate[ip][0:cidrLen] 76 } 77 cidrLen -= 8 78 if cidrLen <= 0 { 79 break 80 } 81 } 82 return ipBitStr, nil 83 }