See Get CIDR from Network Mask
Using:
var cidrnetmask = MaskToCIDR(IPAddress.Parse("255.0.0.0").GetAddressBytes());
This works for IPv4. To support IPv6, it was possible to increase the number of bytes, but hopefully no one will try to use the old-style network layouts for IPv6: o)
Method:
static int MaskToCIDR(byte[] bytes) { var b0 = bytes[0]; var b1 = bytes[1]; var b2 = bytes[2]; var b3 = bytes[3]; return b3 != 0 ? ( (b3 & 0x01) != 0 ? 32 : (b3 & 0x02) != 0 ? 31 : (b3 & 0x04) != 0 ? 30 : (b3 & 0x08) != 0 ? 29 : (b3 & 0x10) != 0 ? 28 : (b3 & 0x20) != 0 ? 27 : (b3 & 0x40) != 0 ? 26 : 25 ) : b2 != 0 ? ( (b2 & 0x01) != 0 ? 24 : (b2 & 0x02) != 0 ? 23 : (b2 & 0x04) != 0 ? 22 : (b2 & 0x08) != 0 ? 21 : (b2 & 0x10) != 0 ? 20 : (b2 & 0x20) != 0 ? 19 : (b2 & 0x40) != 0 ? 18 : 17 ) : b1 != 0 ? ( (b1 & 0x01) != 0 ? 16 : (b1 & 0x02) != 0 ? 15 : (b1 & 0x04) != 0 ? 14 : (b1 & 0x08) != 0 ? 13 : (b1 & 0x10) != 0 ? 12 : (b1 & 0x20) != 0 ? 11 : (b1 & 0x40) != 0 ? 10 : 9 ) : b0 != 0 ? ( (b0 & 0x01) != 0 ? 8 : (b0 & 0x02) != 0 ? 7 : (b0 & 0x04) != 0 ? 6 : (b0 & 0x08) != 0 ? 5 : (b0 & 0x10) != 0 ? 4 : (b0 & 0x20) != 0 ? 3 : (b0 & 0x40) != 0 ? 2 : 1 ) : 0; }
source share