Jason Soo | Software Engineer

  1. How to calculate CIDR address?

CIDR Notation

12 Oct 2022

I recently had to whitelist some IP addresses for a client to connect over the public internet. We have a Kubernetes application that had to open up via Public Ingress (incoming firewall rules), secured with an OAuth2 token.

The Ingress rules require CIDR addresses. When I used standard IP addresses the Terraform project failed on the plan step as the addresses were not CIDR addresses.

What is CIDR?

Classless Inter-Domain Routing (CIDR) is a method for allocating IP addresses and IP routing (subnet).

Good article about how to calculate CIDR addresses

Good article for beginners

CIDR calculator

Why is it important?

It can be used to define a subnet (network within a network) that can be used to whitelist IPs. For example, define the list of IP addresses allowed to connect through the firewall.


Classes of CIDR

Class A: only the first bit is considered. It can take the IP address from 1.X.X.X to 126.X.X.X

Class B: first two bits are considered. It can take the IP address from 128.0.X.X to 191.255.X.X

Class C: first three bits are considered. It can take the IP address from 192.0.0.X to 223.255.255.X

Class D: first four bits are considered. It can take the IP address from 224.0.0.0 to 239.255.255.255. This Class is used for multicasting

Class E: reserved for Research and Development. It can take the IP address from 240.0.0.0 to 255.255.255.254

How to calculate CIDR address?

CIDR block contains IP addresses, consisting of 3 basic rules

  1. In the CIDR block, the IP addresses which are allocated to the hosts should be continuous
  2. Size of the block should be of power 2 and should be equal to the total number of IP addresses
  3. Size of the block must be divisible by the first IP address of the block.

Example 1 (larger range)

Start IP address = 21.19.35.64, End IP address = 21.19.35.127
Range = 127 - 64 + 1 = 64
Size of the block: 2^6 = 64
Number of bits = 32 - 6 = 26
CIDR block = 21.19.35.64/26

Example 2 (smaller range)

Start IP address = 10.20.16.254, End IP address = 10.20.16.255
Range = 255 - 254 + 1 = 2
Size of the block: 2^1 = 2
Number of bits = 32 - 1 = 31
CIDR block = 10.20.16.254/31

Example 3 (smallest range)

Start IP address = 10.20.16.254, End IP address = 10.20.16.254
Range = 254 - 254 + 1 = 1
Size of the block: 2^0 = 1
Number of bits = 32 - 0 = 32
CIDR block = 10.20.16.254/32