A tip to calculate CIDR block
CIDR Block Calculation
CIDR (Classless Inter-Domain Routing) is a notation to describe a range of IP addresses. It is used a lot in IP routing.
An IPv4 address consists of 4 octets. In some cases (if the netmask number is the multiple of 8), the CIDR block describes which octets specifying the network, and which octets specifying the hosts.
For example: there is an IP 10.165.1.165
. Can we directly tell if 10.165.2.10
also lives in the same network? We cannot, because we simply don’t know how the network is organised.
Now if we know the CIDR block of the network is 10.165.0.0/16
. We will be able to tell 10.165.2.10
lives in the same network.
Here is how the calculation of 10.165.0.0/16
works:
Base IP: 10.165.0.0
Netmask length: 16
Base IP in bits: 00001010.10100101.00000000.00000000 (each octet is 8 bits long)
Netmask in bits: 11111111.11111111.00000000.00000000 (16 1s)
Fixed bits: 00001010.10100101
Variable bits: .xxxxxxxx.xxxxxxxx
First IP in bits: 00001010.10100101.00000000.00000000
Last IP in bits: 00001010.10100101.11111111.11111111
First IP: 10.165.0.0
Last IP: 10.165.255.255
Netmask: 255.255.0.0
As we can see, each octet is 8 bits long, so if the netmask number is a multiple of 8 (i.e. 8, 16, 24 and 32), we can quickly tell how many octets are fixed, so that we can easily get the range. In the earlier example 10.165.0.0/16
, we can firstly see the netmask number is 16. As 16=8*2, the first two octets from 10.165.0.0
are fixed, so the IP ranges would be 10.165.0.0 ~ 10.165.255.255
.
What if netmask is not the multiple of 8
To calculate the IP ranges of a CIDR whose netmask is not a multiple of 8, I usually Google “CIDR calculator”, but recently I found out a trick to do the math by ourselves.
The principle is: the total IP number of a CIDR block = 2 ^ (32 - its netmask number). For example, the total number of the IP address in 10.165.1.0/28
is 2^(32-28)=16
.
This principle can be used for some simple CIDR calculation. for example, to calculate 10.165.1.0/28
, you can do:
Base IP: 10.165.1.0
Netmask length: 28
Difference of netmask number with /32: 4
The number of more IPs than /32: 2^4-1=15
/32 IP Range: 10.165.1.0
/28 IP Range = /32 IP Range + 15 extra IPs
/28 IP Range: 10.165.1.0 ~ 10.165.1.15
/32 Netmask: 255.255.255.255
/28 Netmask = /32 Netmask - 15 extra IPs
/28 Netmask: 255.255.255.240
But this may not work for something like /12
, as the total number would become 1048576
, and you can hardly calculate it back how many octets you should reverse back from the IP of /32
.
Conclusion
CIDR calculator is still a useful tool. This math tip isn’t telling you to get rid of the calculator, but I hope it’s fun to read!