Create network address in CIDR format.

    Return network address for a given gateway address and netmask.
424020
def make_cidr(gw, mask):
    
    try:
        int_mask = (0xFFFFFFFF << (32 - int(mask))) & 0xFFFFFFFF
        gw_addr_int = struct.unpack('>L', socket.inet_aton(gw))[0] & int_mask
        return (socket.inet_ntoa(struct.pack("!I", gw_addr_int)) +
                '/' + str(mask))
    except (socket.error, struct.error, ValueError, TypeError):
        return
76554
function buildNetworkAclEntry(
  name,
  CidrBlock,
  { Egress = false, Protocol = -1, RuleAction = 'allow', RuleNumber = 100 } = {},
) {
  const direction = Egress ? 'Egress' : 'Ingress';
  const cfName = `${name}${direction}${RuleNumber}`;
  return {
    [cfName]: {
      Type: 'AWS::EC2::NetworkAclEntry',
      Properties: {
        CidrBlock,
        NetworkAclId: {
          Ref: name,
        },
        Egress,
        Protocol,
        RuleAction,
        RuleNumber,
      },
    },
  };
}
581954
def new_address(self, prefix, type, callback=None, errback=None, **kwargs):
        
        if not self.data:
            raise NetworkException('Network not loaded')

        return Address(self.config, prefix, type, self).create(**kwargs)
533948
def create(gandi, resource, flags, algorithm, public_key):
    """"""

    result = gandi.dnssec.create(resource, flags, algorithm, public_key)

    return result
184350
def create_network_interface(name, subnet_id=None, subnet_name=None,
                             private_ip_address=None, description=None,
                             groups=None, region=None, key=None, keyid=None,
                             profile=None):
    '''
    
    '''
    if not salt.utils.data.exactly_one((subnet_id, subnet_name)):
        raise SaltInvocationError('One (but not both) of subnet_id or '
                                  'subnet_name must be provided.')

    if subnet_name:
        resource = __salt__['boto_vpc.get_resource_id']('subnet', subnet_name,
                                                        region=region, key=key,
                                                        keyid=keyid,
                                                        profile=profile)
        if 'id' not in resource:
            log.warning('Couldn\'t resolve subnet name %s.', subnet_name)
            return False
        subnet_id = resource['id']

    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    r = {}
    result = _get_network_interface(conn, name)
    if 'result' in result:
        r['error'] = {'message': 'An ENI with this Name tag already exists.'}
        return r
    vpc_id = __salt__['boto_vpc.get_subnet_association'](
        [subnet_id], region=region, key=key, keyid=keyid, profile=profile
    )
    vpc_id = vpc_id.get('vpc_id')
    if not vpc_id:
        msg = 'subnet_id {0} does not map to a valid vpc id.'.format(subnet_id)
        r['error'] = {'message': msg}
        return r
    _groups = __salt__['boto_secgroup.convert_to_group_ids'](
        groups, vpc_id=vpc_id, region=region, key=key,
        keyid=keyid, profile=profile
    )
    try:
        eni = conn.create_network_interface(
            subnet_id,
            private_ip_address=private_ip_address,
            description=description,
            groups=_groups
        )
        eni.add_tag('Name', name)
    except boto.exception.EC2ResponseError as e:
        r['error'] = __utils__['boto.get_error'](e)
        return r
    r['result'] = _describe_network_interface(eni)
    return r
993353
def cidr_to_ipv4_netmask(cidr_bits):
    '''
    
    '''
    try:
        cidr_bits = int(cidr_bits)
        if not 1 <= cidr_bits <= 32:
            return ''
    except ValueError:
        return ''

    netmask = ''
    for idx in range(4):
        if idx:
            netmask += '.'
        if cidr_bits >= 8:
            netmask += '255'
            cidr_bits -= 8
        else:
            netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits)))
            cidr_bits = 0
    return netmask
150191
def cidr=(newval)
      new_end = IPAddr.new("#{@starting_address}/#{newval}").to_range.end.mask 32
      self.class.validate_ip_range(@starting_address, new_end)
      @ending_address = new_end
      @need_to_update = true
    end
487337
def create_network(self, name, tenant_id, subnet, gw=None):
        

        try:
            body = {'network': {'name': name, 'tenant_id': tenant_id,
                                'admin_state_up': True}}
            netw = self.neutronclient.create_network(body=body)
            net_dict = netw.get('network')
            net_id = net_dict.get('id')
        except Exception as exc:
            LOG.error("Failed to create network %(name)s, Exc %(exc)s",
                      {'name': name, 'exc': str(exc)})
            return None, None

        try:
            if gw is None:
                body = {'subnet': {'cidr': subnet,
                                   'ip_version': 4,
                                   'network_id': net_id,
                                   'tenant_id': tenant_id,
                                   'enable_dhcp': False}}
            else:
                body = {'subnet': {'cidr': subnet,
                                   'ip_version': 4,
                                   'network_id': net_id,
                                   'tenant_id': tenant_id,
                                   'enable_dhcp': False,
                                   'gateway_ip': gw}}
            subnet_ret = self.neutronclient.create_subnet(body=body)
            subnet_dict = subnet_ret.get('subnet')
            subnet_id = subnet_dict.get('id')
        except Exception as exc:
            LOG.error("Failed to create subnet %(sub)s, exc %(exc)s",
                      {'sub': subnet, 'exc': str(exc)})
            try:
                self.neutronclient.delete_network(net_id)
            except Exception as exc:
                LOG.error("Failed to delete network %(net)s, exc %(exc)s",
                          {'net': net_id, 'exc': str(exc)})
            return None, None
        return net_id, subnet_id
535817
def netmask6(scope = :global)
      if [:global, :link].include?(scope)
        @network_conf["mask6_#{scope}".to_sym] ||= IPAddr.new('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff').mask(prefix6(scope)).to_s if prefix6(scope)
      else
        raise ArgumentError, "Unrecognized address scope #{scope}"
      end
    end
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)
624199
def add_static_ip(n_ip=0)
      begin
        # required metadata values
        ipaddr = ENV["RS_IP#{n_ip}_ADDR"]
        netmask = ENV["RS_IP#{n_ip}_NETMASK"]
        # optional
        gateway = ENV["RS_IP#{n_ip}_GATEWAY"]
        device = shell_escape_if_necessary(device_name_from_mac(ENV["RS_IP#{n_ip}_MAC"]))

        if ipaddr
          # configure network adaptor
          attached_nameservers = nameservers_for_device(n_ip)

          logger.info "Setting up static IP address '#{ipaddr}' for '#{device}'"
          logger.debug "Netmask: '#{netmask}' ; Gateway: '#{gateway}'"
          logger.debug "Nameservers: '#{attached_nameservers.join(' ')}'" if attached_nameservers
          raise "FATAL: RS_IP#{n_ip}_NETMASK not defined ; Cannot configure static IP address" unless netmask

          ip = configure_network_adaptor(device, ipaddr, netmask, gateway, attached_nameservers)
        end
      rescue Exception => e
        logger.error "Detected an error while configuring static IP#{n_ip}: #{e.message}"
        raise e
      end
    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)
958423
def create_key(self):
        """"""
        print("Creating key. Please input the following options:")
        name = input("Key name (optional): ")
        print("To make this key more secure, you should restrict the IP addresses that can use it. ")
        print("To use with all IPs, leave blank or use 0.0.0.0/0.")
        print("To use with a single IP, append '/32', such as 207.39.29.22/32. ")
        print("See this reference on CIDR blocks: http://software77.net/cidr-101.html")
        cidr = input("CIDR (optional): ")
        key = self._curl_bitmex("/apiKey",
                                postdict={"name": name, "cidr": cidr, "enabled": True})

        print("Key created. Details:\n")
        print("API Key:    " + key["id"])
        print("Secret:     " + key["secret"])
        print("\nSafeguard your secret key! If somebody gets a hold of your API key and secret,")
        print("your account can be taken over completely.")
        print("\nKey generation complete.")
320308
def _split_optional_netmask(address):
    """"""
    addr = _compat_str(address).split('/')
    if len(addr) > 2:
        raise AddressValueError("Only one '/' permitted in %r" % address)
    return addr
653798
def _address_in_network(ip, netaddr, mask):
    
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netmask = struct.unpack('=L', socket.inet_aton(mask))[0]
    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask)
900393
def create(self, cidr_mask, description, **kwargs):
        
        return self._instance._client.acls.create(
            self._instance.name,
            cidr_mask,
            description,
            **kwargs
        )
497077
def _create_network_interface(
        self, ip_config_name, nic_name, public_ip, region,
        resource_group_name, subnet, accelerated_networking=False
    ):
        
        nic_config = {
            'location': region,
            'ip_configurations': [{
                'name': ip_config_name,
                'private_ip_allocation_method': 'Dynamic',
                'subnet': {
                    'id': subnet.id
                },
                'public_ip_address': {
                    'id': public_ip.id
                },
            }]
        }

        if accelerated_networking:
            nic_config['enable_accelerated_networking'] = True

        try:
            nic_setup = self.network.network_interfaces.create_or_update(
                resource_group_name, nic_name, nic_config
            )
        except Exception as error:
            raise AzureCloudException(
                'Unable to create network interface: {0}.'.format(
                    error
                )
            )

        return nic_setup.result()