-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathiplist.go
58 lines (51 loc) · 1017 Bytes
/
iplist.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
package iplist
import (
"io"
"bufio"
"fmt"
"strings"
"net"
)
type IPList struct {
networks []*net.IPNet
}
func (iplist *IPList) Contains(ip string) (bool) {
parsedIP := net.ParseIP(ip)
for _, network := range iplist.networks {
if network.Contains(parsedIP) {
return true
}
}
return false
}
func NewFromReader(reader io.Reader) (ipList *IPList, err error) {
scanner := bufio.NewScanner(reader)
lineNum := 1
ipList = &IPList{}
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "#") {
continue
}
network, lineErr := parseLine(line)
if lineErr != nil {
err = fmt.Errorf("error parsing line %d: %s", lineNum, lineErr)
return
}
lineNum++
ipList.networks = append(ipList.networks, network)
}
err = scanner.Err()
if err != nil {
return
}
return
}
func parseLine(line string) (network *net.IPNet, err error) {
line = strings.TrimSpace(line)
if !strings.Contains(line, "/") {
line += "/32"
}
_, network, err = net.ParseCIDR(line)
return
}