network-programmingtcpipsubnet

Calculating range of IPs from subnet mask


Say, I have a subnet of 255.255.255.242 and I have a known IP within that subnet say 192.168.1.101.

Now the way I calculate the range of IPs is this:

In the subnet mask, find the first octet that is not a 255. In my example, its the 4th octet, and its 242. So take 256 and subtract 242, which gives us 14. So we now know that these networks, the 192.168.1.x networks, all have a range of 14. So just start listing them...

192.168.1.0
192.168.1.14
192.168.1.28
....42
....56
....70
....84
....98
....112

Here we can stop. My address, 192.168.1.101 falls into the .98 network. .98 encompasses all ip addresses from 192.168.1.98 to 192.168.1.111, because we know that 192.168.1.112 starts the next network.

I want to confirm, whether this is the right and the easiest process to do so.


Solution

  • A netmask is a series of 1 bits. The bits must be sequential with no 0 gaps. Anything using a 1 bit is part of the network, anything remaining is valid for host assignment within that network. A 255.255.255.224 has 27 "1" bits, which means it's a /27 network.

    To calculate this right, you need to convert IPs to a numeric representation. For example, 255.255.255.224 is 11111111 11111111 11111111 11100000 which is 4294967264. 192.168.1.101 is 3232235877 (11000000 10101000 00000001 01100101).

    If you take the IP and bitwise AND it with the netmask, that gives you the network address. This is the bottom end of the range:

    11111111 11111111 11111111 11100000  (mask)
    11000000 10101000 00000001 01100101  (ip)
    -----------------------------------
    11000000 10101000 00000001 01100000  = 192.168.1.96  (network address)
    

    The complement (bitwise NOT) of the mask gives you the size of the range:

    00000000 00000000 00000000 00011111  = 31
    

    Thus, the range for that IP is between 192.168.1.96 - 192.168.1.127. (127 = 96 + 31)