Browse code

Add an helper function to check if two network overlaps. Also add unit tests for this function

Guillaume J. Charmes authored on 2013/04/04 06:53:54
Showing 2 changed files
... ...
@@ -29,6 +29,19 @@ func networkRange(network *net.IPNet) (net.IP, net.IP) {
29 29
 	return firstIP, lastIP
30 30
 }
31 31
 
32
+// Detects overlap between one IPNet and another
33
+func networkOverlaps(netX *net.IPNet, netY *net.IPNet) bool {
34
+	firstIP, _ := networkRange(netX)
35
+	if netY.Contains(firstIP) {
36
+		return true
37
+	}
38
+	firstIP, _ = networkRange(netY)
39
+	if netX.Contains(firstIP) {
40
+		return true
41
+	}
42
+	return false
43
+}
44
+
32 45
 // Converts a 4 bytes IP into a 32 bit integer
33 46
 func ipToInt(ip net.IP) int32 {
34 47
 	return int32(binary.BigEndian.Uint32(ip.To4()))
... ...
@@ -217,3 +217,38 @@ func assertIPEquals(t *testing.T, ip1, ip2 net.IP) {
217 217
 		t.Fatalf("Expected IP %s, got %s", ip1, ip2)
218 218
 	}
219 219
 }
220
+
221
+func AssertOverlap(CIDRx string, CIDRy string, t *testing.T) {
222
+	_, netX, _ := net.ParseCIDR(CIDRx)
223
+	_, netY, _ := net.ParseCIDR(CIDRy)
224
+	if !networkOverlaps(netX, netY) {
225
+		t.Errorf("%v and %v should overlap", netX, netY)
226
+	}
227
+}
228
+
229
+func AssertNoOverlap(CIDRx string, CIDRy string, t *testing.T) {
230
+	_, netX, _ := net.ParseCIDR(CIDRx)
231
+	_, netY, _ := net.ParseCIDR(CIDRy)
232
+	if networkOverlaps(netX, netY) {
233
+		t.Errorf("%v and %v should not overlap", netX, netY)
234
+	}
235
+}
236
+
237
+func TestNetworkOverlaps(t *testing.T) {
238
+	//netY starts at same IP and ends within netX
239
+	AssertOverlap("172.16.0.1/24", "172.16.0.1/25", t)
240
+	//netY starts within netX and ends at same IP
241
+	AssertOverlap("172.16.0.1/24", "172.16.0.128/25", t)
242
+	//netY starts and ends within netX
243
+	AssertOverlap("172.16.0.1/24", "172.16.0.64/25", t)
244
+	//netY starts at same IP and ends outside of netX
245
+	AssertOverlap("172.16.0.1/24", "172.16.0.1/23", t)
246
+	//netY starts before and ends at same IP of netX
247
+	AssertOverlap("172.16.1.1/24", "172.16.0.1/23", t)
248
+	//netY starts before and ends outside of netX
249
+	AssertOverlap("172.16.1.1/24", "172.16.0.1/23", t)
250
+	//netY starts and ends before netX
251
+	AssertNoOverlap("172.16.1.1/25", "172.16.0.1/24", t)
252
+	//netX starts and ends before netY
253
+	AssertNoOverlap("172.16.1.1/25", "172.16.2.1/24", t)
254
+}