Skip to content

Commit

Permalink
Merge pull request #2806 from weaveworks/commutative-network-calc
Browse files Browse the repository at this point in the history
make network calculation commutative
  • Loading branch information
rade authored Aug 11, 2017
2 parents badac90 + 7db84ab commit 0b283b0
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
19 changes: 12 additions & 7 deletions report/networks.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,20 @@ func ContainingIPv4Network(ips []net.IP) *net.IPNet {
if len(ips) == 0 {
return nil
}
network := net.IPNet{
IP: ips[0],
Mask: net.CIDRMask(net.IPv4len*8, net.IPv4len*8),
}
cpl := net.IPv4len * 8
network := networkFromPrefix(ips[0], cpl)
for _, ip := range ips[1:] {
network.Mask = net.CIDRMask(commonIPv4PrefixLen(network.IP, ip), net.IPv4len*8)
network.IP = network.IP.Mask(network.Mask)
if ncpl := commonIPv4PrefixLen(network.IP, ip); ncpl < cpl {
cpl = ncpl
network = networkFromPrefix(network.IP, cpl)
}
}
return &network
return network
}

func networkFromPrefix(ip net.IP, prefixLen int) *net.IPNet {
mask := net.CIDRMask(prefixLen, net.IPv4len*8)
return &net.IPNet{IP: ip.Mask(mask), Mask: mask}
}

func commonIPv4PrefixLen(a, b net.IP) int {
Expand Down
1 change: 1 addition & 0 deletions report/networks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ func TestContainingIPv4Network(t *testing.T) {
assert.Nil(t, containingIPv4Networks([]string{}))
assert.Equal(t, "10.0.0.1/32", containingIPv4Networks([]string{"10.0.0.1"}).String())
assert.Equal(t, "10.0.0.0/17", containingIPv4Networks([]string{"10.0.0.1", "10.0.2.55", "10.0.106.48"}).String())
assert.Equal(t, "10.0.0.0/16", containingIPv4Networks([]string{"10.0.128.1", "10.0.0.1", "10.0.0.2"}).String())
assert.Equal(t, "0.0.0.0/0", containingIPv4Networks([]string{"10.0.0.1", "192.168.0.1"}).String())
}

Expand Down

0 comments on commit 0b283b0

Please sign in to comment.