How to calculate the IP range when the IP address and the netmask is given?
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
Solution 1:
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
Solution 2:
I'll just post the code:
IPAddress ip = new IPAddress(new byte[] { 192, 168, 0, 1 });
int bits = 25;
uint mask = ~(uint.MaxValue >> bits);
// Convert the IP address to bytes.
byte[] ipBytes = ip.GetAddressBytes();
// BitConverter gives bytes in opposite order to GetAddressBytes().
byte[] maskBytes = BitConverter.GetBytes(mask).Reverse().ToArray();
byte[] startIPBytes = new byte[ipBytes.Length];
byte[] endIPBytes = new byte[ipBytes.Length];
// Calculate the bytes of the start and end IP addresses.
for (int i = 0; i < ipBytes.Length; i++)
{
startIPBytes[i] = (byte)(ipBytes[i] & maskBytes[i]);
endIPBytes[i] = (byte)(ipBytes[i] | ~maskBytes[i]);
}
// Convert the bytes to IP addresses.
IPAddress startIP = new IPAddress(startIPBytes);
IPAddress endIP = new IPAddress(endIPBytes);
Solution 3:
Invert mask (XOR with ones), AND it with IP. Add 1. This will be the starting range. OR IP with mask. This will be the ending range.