Takes a netmask as either an IPAddr or a string, and returns the number
  of network bits.  e.g., 255.255.255.0 -> 24
  Raise exception if subnet mask is not CIDR-compatible.
484617
def netmask_to_cidr (dq):
  
  if isinstance(dq, str):
    dq = IPv4Address(dq)
  v = int(dq)
  c = 0
  while v & 0x80000000:
    c += 1
    v <<= 1
  v = v & 0xffFFffFF
  if v != 0:
    raise RuntimeError("Netmask %s is not CIDR-compatible" % (dq,))
  return c
910214
def __ipv4_netmask(value):
    ''''''
    valid, errmsg = False, 'dotted quad or integer CIDR (0->32)'
    valid, value, _ = __int(value)
    if not (valid and 0 <= value <= 32):
        valid = salt.utils.validate.net.netmask(value)
    return (valid, value, errmsg)
340995
def __ipv6_netmask(value):
    ''''''
    valid, errmsg = False, 'IPv6 netmask (0->128)'
    valid, value, _ = __int(value)
    valid = (valid and 0 <= value <= 128)
    return (valid, value, errmsg)
627503
private IPAddress computeMaskFromNetworkPrefix(int prefix) {
		
		/*
		 * int subnet = 0; for (int i=0; i<prefix; i++) { subnet = subnet << 1; subnet += 1; }
		 */
		
		StringBuilder str = new StringBuilder();
		for (int i = 0; i < 32; i++) {
			if (i < prefix) {
				str.append("1");
			} else {
				str.append("0");
			}
		}
		
		String decimalString = toDecimalString(str.toString());
		return new IPAddress(decimalString);
		
	}
348428
def getMask (self, ifname):
        
        if sys.platform == 'darwin':
            return ifconfig_inet(ifname).get('netmask')
        return self._getaddr(ifname, self.SIOCGIFNETMASK)
1224447
def summ(other)
			if (!other.kind_of?(IPv4Net))
				raise ArgumentError, "Expected an IPv4Net object for 'other' but got a #{other.class}."
			end
			
			# netmasks must be identical
			if (self.netmask.prefix_len != other.netmask.prefix_len)
				return nil
			end
			
			# merge-able networks will be identical if you right shift them by the number of bits in the hostmask + 1
			shift = 32 - self.netmask.prefix_len + 1
			addr = self.network.addr >> shift
			otherAddr = other.network.addr >> shift
			if (addr != otherAddr)
				return nil
			end
			return self.resize(self.netmask.prefix_len - 1)
		end
468464
def hosts2map (hosts):
    
    hostset = set()
    nets = []
    for host in hosts:
        if _host_cidrmask_re.match(host):
            host, mask = host.split("/")
            mask = int(mask)
            if not is_valid_cidrmask(mask):
                log.error(LOG_CHECK,
                          "CIDR mask %d is not a valid network mask", mask)
                continue
            if not is_valid_ipv4(host):
                log.error(LOG_CHECK, "host %r is not a valid ip address", host)
                continue
            nets.append(dq2net(host, cidr2mask(mask)))
        elif _host_netmask_re.match(host):
            host, mask = host.split("/")
            if not is_valid_ipv4(host):
                log.error(LOG_CHECK, "host %r is not a valid ip address", host)
                continue
            if not is_valid_ipv4(mask):
                log.error(LOG_CHECK,
                          "mask %r is not a valid ip network mask", mask)
                continue
            nets.append(dq2net(host, netmask2mask(mask)))
        elif is_valid_ip(host):
            hostset.add(expand_ip(host)[0])
        else:
            hostset |= set(resolve_host(host))
    return (hostset, nets)
91865
def ipv4_prefix_to_mask(prefix):
    
    if prefix > 32 or prefix < 0:
        raise ValueError("invalid cidr prefix for ipv4")
    else:
        mask = ((1 << 32) - 1) ^ ((1 << (32 - prefix)) - 1)
        eight_ones = 255  # 0b11111111
        mask_str = ''
        for i in range(0, 4):
            mask_str = str(mask & eight_ones) + mask_str
            mask = mask >> 8
            if i != 3:
                mask_str = '.' + mask_str
        return mask_str
852200
def rel(other)
			if (!other.kind_of?(IPv4Net))
				raise ArgumentError, "Expected an IPv4Net object for 'other' but got a #{other.class}."
			end
			
			# when networks are equal then we can look exlusively at the netmask
			if (self.network.addr == other.network.addr)
				return self.netmask.cmp(other.netmask)
			end
			
			# when networks are not equal we can use hostmask to test if they are
			# related and which is the supernet vs the subnet
			hostmask = self.netmask.mask ^ NetAddr::F32
			otherHostmask = other.netmask.mask ^ NetAddr::F32
			if (self.network.addr|hostmask == other.network.addr|hostmask)
				return 1
			elsif (self.network.addr|otherHostmask == other.network.addr|otherHostmask)
				return -1
			end
			return nil
		end
1259435
def in_subnet(cidr, addrs=None):
    
    for address in addrs:
        if ip_in_subnet(address, cidr):
            return True
    return False
1104879
protected static function checkIPAddressAgainstCIDRMask($ipAddress, $CIDRMask)
    {
        list( $mask, $CIDRSuffix ) = explode('/', $CIDRMask);

        return ( ip2long($ipAddress) & ~( ( 1 << ( 32 - $CIDRSuffix ) ) - 1 ) ) == ip2long($mask);
    }
717952
def network_size(value, options=None, version=None):
    '''
    
    '''
    ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
    if not ipaddr_filter_out:
        return
    if not isinstance(value, (list, tuple, types.GeneratorType)):
        return _network_size(ipaddr_filter_out[0])
    return [
        _network_size(ip_a)
        for ip_a in ipaddr_filter_out
    ]
25549
def get_subnet_cidr(self, subnet_id):
        
        try:
            subnet_list = self.neutronclient.list_subnets(id=subnet_id)
            subnet_dat = subnet_list.get('subnets')[0]
            return subnet_dat.get('cidr')
        except Exception as exc:
            LOG.error("Failed to list subnet for ID %(subnet)s, "
                      "exc %(exc)s", {'subnet': subnet_id, 'exc': exc})
            return None
436241
def in6_isincluded(addr, prefix, plen):
    
    temp = inet_pton(socket.AF_INET6, addr)
    pref = in6_cidr2mask(plen)
    zero = inet_pton(socket.AF_INET6, prefix)
    return zero == in6_and(temp, pref)
1374506
def rel(other)
			if (!other.kind_of?(IPv6Net))
				raise ArgumentError, "Expected an IPv6Net object for 'other' but got a #{other.class}."
			end
			
			# when networks are equal then we can look exlusively at the netmask
			if (self.network.addr == other.network.addr)
				return self.netmask.cmp(other.netmask)
			end
			
			# when networks are not equal we can use hostmask to test if they are
			# related and which is the supernet vs the subnet
			hostmask = self.netmask.mask ^ NetAddr::F128
			otherHostmask = other.netmask.mask ^ NetAddr::F128
			if (self.network.addr|hostmask == other.network.addr|hostmask)
				return 1
			elsif (self.network.addr|otherHostmask == other.network.addr|otherHostmask)
				return -1
			end
			return nil
		end
341513
def get_all_subnets_cidr(self, no_mask=False):
        
        body = {}
        subnet_cidrs = []
        try:
            subnet_list = self.neutronclient.list_subnets(body=body)
            subnet_dat = subnet_list.get('subnets')
            for sub in subnet_dat:
                if no_mask:
                    subnet_cidrs.append(sub.get('cidr').split('/')[0])
                else:
                    subnet_cidrs.append(sub.get('cidr'))
        except Exception as exc:
            LOG.error("Failed to list subnet Exc %s", str(exc))
        return subnet_cidrs
947205
def target_to_ipv4_cidr(target):
    

    splitted = target.split('/')
    if len(splitted) != 2:
        return None
    try:
        start_packed = inet_pton(socket.AF_INET, splitted[0])
        block = int(splitted[1])
    except (socket.error, ValueError):
        return None
    if block <= 0 or block > 30:
        return None
    start_value = int(binascii.hexlify(start_packed), 16) >> (32 - block)
    start_value = (start_value << (32 - block)) + 1
    end_value = (start_value | (0xffffffff >> block)) - 1
    start_packed = struct.pack('!I', start_value)
    end_packed = struct.pack('!I', end_value)
    return ipv4_range_to_list(start_packed, end_packed)