pevhs.ch ~/etc/

Finding out the subnet of an IP address

Consider the following IPv4 address: 192.168.34.82 with a CIDR of /28.

We want to find out:

The address of the subnet

We need to do a bitwise AND on the mask and the IP address:

11111111.11111111.11111111.11110000 <- the CIDR converted in bits
  192   .  168   .   34   .01010010 <- the IP address in bits

                          .01010000 <- the result of the bitwise AND

Which gives us: 192.168.34.80

Note: It's unnecessary to convert the parts of the IP address that are under full rows of 1. Since a bitwise AND will return 0 if one of the two values checked is 0, those parts will remain unchanged. Think about it.

The address of the broadcast

This time, a bitwise OR on the inverted mask and the IP address:

00000000.00000000.00000000.00001111
  192   .  168   .   34   .01010010

                          .01011111

And we end with: 192.168.34.111

Note: Also unnecessary here, since a bitwise OR will return 1 if one of the values checked is 1.

The number of subnets

2 power "the number of bits of the subnet mask minus the number of bits from the default mask of the IP class". As we know that the IP address is a C class, we can do:

28 - 24 = 4
2^4 = 16

And we have our answer.

The maximum number of hosts for each subnet

The number of bits required to make an IP address is 32. Let's remove the number of bits taken by the subnet mask and we get 4. 2 to the power of 4 equals 16. But this calculation doesn't take into account that there is two addresses already taken by the network address and the broadcast, so 16 becomes 14.

32 - 28 = 4
2^4 = 16
16 - 2 = 14

This subnet is only one of the 16 other ones created by this subnet mask. If we wanted to get the first one created by this mask, we can simply set the bits after the default mask to 0 and we get 192.168.34.0. Since we know the maximum number of hosts is 14, we can just add 14 + 1 to this address and we get this time the broadcast 192.168.34.15. + 1 to get the next subnet address, etc.