]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
util/cidr: add util to convert netmask to cidr
authorVictor Julien <vjulien@oisf.net>
Tue, 1 Mar 2022 11:41:49 +0000 (12:41 +0100)
committerVictor Julien <vjulien@oisf.net>
Mon, 21 Mar 2022 08:17:32 +0000 (09:17 +0100)
(cherry picked from commit a67b97e14c08f46f50c1acd989f0dc049a8e4cba)

src/util-cidr.c
src/util-cidr.h

index 41d9b66536f5e1a427c7afc44acf4ca9f0abbc13..06a0c30bc2143d859c90992cd8e80d65729987c5 100644 (file)
 #include "suricata-common.h"
 #include "util-cidr.h"
 
+/** \brief turn 32 bit mask into CIDR
+ *  \retval cidr cidr value or -1 if the netmask can't be expressed as cidr
+ */
+int CIDRFromMask(uint32_t netmask)
+{
+    if (netmask == 0) {
+        return 0;
+    }
+    int lead_1 = 0;
+    bool seen_0 = false;
+    for (int i = 0; i < 32; i++) {
+        if (!seen_0) {
+            if ((netmask & BIT_U32(i)) != 0) {
+                lead_1++;
+            } else {
+                seen_0 = true;
+            }
+        } else {
+            if ((netmask & BIT_U32(i)) != 0) {
+                return -1;
+            }
+        }
+    }
+    return lead_1;
+}
+
 uint32_t CIDRGet(int cidr)
 {
     if (cidr <= 0 || cidr > 32)
index 3653b8b95a972a7fdd9ad393f37145fca2871670..a5d4a94bbba682436c6c42a7886a45adc76743ee 100644 (file)
@@ -24,6 +24,7 @@
 #ifndef __UTIL_NETMASK_H__
 #define __UTIL_NETMASK_H__
 
+int CIDRFromMask(uint32_t netmask);
 uint32_t CIDRGet(int);
 void CIDRGetIPv6(int cidr, struct in6_addr *in6);