Return a random IPv4 address from the given CIDR block.

    :key str cidr: CIDR block
    :returns: An IPv4 address from the given CIDR block
    :rtype: ipaddress.IPv4Address
973541
def random_ipv4(cidr='10.0.0.0/8'):
    
    try:
        u_cidr = unicode(cidr)
    except NameError:
        u_cidr = cidr
    network = ipaddress.ip_network(u_cidr)
    start = int(network.network_address) + 1
    end = int(network.broadcast_address)
    randint = random.randrange(start, end)
    return ipaddress.ip_address(randint)
396237
function CIDR(addr, prefixLen) {
  if (prefixLen === undefined) {
    /* OK to pass pass string of "<addr>/<prefix>" */
    assert.string(addr);
    var fields = addr.match(/^([a-fA-F0-9:.]+)\/([0-9]+)$/);
    if (fields === null) {
      throw new Error('Invalid argument: <addr>/<prefix> expected');
    }
    addr = fields[1];
    prefixLen = parseInt(fields[2], 10);
  }
  assert.number(prefixLen);
  prefixLen = prefixLen | 0;
  addr = _toAddr(addr);

  /* Expand prefix to ipv6 length of bare ipv4 address provided */
  if (addr._attrs.ipv4Bare) {
    prefixLen += 96;
  }
  if (prefixLen < 0 || prefixLen > 128) {
    throw new Error('Invalid prefix length');
  }
  this._prefix = prefixLen;
  this._mask = _prefixToAddr(prefixLen);
  this._addr = addr.and(this._mask);
}
273119
def nextfreeip(self):
        
        allocated_ips = [ipaddress.ip_address(host['ip']) for host in self.hosts]
        for ip in self.netaddr:
            if str(ip).split('.')[-1] == '0':
                continue
            if ip not in allocated_ips:
                return ip
1314168
def target_to_ipv6_cidr(target):
    

    splitted = target.split('/')
    if len(splitted) != 2:
        return None
    try:
        start_packed = inet_pton(socket.AF_INET6, splitted[0])
        block = int(splitted[1])
    except (socket.error, ValueError):
        return None
    if block <= 0 or block > 126:
        return None
    start_value = int(binascii.hexlify(start_packed), 16) >> (128 - block)
    start_value = (start_value << (128 - block)) + 1
    end_value = (start_value | (int('ff' * 16, 16) >> block)) - 1
    high = start_value >> 64
    low = start_value & ((1 << 64) - 1)
    start_packed = struct.pack('!QQ', high, low)
    high = end_value >> 64
    low = end_value & ((1 << 64) - 1)
    end_packed = struct.pack('!QQ', high, low)
    return ipv6_range_to_list(start_packed, end_packed)
650052
def uuid4(self, cast_to=str):
        
        # Based on http://stackoverflow.com/q/41186818
        return cast_to(uuid.UUID(int=self.generator.random.getrandbits(128), version=4))
951026
def ipv6(self, network=False):
        """"""
        address = str(ip_address(self.generator.random.randint(
            2 ** IPV4LENGTH, (2 ** IPV6LENGTH) - 1)))
        if network:
            address += '/' + str(self.generator.random.randint(0, IPV6LENGTH))
            address = str(ip_network(address, strict=False))
        return address
37248
def parse_cidr(value):
    """"""
    klass = IPv4Network
    if '/' not in value:
        klass = ipaddress.ip_address
    try:
        v = klass(six.text_type(value))
    except (ipaddress.AddressValueError, ValueError):
        v = None
    return v
536294
def get_random_service(
        service_registry: ServiceRegistry,
        block_identifier: BlockSpecification,
) -> Tuple[Optional[str], Optional[str]]:
    
    count = service_registry.service_count(block_identifier=block_identifier)
    if count == 0:
        return None, None
    index = random.SystemRandom().randint(0, count - 1)
    address = service_registry.get_service_address(
        block_identifier=block_identifier,
        index=index,
    )
    # We are using the same blockhash for both blockchain queries so the address
    # should exist for this query. Additionally at the moment there is no way for
    # services to be removed from the registry.
    assert address, 'address should exist for this index'
    url = service_registry.get_service_url(
        block_identifier=block_identifier,
        service_hex_address=address,
    )
    return url, address
695910
def cidr_to_netmask(cidr_range)
      cidr = IP::CIDR.new(cidr_range)
      return cidr.ip.ip_address, cidr.long_netmask.ip_address
    end
261793
def maybe_ip_addr(addr):
    

    if six.PY2 and isinstance(addr, str):
        addr = unicode(addr)  # noqa
    try:
        return ipaddress.ip_address(addr)
    except ValueError:
        pass
    return str(addr)
453675
def get_ip4():
    
    addresses = []

    shell_cmd = "ifconfig | awk '/inet addr/{print substr($2,6)}'"
    proc = subprocess.Popen([shell_cmd], stdout=subprocess.PIPE, shell=True)
    (out, err) = proc.communicate()
    ip_addresses = out.split('\n')
    for addr in ip_addresses:
        if re.match(r'\d{1,4}\.\d{1,4}\.\d{1,4}\.\d{1,4}', addr):
             addresses.append(addr)
    return addresses
786351
def cidr_netmask(cidr):
    '''
    
    '''
    ips = netaddr.IPNetwork(cidr)
    return six.text_type(ips.netmask)
226480
def delete_ip4(self, id_ip):
        

        if not is_valid_int_param(id_ip):
            raise InvalidParameterError(u'Ipv4 identifier is invalid or was not informed.')

        url = 'ip4/delete/' + str(id_ip) + "/"
        code, xml = self.submit(None, 'DELETE', url)

        return self.response(code, xml)
524042
def natural_ipv4_netmask(ip, fmt='prefixlen'):
    '''
    
    '''
    bits = _ipv4_to_bits(ip)

    if bits.startswith('11'):
        mask = '24'
    elif bits.startswith('1'):
        mask = '16'
    else:
        mask = '8'

    if fmt == 'netmask':
        return cidr_to_ipv4_netmask(mask)
    else:
        return '/' + mask
786832
def _parse_addr(self, addr): 
        '''  '''
        ipv = 0
        try:
            socket.inet_pton(socket.AF_INET6, addr)
            # Convert ::FFFF:x.y.z.y to IPv4
            if addr.lower().startswith('::ffff:'):
                try:
                    socket.inet_pton(socket.AF_INET, addr)
                    ipv = 4
                except:
                    ipv = 6
            else:
                ipv = 6
        except:
            socket.inet_pton(socket.AF_INET, addr)
            ipv = 4
        return ipv
510654
def _interfaces_ip(out):
    
    ret = dict()

    def parse_network(value, cols):
        """
        Return a tuple of ip, netmask, broadcast
        based on the current set of cols
        """
        brd = None
        if '/' in value:  # we have a CIDR in this address
            ip, cidr = value.split('/')  # pylint: disable=C0103
        else:
            ip = value  # pylint: disable=C0103
            cidr = 32

        if type_ == 'inet':
            mask = cidr_to_ipv4_netmask(int(cidr))
            if 'brd' in cols:
                brd = cols[cols.index('brd') + 1]
        elif type_ == 'inet6':
            mask = cidr
        return (ip, mask, brd)

    groups = re.compile('\r?\n\\d').split(out)
    for group in groups:
        iface = None
        data = dict()

        for line in group.splitlines():
            if ' ' not in line:
                continue
            match = re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+<(.+)>', line)
            if match:
                iface, parent, attrs = match.groups()
                if 'UP' in attrs.split(','):
                    data['up'] = True
                else:
                    data['up'] = False
                if parent:
                    data['parent'] = parent
                continue

            cols = line.split()
            if len(cols) >= 2:
                type_, value = tuple(cols[0:2])
                iflabel = cols[-1:][0]
                if type_ in ('inet', 'inet6'):
                    if 'secondary' not in cols:
                        ipaddr, netmask, broadcast = parse_network(value, cols)
                        if type_ == 'inet':
                            if 'inet' not in data:
                                data['inet'] = list()
                            addr_obj = dict()
                            addr_obj['address'] = ipaddr
                            addr_obj['netmask'] = netmask
                            addr_obj['broadcast'] = broadcast
                            addr_obj['label'] = iflabel
                            data['inet'].append(addr_obj)
                        elif type_ == 'inet6':
                            if 'inet6' not in data:
                                data['inet6'] = list()
                            addr_obj = dict()
                            addr_obj['address'] = ipaddr
                            addr_obj['prefixlen'] = netmask
                            data['inet6'].append(addr_obj)
                    else:
                        if 'secondary' not in data:
                            data['secondary'] = list()
                        ip_, mask, brd = parse_network(value, cols)
                        data['secondary'].append({
                            'type': type_,
                            'address': ip_,
                            'netmask': mask,
                            'broadcast': brd,
                            'label': iflabel,
                        })
                        del ip_, mask, brd
                elif type_.startswith('link'):
                    data['hwaddr'] = value
        if iface:
            ret[iface] = data
            del iface, data
    return ret
313682
def in_subnet(cidr, addr=None):
    '''
    
    '''
    try:
        cidr = ipaddress.ip_network(cidr)
    except ValueError:
        log.error('Invalid CIDR \'%s\'', cidr)
        return False

    if addr is None:
        addr = ip_addrs()
        addr.extend(ip_addrs6())
    elif not isinstance(addr, (list, tuple)):
        addr = (addr,)

    return any(ipaddress.ip_address(item) in cidr for item in addr)