-
Notifications
You must be signed in to change notification settings - Fork 79
/
test.go
117 lines (95 loc) · 2.06 KB
/
test.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"fmt"
"github.com/oschwald/geoip2-golang"
"log"
"net"
"path/filepath"
"sync/atomic"
)
var (
db1 *geoip2.Reader
db2 *geoip2.Reader
)
func hosts(cidr string) ([]string, error) {
ip, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
return nil, err
}
var ips []string
for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) {
ips = append(ips, ip.String())
}
return ips, nil
}
func inc(ip net.IP) {
for j := len(ip) - 1; j >= 0; j-- {
ip[j]++
if ip[j] > 0 {
break
}
}
}
func loadMmdb(mmdbFile1 string, mmdbFile2 string) {
var err error
db1, err = geoip2.Open(filepath.Join(workDir, mmdbFile1))
if err != nil {
log.Fatal(err)
}
db2, err = geoip2.Open(filepath.Join(workDir, mmdbFile2))
if err != nil {
log.Fatal(err)
}
}
func testIp(dbNum int, ip string) string {
var db *geoip2.Reader
if dbNum == 1 {
db = db1
} else {
db = db2
}
ipNet := net.ParseIP(ip)
record, err := db.Country(ipNet)
if err != nil {
log.Fatal(err)
}
return record.Country.IsoCode
}
func testAllIPDiff(mmdbFile1 string, mmdbFile2 string) {
loadMmdb(mmdbFile1, mmdbFile2)
var res []string
var count uint64 = 0
var process int = 0
total := len(chinaIpList)
for _, ips := range chinaIpList {
process++
log.Printf("process: %v/%v, current: %v", process, total, ips)
hosts, _ := hosts(ips)
for _, ip := range hosts {
iso1 := testIp(1, ip)
iso2 := testIp(2, ip)
if iso1 != iso2 {
atomic.AddUint64(&count, 1)
log.Printf("ip: %v, before: %v, after: %v\n", ip, iso1, iso2)
res = append(res, fmt.Sprintf("ip: %v, before: %v, after: %v\n", ip, iso1, iso2))
}
}
}
log.Printf("Different country from ipip cn count: %v\n", count)
log.Print(res)
defer db1.Close()
defer db2.Close()
}
func testSingleIp(ipStr string, mmdbFile string) {
db, err := geoip2.Open(filepath.Join(workDir, mmdbFile))
if err != nil {
log.Fatal(err)
}
defer db.Close()
ip := net.ParseIP(ipStr)
record, err := db.Country(ip)
if err != nil {
log.Fatal(err)
}
log.Printf("ISO country code: %v\n", record.Country.IsoCode)
}