Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 656
choy Avatar asked Oct 20 '08 14:10

choy


4 Answers

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?"

like image 166
tvanfosson Avatar answered Oct 06 '22 18:10

tvanfosson


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.

like image 44
Mecki Avatar answered Oct 06 '22 17:10

Mecki


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.

like image 40
joeforker Avatar answered Oct 06 '22 17:10

joeforker


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
like image 44
Eric Hogue Avatar answered Oct 06 '22 16:10

Eric Hogue