-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathipgen.go
More file actions
127 lines (105 loc) · 2.36 KB
/
ipgen.go
File metadata and controls
127 lines (105 loc) · 2.36 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main
import (
"fmt"
"net"
)
// Sampling strategies for different modes
var (
// fast: common gateway/DNS positions
fastOctets = []int{1, 53, 254}
// medium: expanded common positions
mediumOctets = []int{1, 2, 10, 53, 100, 200, 254}
// all: every usable IP (generated dynamically)
)
func ExpandCIDR(blocks []string, mode string) <-chan string {
out := make(chan string, 10000)
go func() {
defer close(out)
for _, block := range blocks {
for ip := range expandBlock(block, mode) {
out <- ip
}
}
}()
return out
}
func expandBlock(cidr string, mode string) <-chan string {
out := make(chan string, 1000)
go func() {
defer close(out)
_, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
return
}
ones, bits := ipnet.Mask.Size()
if bits != 32 {
return // Only IPv4
}
base := ipnet.IP.To4()
if base == nil {
return
}
// Get octets to sample based on mode
var octets []int
switch mode {
case "fast":
octets = fastOctets
case "medium":
octets = mediumOctets
case "all":
// Generate all 1-254
octets = make([]int, 254)
for i := 1; i <= 254; i++ {
octets[i-1] = i
}
default:
octets = fastOctets
}
// Expand based on prefix length
numHosts := uint32(1) << (32 - ones)
baseInt := ipToUint32(base)
// Iterate through each /24 in the range
for i := uint32(0); i < numHosts; i += 256 {
subnetBase := uint32ToIP(baseInt + i)
for _, o4 := range octets {
out <- fmt.Sprintf("%d.%d.%d.%d", subnetBase[0], subnetBase[1], subnetBase[2], o4)
}
}
}()
return out
}
func CountCIDRIPs(blocks []string, mode string) int {
var octetsPerSubnet int
switch mode {
case "fast":
octetsPerSubnet = len(fastOctets)
case "medium":
octetsPerSubnet = len(mediumOctets)
case "all":
octetsPerSubnet = 254
default:
octetsPerSubnet = len(fastOctets)
}
total := 0
for _, cidr := range blocks {
_, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
continue
}
ones, _ := ipnet.Mask.Size()
numHosts := 1 << (32 - ones)
num24s := numHosts / 256
if num24s == 0 {
num24s = 1
}
total += num24s * octetsPerSubnet
}
return total
}
func ipToUint32(ip net.IP) uint32 {
ip = ip.To4()
return uint32(ip[0])<<24 | uint32(ip[1])<<16 | uint32(ip[2])<<8 | uint32(ip[3])
}
func uint32ToIP(n uint32) net.IP {
return net.IPv4(byte(n>>24), byte(n>>16), byte(n>>8), byte(n)).To4()
}