How to calculate the IP range when the IP address and the netmask is given?

Anheledir picture Anheledir · Sep 24, 2009 · Viewed 120.7k times · Source

When a IP-Range is written as aaa.bbb.ccc.ddd/netmask (CIDR Notation) I need to calculate the first and the last included ip address in this range with C#.

Example:

Input: 192.168.0.1/25

Result: 192.168.0.1 - 192.168.0.126

Answer

balexandre picture balexandre · Sep 24, 2009

my good friend Alessandro have a nice post regarding bit operators in C#, you should read about it so you know what to do.

It's pretty easy. If you break down the IP given to you to binary, the network address is the ip address where all of the host bits (the 0's in the subnet mask) are 0,and the last address, the broadcast address, is where all the host bits are 1.

For example:

ip 192.168.33.72 mask 255.255.255.192

11111111.11111111.11111111.11000000 (subnet mask)
11000000.10101000.00100001.01001000 (ip address)

The bolded parts is the HOST bits (the rest are network bits). If you turn all the host bits to 0 on the IP, you get the first possible IP:

11000000.10101000.00100001.01000000 (192.168.33.64)

If you turn all the host bits to 1's, then you get the last possible IP (aka the broadcast address):

11000000.10101000.00100001.01111111 (192.168.33.127)

So for my example:

the network is "192.168.33.64/26":
Network address: 192.168.33.64
First usable: 192.168.33.65 (you can use the network address, but generally this is considered bad practice)
Last useable: 192.168.33.126
Broadcast address: 192.168.33.127