Convert Subnet to CIDR in C#
int Mask2CIDR(IPAddress subnetmask)
{
	try
	{
		Byte[] ipbytes = subnetmask.GetAddressBytes();
 
		uint subnet = 16777216 * Convert.ToUInt32(ipbytes[0]) +
			65536 * Convert.ToUInt32(ipbytes[1]) + 256 * Convert.ToUInt32(ipbytes[2]) + Convert.ToUInt32(ipbytes[3]);
		uint mask = 0x80000000;
		uint subnetConsecutiveOnes = 0;
 
		for (int i = 0; i < 32; i++)
		{
			if (!(mask & subnet).Equals(mask)) break;
 
			subnetConsecutiveOnes++;
			mask = mask >> 1;
		}
 
		return (int)subnetConsecutiveOnes;
	}
	catch
	{
		return -1;
	}
}
Categories: C# Tags: , , ,
%d bloggers like this: