-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.go
More file actions
103 lines (84 loc) · 2.28 KB
/
Copy pathparse.go
File metadata and controls
103 lines (84 loc) · 2.28 KB
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
package main
import (
"log"
"bufio"
"fmt"
"strings"
"time"
"regexp"
"flag"
"os"
)
func addrFormat(parts []string) string {
addr := ""
if strings.Contains(parts[1], ".") {
// IPv4
fromTo := strings.Split(parts[1], "-")
addr = fromTo[0] + ";" + fromTo[1]
} else {
// IPv6
ipv6 := strings.Join(parts[1:], ":")
addr = ipv6 + ";" + ipv6
}
addr += ";"
return addr
}
// Parse(fh *os.File, ip6 bool)
// Parses the input ripe database for IPv4 ranges and corresponding countries.
// Also includes IPv6 ranges if ip6 param is set to true.
// Status messages are written to stderr, and data to stdout.
func Parse(fh *os.File, ip6 bool) {
started := time.Now()
fmt.Fprintf(os.Stderr, "Starting output at: %s\n", started.String())
scanner := bufio.NewScanner(fh)
isBlock := false
str := ""
spaces, _ := regexp.Compile(" +")
hasInetnum, _ := regexp.Compile("^inetnum:")
if ip6 {
hasInetnum, _ = regexp.Compile("^inet6?num:")
}
isInet := false
for scanner.Scan() {
text := scanner.Text()
if hasInetnum.MatchString(text) {
isBlock = true
isInet = true
} else {
isInet = false
}
isCountry := strings.Contains(text, "country:")
if isBlock && (isInet || isCountry) {
simple := spaces.ReplaceAllString(text, "")
parts := strings.Split(simple, ":")
if isInet {
str += addrFormat(parts)
} else {
str += parts[1]
}
}
if text == "" {
isBlock = false
if str != "" {
fmt.Println(str)
str = ""
}
}
}
fmt.Fprintf(os.Stderr, "Ending output at: %s, took: %s\n", time.Now().String(), time.Now().Sub(started).String())
}
func main() {
fName := flag.String("in", "ripe.db", "Input file to parse, defauls to ripe.db")
ip6 := flag.Bool("ip6", false, "Include IPv6 ranges as well, defaults to false")
flag.Parse()
if len(*fName) <= 0 {
flag.Usage()
os.Exit(6)
}
f, err := os.Open(*fName)
if err != nil {
log.Fatalln(err)
}
defer f.Close()
Parse(f, *ip6)
}