What's the best way to convert from network bitcount to netmask?

Assuming 32-bit mask and 32-bit int.

int keepBits = 24;  /* actually get it from somewhere else? */

int mask = (0xffffffff >> (32 - keepBits )) << (32 - keepBits);

Note: this isn't necessarily the answer to the question "What's the best way to get the network mask for an interface?"


I always do it like that (in your case cidr = 24):

uint32_t ipv4Netmask;

ipv4Netmask = 0xFFFFFFFF;
ipv4Netmask <<= 32 - cidr;
ipv4Netmask = htonl(ipv4Netmask);

This will only work with ipv4Netmask to be actually uint32_t, don't make it int, as int doesn't have to be 32 Bit on every system. The result is converted to network byte order, as that's what most system functions expect.

Note that this code will fail if cidr is zero as then the code would shift a 32 bit variable by 32 bit and, believe it or not, that is undefined behavior in C. One would expect the result to always be zero but the C standard says that this is not defined to begin with. If your CIDR can be zero (which would only be allowed in the any IP address placeholder 0.0.0.0/0), then the code must catch special case.