-
Notifications
You must be signed in to change notification settings - Fork 7
/
cidr.go
226 lines (195 loc) · 5.62 KB
/
cidr.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// Package cidr calculates CIDR network
package cidr
import (
"encoding/hex"
"fmt"
"math"
"math/big"
"net"
)
// CIDR https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
type CIDR struct {
ip net.IP
ipnet *net.IPNet
}
// ParseCIDR parses s as a CIDR notation IP address and mask length,
// like "192.0.2.0/24" or "2001:db8::/32", as defined in RFC 4632 and RFC 4291
func ParseCIDR(s string) (*CIDR, error) {
i, n, err := net.ParseCIDR(s)
if err != nil {
return nil, err
}
return &CIDR{ip: i, ipnet: n}, nil
}
// String returns the CIDR string. If the IP prefix of the input CIDR string is inaccurate, it returns the string which be corrected by the mask length. For example, "192.0.2.10/24" return "192.0.2.0/24"
func (c CIDR) String() string {
return c.ipnet.String()
}
// Equal reports whether cidr and ns are the same CIDR
func (c CIDR) Equal(ns string) bool {
c2, err := ParseCIDR(ns)
if err != nil {
return false
}
return c.ipnet.IP.Equal(c2.ipnet.IP)
}
// IsIPv4 reports whether the CIDR is IPv4
func (c CIDR) IsIPv4() bool {
_, bits := c.ipnet.Mask.Size()
return bits/8 == net.IPv4len
}
// IsIPv6 reports whether the CIDR is IPv6
func (c CIDR) IsIPv6() bool {
_, bits := c.ipnet.Mask.Size()
return bits/8 == net.IPv6len
}
// Contains reports whether the CIDR includes ip
func (c CIDR) Contains(ip string) bool {
return c.ipnet.Contains(net.ParseIP(ip))
}
// CIDR returns the CIDR string. If the IP prefix of the input CIDR string is inaccurate, it returns the string which be corrected by the mask length. For example, "192.0.2.10/24" return "192.0.2.0/24"
func (c CIDR) CIDR() string {
return c.ipnet.String()
}
// IP returns the original IP prefix of the input CIDR
func (c CIDR) IP() string {
return c.ip.String()
}
// Network returns network of the CIDR
func (c CIDR) Network() string {
return c.ipnet.IP.String()
}
// MaskSize returns the number of leading ones and total bits in the CIDR mask
func (c CIDR) MaskSize() (ones, bits int) {
ones, bits = c.ipnet.Mask.Size()
return
}
// Mask returns mask of the CIDR
func (c CIDR) Mask() string {
mask, _ := hex.DecodeString(c.ipnet.Mask.String())
return net.IP([]byte(mask)).String()
}
// Broadcast returns broadcast of the CIDR
func (c CIDR) Broadcast() string {
mask := c.ipnet.Mask
bcst := make(net.IP, len(c.ipnet.IP))
copy(bcst, c.ipnet.IP)
for i := 0; i < len(mask); i++ {
ipIdx := len(bcst) - i - 1
bcst[ipIdx] = c.ipnet.IP[ipIdx] | ^mask[len(mask)-i-1]
}
return bcst.String()
}
// IPRange returns begin and end ip of the CIDR
func (c CIDR) IPRange() (begin, end string) {
return c.Network(), c.Broadcast()
}
// IPCount returns ip total of the CIDR
func (c CIDR) IPCount() *big.Int {
ones, bits := c.ipnet.Mask.Size()
return big.NewInt(0).Lsh(big.NewInt(1), uint(bits-ones))
}
// ForEachIP iterate through each ip in the CIDR
func (c CIDR) ForEachIP(iterator func(ip string) error) error {
next := make(net.IP, len(c.ipnet.IP))
copy(next, c.ipnet.IP)
for c.ipnet.Contains(next) {
if err := iterator(next.String()); err != nil {
return err
}
IncrIP(next)
}
return nil
}
// ForEachIPBeginWith begin with specified ip, iterate through each ip in the CIDR
func (c CIDR) ForEachIPBeginWith(beginIP string, iterator func(ip string) error) error {
next := net.ParseIP(beginIP)
for c.ipnet.Contains(next) {
if err := iterator(next.String()); err != nil {
return err
}
IncrIP(next)
}
return nil
}
const (
subnettingMethodSubnetNum = 0
subnettingMethodHostNum = 1
)
// SubNetting split network segment based on the number of hosts or subnets
func (c CIDR) SubNetting(method, num int) ([]*CIDR, error) {
if num < 1 || (num&(num-1)) != 0 {
return nil, fmt.Errorf("num must the power of 2")
}
newOnes := int(math.Log2(float64(num)))
ones, bits := c.MaskSize()
switch method {
default:
return nil, fmt.Errorf("unsupported method")
case subnettingMethodSubnetNum:
newOnes = ones + newOnes
// can't split when subnet mask greater than parent mask
if newOnes > bits {
return nil, nil
}
case subnettingMethodHostNum:
newOnes = bits - newOnes
// can't split when subnet mask not greater than parent mask
if newOnes <= ones {
return nil, nil
}
// calculate subnet num by host num
num = int(math.Pow(float64(2), float64(newOnes-ones)))
}
cidrs := []*CIDR{}
network := make(net.IP, len(c.ipnet.IP))
copy(network, c.ipnet.IP)
for i := 0; i < num; i++ {
cidr, _ := ParseCIDR(fmt.Sprintf("%v/%v", network.String(), newOnes))
cidrs = append(cidrs, cidr)
network = net.ParseIP(cidr.Broadcast())
IncrIP(network)
}
return cidrs, nil
}
// SuperNetting merge network segments, must be contiguous
func SuperNetting(ns []string) (*CIDR, error) {
num := len(ns)
if num < 1 || (num&(num-1)) != 0 {
return nil, fmt.Errorf("ns length must the power of 2")
}
mask := ""
cidrs := make([]*CIDR, 0, num)
for _, n := range ns {
c, err := ParseCIDR(n)
if err != nil {
return nil, fmt.Errorf("invalid CIDR format:%v", n)
}
cidrs = append(cidrs, c)
// TODO only network segments with the same mask are supported
if len(mask) == 0 {
mask = c.Mask()
} else if c.Mask() != mask {
return nil, fmt.Errorf("not the same mask")
}
}
AscSortCIDRs(cidrs)
// check whether contiguous segments
var network net.IP
for _, c := range cidrs {
if len(network) > 0 {
if !network.Equal(c.ipnet.IP) {
return nil, fmt.Errorf("not the contiguous segments")
}
}
network = net.ParseIP(c.Broadcast())
IncrIP(network)
}
// calculate parent segment by mask
c := cidrs[0]
ones, bits := c.MaskSize()
ones = ones - int(math.Log2(float64(num)))
c.ipnet.Mask = net.CIDRMask(ones, bits)
c.ipnet.IP.Mask(c.ipnet.Mask)
return c, nil
}