How to determine if there is an intersection between two Golang net.IPNet objects?
That is, how to check how , if the first network is a subnet of the second OR , if the second network is a subnet of the first.
Does Go provide any useful feature ready for this particular task?
See test code below.
package main import ( "fmt" "net" ) func main() { _, net1, _ := net.ParseCIDR("1.1.1.1/24") _, net2, _ := net.ParseCIDR("1.1.0.2/16") _, net3, _ := net.ParseCIDR("1.1.1.3/25") _, net4, _ := net.ParseCIDR("1.2.0.4/16") test(net1, net2, true) test(net2, net1, true) test(net1, net3, true) test(net3, net1, true) test(net1, net4, false) test(net4, net1, false) } func test(n1, n2 *net.IPNet, expect bool) { result := intersect(n1, n2) var label string if result == expect { label = "good" } else { label = "FAIL" } fmt.Printf("test intersect(%v,%v)=%v expected=%v => %s\n", n1, n2, result, expect, label) } func intersect(n1, n2 *net.IPNet) bool { return false
Run it on Go to the Playground