For example, if I have a network spec like 172.20.10.0/24, "24" is the bitcount. What's the best way to convert that to a netmask like 0xffffff00 ?
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.
Why waste time with subtraction or ternary statements?
int suffix = 24;
int mask = 0xffffffff ^ 0xffffffff >> suffix;
If you know your integer is exactly 32 bits long then you only need to type 0xffffffff once.
int32_t mask = ~(0xffffffff >> suffix);
Both compile to the exact same assembly code.
This is not a programming question, but in linux you can use whatmask.
whatmask 72.20.10.0/24
returns
IP Entered = ..................: 72.20.10.0
CIDR = ........................: /24
Netmask = .....................: 255.255.255.0
Netmask (hex) = ...............: 0xffffff00
Wildcard Bits = ...............: 0.0.0.255
------------------------------------------------
Network Address = .............: 72.20.10.0
Broadcast Address = ...........: 72.20.10.255
Usable IP Addresses = .........: 254
First Usable IP Address = .....: 72.20.10.1
Last Usable IP Address = ......: 72.20.10.254
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With