To check an invalid network mask, you can use the following simple algorithm:
mask & (~mask >> 1)
This will be evaluated at 1 for an invalid network mask and 0 for a valid network mask.
A valid netmask cannot have zero with one to its right. All zeros must have another zero to the right of it or be bit 0. If you take the additions (~) of the network mask, which has zero with one to the right of it and moves it to the right one bit position, you will align one in the network mask with one in an offset addition to the netmask. And these two values โโtogether will lead to what points to an invalid network mask.
Be sure to use ntohl () to convert the netmask to host byte order before applying this algorithm if it is in the network byte order. In addition, you need to do special checks for 0xffffffff and 0x00000000 if you want to exclude them.
Note. Due to the priority rules and associativity rules for operators, the brackets shown in the algorithm are not needed, but I added them to make the code more understandable if you do not always remember the priority and associativity rules,
int is_netmask_valid(uint32_t mask) { if (mask == 0) return 0; if (mask & (~mask >> 1)) { return 0; } else { return 1; } }
source share