Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c code for valid netmask

Tags:

c

networking

I there any way to check that 32 bit netmask is valid or not using bitwise operator?

I have to check from msb side that '1' are in continuous stream or not. eg 11111111.0.0.0 (255.0.0.0)is valid but 11111101.0.0.0 (253.0.0.0) is not.

like image 866
Vid Avatar asked Jul 01 '13 09:07

Vid


1 Answers

First thing to do is to check for the netmask being non zero (a nasty edge case). Given this is ok, you need to take the bitwise inverse.

uint32_t y = ~x;

Then add one

uint32_t z = y + 1;

Then if x was a proper netmask, there will be at most 1 bit set in this.

To test that, simply and z with z - 1, which happens to be y. The result will be zero if all is OK, non zero otherwise.

valid = (z & y) == 0;
like image 150
Tom Tanner Avatar answered Oct 18 '22 16:10

Tom Tanner