forked from EvilSuperstars/go-cidrman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.go
75 lines (63 loc) · 1.62 KB
/
merge.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
// Inspired by the Python netaddr cidr_merge function
// https://netaddr.readthedocs.io/en/latest/api.html#netaddr.cidr_merge.
package cidrman
import (
"errors"
"net"
)
type ipNets []*net.IPNet
func (nets ipNets) toCIDRs() []string {
var cidrs []string
for _, net := range nets {
cidrs = append(cidrs, net.String())
}
return cidrs
}
// MergeIPNets accepts a list of IP networks and merges them into the smallest possible list of IPNets.
// It merges adjacent subnets where possible, those contained within others and removes any duplicates.
func MergeIPNets(nets []*net.IPNet) ([]*net.IPNet, error) {
if nets == nil {
return nil, nil
}
if len(nets) == 0 {
return make([]*net.IPNet, 0), nil
}
// Split into IPv4 and IPv6 lists.
// Merge the list separately and then combine.
var block4s cidrBlock4s
for _, net := range nets {
ip4 := net.IP.To4()
if ip4 != nil {
block4s = append(block4s, newBlock4(ip4, net.Mask))
} else {
return nil, errors.New("Not implemented")
}
}
merged, err := merge4(block4s)
if err != nil {
return nil, err
}
return merged, nil
}
// MergeCIDRs accepts a list of CIDR blocks and merges them into the smallest possible list of CIDRs.
func MergeCIDRs(cidrs []string) ([]string, error) {
if cidrs == nil {
return nil, nil
}
if len(cidrs) == 0 {
return make([]string, 0), nil
}
var networks []*net.IPNet
for _, cidr := range cidrs {
_, network, err := net.ParseCIDR(cidr)
if err != nil {
return nil, err
}
networks = append(networks, network)
}
mergedNets, err := MergeIPNets(networks)
if err != nil {
return nil, err
}
return ipNets(mergedNets).toCIDRs(), nil
}