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