Browse code

core: function to match ip address to net address with bitmask

Daniel-Constantin Mierla authored on 23/12/2011 08:32:24
Showing 2 changed files
... ...
@@ -354,3 +354,60 @@ char* get_proto_name(unsigned int proto)
354 354
 			return "unknown";
355 355
 	}
356 356
 }
357
+
358
+
359
+/**
360
+ * match ip address with net address and bitmask
361
+ * - return 0 on match, -1 otherwise
362
+ */
363
+int ip_addr_match_net(ip_addr_t *iaddr, ip_addr_t *naddr,
364
+		int mask)
365
+{
366
+	unsigned char c;
367
+	int i;
368
+	int mbytes;
369
+	int mbits;
370
+
371
+	if(mask==0)
372
+		return 0;
373
+	if(iaddr==NULL || naddr==NULL || mask<0)
374
+		return -1;
375
+	if(iaddr->af != naddr->af)
376
+		return -1;
377
+
378
+	if(iaddr->af == AF_INET)
379
+	{
380
+		if(mask>32)
381
+			return -1;
382
+		if(mask==32)
383
+		{
384
+			if(ip_addr_cmp(iaddr, naddr))
385
+				return 0;
386
+			return -1;
387
+		}
388
+	} else if(iaddr->af ==  AF_INET6) {
389
+		if(mask>128)
390
+			return -1;
391
+
392
+		if(mask==128)
393
+		{
394
+			if(ip_addr_cmp(iaddr, naddr))
395
+				return 0;
396
+			return -1;
397
+		}
398
+	}
399
+
400
+	mbytes = mask / 8;
401
+	for(i=0; i<mbytes; i++)
402
+	{
403
+		if(iaddr->u.addr[i] != naddr->u.addr[i])
404
+			return -1;
405
+	}
406
+	mbits = mask % 8;
407
+	if(mbits==0)
408
+		return 0;
409
+	c = naddr->u.addr[i] & (~((1 << (8 - mbits)) - 1));
410
+	if((iaddr->u.addr[i] & c) == c)
411
+		return 0;
412
+	return -1;
413
+}
... ...
@@ -72,7 +72,7 @@ struct ip_addr{
72 72
 	}u;
73 73
 };
74 74
 
75
-
75
+typedef struct ip_addr ip_addr_t;
76 76
 
77 77
 struct net{
78 78
 	struct ip_addr ip;
... ...
@@ -825,5 +825,10 @@ inline static void init_dst_from_rcv(struct dest_info* dst,
825 825
 #endif
826 826
 }
827 827
 
828
+/**
829
+ * match ip address with net address and bitmask
830
+ * - return 0 on match, -1 otherwise
831
+ */
832
+int ip_addr_match_net(ip_addr_t *iaddr, ip_addr_t *naddr, int mask);
828 833
 
829 834
 #endif