-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
116 lines (97 loc) · 2.42 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
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
package main
import (
"crypto/rand"
"flag"
"fmt"
"net"
"os"
"strings"
)
var (
version = "dev"
commit = "none"
date = "unknown"
)
func main() {
oneMb := 1024 * 1024
n := -1
outpath := "-"
excludedRangesStr := ""
v6 := false
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options]\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Generates random IPv4 addresses and writes them to a stream\n")
fmt.Fprintf(os.Stderr, "Version: %s (%s) at %s\n\n", version, commit, date)
flag.PrintDefaults()
}
flag.IntVar(&n, "n", -1, "Number of IPs to generate. -1 means infinite")
flag.StringVar(&outpath, "o", "-", "Output path for the generated data")
flag.StringVar(&excludedRangesStr, "x", "", "IP ranges to exclude from the generated data (format: range,range,range)")
flag.BoolVar(&v6, "6", false, "Generate IPv6 addresses instead of IPv4 addresses (default: false)")
flag.Parse()
excludedRanges := ParseExcludedRanges(excludedRangesStr)
outFile := SetupOutput(outpath)
ipBytesMultiplier := 1
if v6 {
ipBytesMultiplier = 4
}
buf := make([]byte, 0, oneMb)
bufLen := 0
generateRandomIP := func() net.IP {
ip := make(net.IP, 4*ipBytesMultiplier)
rand.Read(ip)
return ip
}
for i := 0; n == -1 || i < n; i++ {
ip := generateRandomIP()
if len(excludedRanges) > 0 && IsExcluded(ip, excludedRanges) {
i--
continue
}
ipStr := ip.String()
ipBytes := append([]byte(ipStr), '\n')
if bufLen+len(ipStr) > oneMb {
outFile.Write(buf)
// reset buffer
buf = buf[:0]
bufLen = 0
}
buf = append(buf, ipBytes...)
bufLen += len(ipBytes)
}
outFile.Write(buf)
}
func SetupOutput(outpath string) *os.File {
outFile := os.Stdout
if outpath != "-" {
var err error
outFile, err = os.Create(outpath)
if err != nil {
panic(err)
}
}
return outFile
}
func ParseExcludedRanges(excludedRangesStr string) []net.IPNet {
var excludedRanges []net.IPNet = make([]net.IPNet, 0)
if len(excludedRangesStr) > 0 {
ranges := strings.Split(excludedRangesStr, ",")
for _, excludedRange := range ranges {
_, network, err := net.ParseCIDR(excludedRange)
if err != nil {
panic(err)
}
excludedRanges = append(excludedRanges, *network)
}
}
return excludedRanges
}
// Checks if an IP is in any of the excluded ranges
func IsExcluded(ip net.IP, excludedRanges []net.IPNet) bool {
for _, network := range excludedRanges {
if network.Contains(ip) {
return true
}
}
return false
}