Skip to content

Instantly share code, notes, and snippets.

@satta

satta/cidr.patch Secret

Created April 27, 2022 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satta/7406fe735d8b449a4c9af73822d2bc9a to your computer and use it in GitHub Desktop.
Save satta/7406fe735d8b449a4c9af73822d2bc9a to your computer and use it in GitHub Desktop.
CIDRFromMask endianness
diff --git a/src/util-cidr.c b/src/util-cidr.c
index 06a0c30bc..bdab3063c 100644
--- a/src/util-cidr.c
+++ b/src/util-cidr.c
@@ -31,25 +31,24 @@
*/
int CIDRFromMask(uint32_t netmask)
{
+ netmask = ntohl(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;
- }
+ int p = 0;
+ bool seen_1 = false;
+ while (netmask > 0) {
+ if (netmask & 1) {
+ seen_1 = true;
+ p++;
} else {
- if ((netmask & BIT_U32(i)) != 0) {
+ if (seen_1) {
return -1;
}
}
+ netmask >>= 1;
}
- return lead_1;
+ return p;
}
uint32_t CIDRGet(int cidr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment