Create one or more CIDR source restriction policies.

		Include a list of CIDR strings.

		>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0]
				.AddSourceRestrictions(cidrs=["132.200.20.1/32","132.200.20.100/32"]).WaitUntilComplete()
		0
979088
def AddSourceRestrictions(self,cidrs):
		

		for cidr in cidrs:  self.source_restrictions.append(SourceRestriction(self,cidr))

		return(self.Update())
550754
def put_cidr_name(aws_config, current_config, path, current_path, resource_id, callback_args):
    
    if 'cidrs' in current_config:
        cidr_list = []
        for cidr in current_config['cidrs']:
            if type(cidr) == dict:
                cidr = cidr['CIDR']
            if cidr in known_cidrs:
                cidr_name = known_cidrs[cidr]
            else:
                cidr_name = get_cidr_name(cidr, callback_args['ip_ranges'], callback_args['ip_ranges_name_key'])
                known_cidrs[cidr] = cidr_name
            cidr_list.append({'CIDR': cidr, 'CIDRName': cidr_name})
        current_config['cidrs'] = cidr_list
706102
public void setCidrAllowedList(java.util.Collection<String> cidrAllowedList) {
        if (cidrAllowedList == null) {
            this.cidrAllowedList = null;
            return;
        }

        this.cidrAllowedList = new java.util.ArrayList<String>(cidrAllowedList);
    }
555572
def add_source(zone, source, permanent=True):
    '''
    
    '''
    if source in get_sources(zone, permanent):
        log.info('Source is already bound to zone.')

    cmd = '--zone={0} --add-source={1}'.format(zone, source)

    if permanent:
        cmd += ' --permanent'

    return __firewall_cmd(cmd)
155966
public void setCidrs(java.util.Collection<String> cidrs) {
        if (cidrs == null) {
            this.cidrs = null;
            return;
        }

        this.cidrs = new com.amazonaws.internal.SdkInternalList<String>(cidrs);
    }
896444
public void setNetworkSourceIpV4(java.util.Collection<IpFilter> networkSourceIpV4) {
        if (networkSourceIpV4 == null) {
            this.networkSourceIpV4 = null;
            return;
        }

        this.networkSourceIpV4 = new java.util.ArrayList<IpFilter>(networkSourceIpV4);
    }
697577
public static function ipCidrCheck($p_ip, $p_cidr)
    {
        if (strpos($p_cidr, '/') !== false) {
            list ($net, $mask) = split("/", $p_cidr);
            $ip_net            = ip2long($net);
            $ip_mask           = ~((1 << (32 - $mask)) - 1);
            $ip_ip             = ip2long($p_ip);
            $ip_ip_net         = $ip_ip & $ip_mask;
            
            return ($ip_ip_net == $ip_net);
        } else {
            return (ip2long($p_ip) == ip2long($p_cidr));
        }
    }
881702
static Policy setIamPolicySource(SourceName sourceName, String userEmail) {
    try (SecurityCenterClient client = SecurityCenterClient.create()) {
      // userEmail = "someuser@domain.com"
      // Set up IAM Policy for the user userMail to use the role findingsEditor.
      // The user must be a valid google account.
      Policy oldPolicy = client.getIamPolicy(sourceName.toString());
      Binding bindings =
          Binding.newBuilder()
              .setRole("roles/securitycenter.findingsEditor")
              .addMembers("user:" + userEmail)
              .build();
      Policy policy = oldPolicy.toBuilder().addBindings(bindings).build();

      // Start setting up a request to set IAM policy for a source.
      // SourceName sourceName = SourceName.of("123234324", "423432321");
      SetIamPolicyRequest.Builder request =
          SetIamPolicyRequest.newBuilder().setPolicy(policy).setResource(sourceName.toString());

      // Call the API.
      Policy response = client.setIamPolicy(request.build());

      System.out.println("Policy: " + response);
      return response;
    } catch (IOException e) {
      throw new RuntimeException("Couldn't create client.", e);
    }
  }
57404
def update_iptables(self):
        """"""

        # Read the iptables
        iptables_cmds = ['iptables-save', '-c']
        all_rules = dsl.execute(iptables_cmds, root_helper=self._root_helper,
                                log_output=False)

        # For each rule in rule_info update the rule if necessary.
        new_rules = []
        is_modified = False
        for line in all_rules.split('\n'):
            new_line = line
            line_content = line.split()
            # The spoofing rule which includes mac and ip should have
            # -s cidr/32  option for ip address. Otherwise no rule
            # will be modified.
            if '-s' in line_content:
                tmp_rule_info = list(self.rule_info)
                for rule in tmp_rule_info:
                    if (rule.mac in line.lower() and
                        rule.chain.lower() in line.lower() and
                            not self._is_ip_in_rule(rule.ip, line_content)):
                        ip_loc = line_content.index('-s') + 1
                        line_content[ip_loc] = rule.ip + '/32'
                        new_line = ' '.join(line_content)
                        LOG.debug('Modified %(old_rule)s. '
                                  'New rule is %(new_rule)s.' % (
                                      {'old_rule': line,
                                       'new_rule': new_line}))
                        is_modified = True
            new_rules.append(new_line)

        if is_modified and new_rules:
            # Updated all the rules. Now commit the new rules.
            iptables_cmds = ['iptables-restore', '-c']
            dsl.execute(iptables_cmds, process_input='\n'.join(new_rules),
                        root_helper=self._root_helper, log_output=False)
1359234
public OperationFuture<List<Server>> addPublicIp(ServerFilter serverFilter,  CreatePublicIpConfig publicIpConfig) {
        return addPublicIp(Arrays.asList(getRefsFromFilter(serverFilter)), publicIpConfig);
    }
846391
def restrict(self, addr):
        

        # Remove the address from the set
        ip_addr = _parse_ip(addr)
        if ip_addr is None:
            LOG.warn("Cannot restrict address %r from proxy %s: "
                     "invalid address" % (addr, self.address))
        else:
            self.excluded.add(addr)
977330
def add_access_control_headers(self, env=None):
        
        allowed_methods = 'GET, POST, PUT, OPTIONS, DELETE, PATCH, HEAD, TRACE, CONNECT'
        allowed_origin = None
        if env is not None:
            acr_method = env.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
            if acr_method is not None and acr_method not in allowed_methods:
                allowed_methods = allowed_methods + ', ' + acr_method
            r_method = env.get('REQUEST_METHOD')
            if r_method is not None and r_method not in allowed_methods:
                allowed_methods = allowed_methods + ', ' + r_method
            acr_headers = env.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS')
            if acr_headers is not None:
                self.status_headers.add_header('Access-Control-Allow-Headers', acr_headers)
            allowed_origin = env.get('HTTP_ORIGIN', env.get('HTTP_REFERER', allowed_origin))
        if allowed_origin is None:
            allowed_origin = '*'
        self.status_headers.replace_header('Access-Control-Allow-Origin',  allowed_origin)
        self.status_headers.add_header('Access-Control-Allow-Methods', allowed_methods)
        self.status_headers.add_header('Access-Control-Allow-Credentials', 'true')
        self.status_headers.add_header('Access-Control-Max-Age', '1800')
        return self
656116
def ifacestartswith(cidr):
    '''
    
    '''
    net_list = interfaces()
    intfnames = []
    pattern = six.text_type(cidr)
    size = len(pattern)
    for ifname, ifval in six.iteritems(net_list):
        if 'inet' in ifval:
            for inet in ifval['inet']:
                if inet['address'][0:size] == pattern:
                    if 'label' in inet:
                        intfnames.append(inet['label'])
                    else:
                        intfnames.append(ifname)
    return intfnames
1304355
def _access_rule(method,
                ip=None,
                port=None,
                proto='tcp',
                direction='in',
                port_origin='d',
                ip_origin='d',
                comment=''):
    '''
    
    '''
    if _status_csf():
        if ip is None:
            return {'error': 'You must supply an ip address or CIDR.'}
        if port is None:
            args = _build_args(method, ip, comment)
            return __csf_cmd(args)
        else:
            if method not in ['allow', 'deny']:
                return {'error': 'Only allow and deny rules are allowed when specifying a port.'}
            return _access_rule_with_port(method=method,
                                            ip=ip,
                                            port=port,
                                            proto=proto,
                                            direction=direction,
                                            port_origin=port_origin,
                                            ip_origin=ip_origin,
                                            comment=comment)
1014765
def _update_cidr(self, cidr):
        
        new_ip_ranges = []
        is_bulk_create_supported = hasattr(IpRange.objects, 'bulk_create')
        IpRange.objects.all().delete()
        city_region_mapping = self._build_city_region_mapping()

        if self.logger.getEffectiveLevel() in [logging.INFO, logging.DEBUG]:
            pbar = ProgressBar(widgets=[Percentage(), ' ', Bar()])
        else:
            pbar = iter
        for entry in pbar(cidr['cidr']):
            # skipping for country rows
            if entry['city_id']:
                entry.update({'region_id': city_region_mapping[int(entry['city_id'])]})
            if is_bulk_create_supported:
                new_ip_ranges.append(IpRange(**entry))

                if len(new_ip_ranges) >= self.BULK_CHAIN:
                    IpRange.objects.bulk_create(new_ip_ranges)
                    new_ip_ranges = []
            else:
                IpRange.objects.create(**entry)

        if is_bulk_create_supported and new_ip_ranges:
            IpRange.objects.bulk_create(new_ip_ranges)
510081
def allow_ip(*ips: typing.Union[str, ipaddress.IPv4Network, ipaddress.IPv4Address]):
    
    for ip in ips:
        if isinstance(ip, ipaddress.IPv4Address):
            allowed_ips.add(ip)
        elif isinstance(ip, str):
            allowed_ips.add(ipaddress.IPv4Address(ip))
        elif isinstance(ip, ipaddress.IPv4Network):
            allowed_ips.update(ip.hosts())
        else:
            raise ValueError(f"Bad type of ipaddress: {type(ip)} ('{ip}')")
623145
private CreateSubnetResponseType createSubnet(final String vpcId, final String cidrBlock) {
        CreateSubnetResponseType ret = new CreateSubnetResponseType();
        ret.setRequestId(UUID.randomUUID().toString());
        MockSubnet mockSubnet = mockSubnetController.createSubnet(cidrBlock, vpcId);

        SubnetType subnetType = new SubnetType();
        subnetType.setVpcId(mockSubnet.getVpcId());
        subnetType.setSubnetId(mockSubnet.getSubnetId());

        ret.setSubnet(subnetType);
        return ret;
    }