import struct
import socket


def _ConvertMaskToCIDR(mask):
  """Convert a netmask like 255.255.255.0 to a CIDR length like /24."""
  bits = int(struct.unpack('!I', socket.inet_pton(socket.AF_INET, mask))[0])
  found_one_bit = False
  maskbits = 0
  for i in range(32):
    if (bits >> i) & 1 == 1:
      found_one_bit = True
    elif found_one_bit:
      return -1
    else:
      maskbits += 1
  return 32 - maskbits