-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip_compact.go
78 lines (72 loc) · 1.37 KB
/
ip_compact.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
package main
import (
"bufio"
"fmt"
"log"
"net/netip"
"os"
"strings"
"go4.org/netipx"
)
func readFile(name string) []netip.Prefix {
var prefixes []netip.Prefix
var f *os.File
if name == "-" {
f = os.Stdin
} else {
var err error
f, err = os.Open(name)
if err != nil {
log.Fatal(err)
}
defer f.Close()
}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if !strings.Contains(line, "/") {
if strings.Contains(line, ":") {
line = line + "/128"
} else {
line = line + "/32"
}
}
prefix, err := netip.ParsePrefix(line)
if err != nil {
log.Fatal(err)
}
prefixes = append(prefixes, prefix)
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return prefixes
}
func mustIPSet(b netipx.IPSetBuilder) *netipx.IPSet {
s, err := b.IPSet()
if err != nil {
log.Fatal(err)
}
return s
}
func main() {
var prefixes []netip.Prefix
if len(os.Args) > 1 {
if os.Args[1] == "-h" || os.Args[1] == "--help" {
fmt.Println("Usage: cat iplist.txt | ip_compact")
return
}
for _, fn := range os.Args[1:] {
prefixes = append(prefixes, readFile(fn)...)
}
} else {
prefixes = readFile("-")
}
var builder netipx.IPSetBuilder
for _, prefix := range prefixes {
builder.AddPrefix(prefix)
}
for _, prefix := range mustIPSet(builder).Prefixes() {
fmt.Println(prefix.String())
}
}