Tuesday, April 27, 2010

How to Calculate CIDR, Netmask, etc. For Reals.

I've always been kind of bad with math (yeah I know). I mean, I'm good at stuff like 22*15. (22*10)+((20*5)+(2*5))=330. I can do that in my head.

But when starting in my career, binary math seemed so overwhelming. So I didn't learn it. By the time I got to a point where I needed to calculate CIDR addressing, I had a wonderful tool called the Internet search engine.

So I've been a sysadmin for a long time now, I guess. A sysadmin who could not perform binary math.

No more. Tonight I finally sat my ass down and figured it out. I tried searching explanations online but found very little practical math. A lot of it seemed really complicated and, still overwhelming. After banging my head and pulling my hair (simultaneously, too--what an accomplishment itself!), I finally had that epiphany and sorted it out in like five minutes.

Because interview questions always seem to "base" (Hurrrr, I made a pun.) on the network bits, that's all I am going to address (Look Ma, another one!) in this post.

Here's how to do it:

Given a block /N, find the number of usable addresses and the netmask.

Each octet consists of two sets of 4 bits:

0000 0000 0000 0000 0000 0000 0000 0000

so take N/4 to find the exact number of bits in the network address:

/23 => 23/4=5.75

Fill in 5.75 of those sets with a 1:

1111 1111 1111 1111 1111 1110 0000 0000

To find the number of usable addresses, calculate 2^the number of host bits-2.

2^9-2=510 usable addresses

Now let's find the netmask. This is the trickiest "bit": section up the octets and find the number of host bits in the last octet that is not 0. In this case it is the 3rd octet. Subtract that from 255, and you have that octet in the netmask. All prior octets are 255 (1111 1111) and any subsequent octets are 0 (0000 0000).

255-(2^0)=254

Netmask: 255.255.254.0

Obviously this is the second easiest possible netmask to calculate (the easiest being 0). Let's try a harder block: /17.

/17 => 17/4=4.25

1111 1111 1111 1111 1000 0000 0000 0000

2^15-2=32766 usable addresses

3rd octet "1000 0000" (working 0s right->left)
255-(2^0+2^1+2^2+2^3+2^4+2^5+2^6) = 128

Netmask: 255.255.128.0

I hope you find this useful. I feel it explains it in a much more straightforward way than most resources I've found online.