THis methods checks if the first IP network contains the second (the maskSize of first should be <= that the maskSize of second, and their IPs should be identical for the duration of the first mask:
func ContainsIPNetwork(first, second net.IPNet) bool {
if len(first.IP) != len(second.IP) {
return false
}
i := len(first.IP) - 1
for i > 0 && (first.Mask[i]|second.Mask[i] == 0) {
i--
}
if first.Mask[i] > second.Mask[i] || ((first.IP[i]^second.IP[i])&first.Mask[i] != 0) {
return false
}
i--
for i >= 0 && first.IP[i] == second.IP[i] {
i--
}
return i == -1
}
There is a bug in the code above, it works for most cases, but not all. Can you figure it out ?
I for one cannot, but there is certainly a bug. What should I do to figure it out ?
first {IP:0.0.0.0 Mask:00000000}, second {IP:2.0.0.0 Mask:ffffffff}, contains false <–wrong
first {IP:0.0.0.0 Mask:00000000}, second {IP:255.255.255.255 Mask:ffffffff}, contains false <–wrong
when i == 0, first.IP[0] == 0 and second.IP[0] == 2, so the loop breaks and returns i == -1 (0 == -1, false).
For your second example, in the same loop, when i is decremented from 3 to 2, first.IP[2] == 0 and second.IP[2] == 255, so the loop breaks and returns i == -1 (2 == -1, false).