core: function to match ip address to net address with bitmask
authorDaniel-Constantin Mierla <miconda@gmail.com>
Fri, 23 Dec 2011 08:32:24 +0000 (09:32 +0100)
committerDaniel-Constantin Mierla <miconda@gmail.com>
Fri, 23 Dec 2011 08:32:24 +0000 (09:32 +0100)
ip_addr.c
ip_addr.h

index 06c57c3..1b15c96 100644 (file)
--- a/ip_addr.c
+++ b/ip_addr.c
@@ -354,3 +354,60 @@ char* get_proto_name(unsigned int proto)
                        return "unknown";
        }
 }
+
+
+/**
+ * match ip address with net address and bitmask
+ * - return 0 on match, -1 otherwise
+ */
+int ip_addr_match_net(ip_addr_t *iaddr, ip_addr_t *naddr,
+               int mask)
+{
+       unsigned char c;
+       int i;
+       int mbytes;
+       int mbits;
+
+       if(mask==0)
+               return 0;
+       if(iaddr==NULL || naddr==NULL || mask<0)
+               return -1;
+       if(iaddr->af != naddr->af)
+               return -1;
+
+       if(iaddr->af == AF_INET)
+       {
+               if(mask>32)
+                       return -1;
+               if(mask==32)
+               {
+                       if(ip_addr_cmp(iaddr, naddr))
+                               return 0;
+                       return -1;
+               }
+       } else if(iaddr->af ==  AF_INET6) {
+               if(mask>128)
+                       return -1;
+
+               if(mask==128)
+               {
+                       if(ip_addr_cmp(iaddr, naddr))
+                               return 0;
+                       return -1;
+               }
+       }
+
+       mbytes = mask / 8;
+       for(i=0; i<mbytes; i++)
+       {
+               if(iaddr->u.addr[i] != naddr->u.addr[i])
+                       return -1;
+       }
+       mbits = mask % 8;
+       if(mbits==0)
+               return 0;
+       c = naddr->u.addr[i] & (~((1 << (8 - mbits)) - 1));
+       if((iaddr->u.addr[i] & c) == c)
+               return 0;
+       return -1;
+}
index 0c1a129..9bfe670 100644 (file)
--- a/ip_addr.h
+++ b/ip_addr.h
@@ -72,7 +72,7 @@ struct ip_addr{
        }u;
 };
 
-
+typedef struct ip_addr ip_addr_t;
 
 struct net{
        struct ip_addr ip;
@@ -825,5 +825,10 @@ inline static void init_dst_from_rcv(struct dest_info* dst,
 #endif
 }
 
+/**
+ * match ip address with net address and bitmask
+ * - return 0 on match, -1 otherwise
+ */
+int ip_addr_match_net(ip_addr_t *iaddr, ip_addr_t *naddr, int mask);
 
 #endif