C for a valid network mask

Is there a way to verify that the 32-bit netmask is valid or not being used by the bitwise operator?

I need to check on the msb side that '1' is in a continuous stream or not. for example, 11111111.0.0.0 (255.0.0.0) but 11111101.0.0.0 (253.0.0.0) is not.

+6
source share
2 answers

The first thing to do is to verify that the netmask is not zero (an unpleasant edge case). Given that this is normal, you need to take the bitwise inverse.

uint32_t y = ~x; 

Then add one

 uint32_t z = y + 1; 

Then, if x was the correct network mask, there will be no more than 1 bit in it.

To check this, simply z with z - 1 , which happens to be y . The result will be zero if everything is in order, otherwise there is no zero.

 valid = (z & y) == 0; 
+12
source

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; } } 
+1
source

Source: https://habr.com/ru/post/948458/


All Articles