-
Notifications
You must be signed in to change notification settings - Fork 1
/
ip2country.go
196 lines (154 loc) · 3.53 KB
/
ip2country.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// DB-IP.com
// You are free to use this database in your application, provided you give attribution to DB-IP.com for the data.
// In the case of a web application, you must include a link back to DB-IP.com on the pages displaying or using results from the database.
package ip2country
import (
"bufio"
"errors"
"os"
"strconv"
"strings"
"sync"
)
//ErrInvalidLine when csv line is invalid
var ErrInvalidLine = errors.New("Invalid line structure")
//ErrInvalidIPv4 when invalid ip address provided
var ErrInvalidIPv4 = errors.New("Invalid IPv4 address")
type ipRange struct {
start uint
end uint
country string
}
var arr []ipRange
var once sync.Once
var loadError error
//Load db-ip.com csv file
//It must be called only once
func Load(filepath string) error {
once.Do(func() {
loadError = load(filepath)
})
return loadError
}
//GetCountry returns the country which ip blongs to
func GetCountry(ip string) string {
ipNumb, err := ipToInt(ip)
if err != nil {
return ""
}
index := binarySearch(arr, ipNumb, 0, len(arr)-1)
if index == -1 {
return ""
}
return arr[index].country
}
//GetCountryMulti is a batch version of GetCountry function
//It allows you to pass many ip addresses as input, and will return countries as output
//the first index of slice is the answer for the first input , the second index for the second input and so on
func GetCountryMulti(ips ...string) []string {
size := len(ips)
answers := make([]string, size)
var wg sync.WaitGroup
wg.Add(size)
for i := 0; i < size; i++ {
go func(index int) {
answers[index] = GetCountry(ips[index])
wg.Done()
}(i)
}
wg.Wait()
return answers
}
func load(filepath string) error {
arr = make([]ipRange, 0)
return loadFile(filepath)
}
func loadFile(filepath string) error {
file, err := os.Open(filepath)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
err = addRaw(scanner.Text())
if err != nil {
return err
}
}
err = scanner.Err()
return err
}
//accept input string as follows
//"{ip}","{ip}","{country}"
func addRaw(line string) error {
//replace all double quotations
line = strings.Replace(line, "\"", "", -1)
startIP, endIP, country, err := extract(line)
if err != nil {
return err
}
startIPnum, err := ipToInt(startIP)
if err != nil {
return err
}
endIPnum, err := ipToInt(endIP)
if err != nil {
return err
}
arr = append(arr, ipRange{startIPnum, endIPnum, country})
ensureSorted(arr)
return nil
}
func ensureSorted(arr []ipRange) {
i := len(arr) - 1
temp := arr[i]
for {
if i == 0 || arr[i].start >= arr[i-1].start {
break
}
arr[i] = arr[i-1]
i--
}
arr[i] = temp
}
func ipToInt(ip string) (uint, error) {
parts := strings.Split(ip, ".")
if len(parts) != 4 {
return 0, ErrInvalidIPv4
}
var result uint
var index uint = 3
for i := 3; i >= 0; i-- {
ipNumb, err := strconv.Atoi(parts[index])
if err != nil {
return 0, err
}
result |= uint(ipNumb) << ((uint(3) - index) * uint(8))
index--
}
return result, nil
}
func extract(line string) (string, string, string, error) {
parts := strings.Split(line, ",")
if len(parts) != 3 {
return "", "", "", ErrInvalidLine
}
return parts[0], parts[1], parts[2], nil
}
func binarySearch(arr []ipRange, key uint, start, end int) int {
for {
if start > end {
return -1 //not found
}
mid := (start + end) / 2
if key >= arr[mid].start && key <= arr[mid].end {
return mid
}
if key < arr[mid].start {
end = mid - 1
} else if key > arr[mid].end {
start = mid + 1
}
}
}