-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmain.go
88 lines (72 loc) · 1.46 KB
/
main.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
// asn-writer is an example of how to create an ASN MaxMind DB file from the
// GeoLite2 ASN CSVs. You must have the CSVs in the current working directory.
package main
import (
"encoding/csv"
"io"
"log"
"net"
"os"
"strconv"
"github.com/maxmind/mmdbwriter"
"github.com/maxmind/mmdbwriter/mmdbtype"
)
func main() {
writer, err := mmdbwriter.New(
mmdbwriter.Options{
DatabaseType: "My-ASN-DB",
RecordSize: 24,
},
)
if err != nil {
log.Fatal(err)
}
for _, file := range []string{"GeoLite2-ASN-Blocks-IPv4.csv", "GeoLite2-ASN-Blocks-IPv6.csv"} {
fh, err := os.Open(file)
if err != nil {
log.Fatal(err)
}
r := csv.NewReader(fh)
// first line
r.Read()
for {
row, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
if len(row) != 3 {
log.Fatalf("unexpected CSV rows: %v", row)
}
_, network, err := net.ParseCIDR(row[0])
if err != nil {
log.Fatal(err)
}
asn, err := strconv.Atoi(row[1])
if err != nil {
log.Fatal(err)
}
record := mmdbtype.Map{}
if asn != 0 {
record["autonomous_system_number"] = mmdbtype.Uint32(asn)
}
if row[2] != "" {
record["autonomous_system_organization"] = mmdbtype.String(row[2])
}
err = writer.Insert(network, record)
if err != nil {
log.Fatal(err)
}
}
}
fh, err := os.Create("out.mmdb")
if err != nil {
log.Fatal(err)
}
_, err = writer.WriteTo(fh)
if err != nil {
log.Fatal(err)
}
}