0

I need to convert IP range to starting IP with its subnet.

for example, the input:

1.1.1.0 - 1.1.1.255
(255.255.255.0)

the output:

1.1.1.0/24

thanks,

Yakiros
  • 107
  • 2
  • 2
  • 8
  • 1
    Not all ranges will have appropriate CIDR netmasks; how do you intend to handle those? – sarnold May 10 '12 at 22:40
  • to clarify: what would you expect to be output for 1.1.1.3 - 1.1.1.5? – Vlad May 10 '12 at 22:41
  • 1
    As a reference, this is the opposite of what you're asking for: http://stackoverflow.com/questions/1470792/how-to-calculate-the-ip-range-when-the-ip-address-and-the-netmask-is-given – BeemerGuy May 10 '12 at 23:04

1 Answers1

0

It's easy using bitwise operators:

byte[] ip1 = {1, 1, 1, 0};
byte[] ip2 = {1, 1, 1, 255};
byte[] omask = 
{
    (byte)(ip1[0] ^ ip2[0]), 
    (byte)(ip1[1] ^ ip2[1]), 
    (byte)(ip1[2] ^ ip2[2]),
    (byte)(ip1[3] ^ ip2[3])
};
string mask = Convert.ToString(omask[0], 2) + Convert.ToString(omask[1], 2)
              + Convert.ToString(omask[2], 2) + Convert.ToString(omask[3], 2);
// count the number of 1's in the mask. Substract to 32:
// NOTE: the mask doesn't have all the zeroes on the left, but it doesn't matter
int bitsInMask = 32 - (mask.Length - mask.IndexOf("1")); // this is the /n part
byte[] address = 
{
    (byte)(ip1[0] & ip2[0]), 
    (byte)(ip1[1] & ip2[1]), 
    (byte)(ip1[2] & ip2[2]),
    (byte)(ip1[3] & ip2[3])
};
string cidr = address[0] + "." + address[1] + "." 
    + address[2] + "." + address[3] + "/" + bitsInMask;

cidr gives you the network rank.

JotaBe
  • 38,030
  • 8
  • 98
  • 117