Example usage for org.apache.commons.net.util SubnetUtils setInclusiveHostCount

List of usage examples for org.apache.commons.net.util SubnetUtils setInclusiveHostCount

Introduction

In this page you can find the example usage for org.apache.commons.net.util SubnetUtils setInclusiveHostCount.

Prototype

public void setInclusiveHostCount(boolean inclusiveHostCount) 

Source Link

Document

Set to true if you want the return value of SubnetInfo#getAddressCount() to include the network and broadcast addresses.

Usage

From source file:com.cloud.utils.net.NetUtils.java

public static boolean isIpWithtInCidrRange(final String ipAddress, final String cidr) {
    if (!isValidIp(ipAddress)) {
        return false;
    }//ww w  .j  av  a2s.  c o m
    if (!isValidCIDR(cidr)) {
        return false;
    }

    // check if the gatewayip is the part of the ip range being added.
    // RFC 3021 - 31-Bit Prefixes on IPv4 Point-to-Point Links
    //     GW              Netmask         Stat IP        End IP
    // 192.168.24.0 - 255.255.255.254 - 192.168.24.0 - 192.168.24.1
    // https://tools.ietf.org/html/rfc3021
    // Added by Wilder Rodrigues
    final SubnetUtils subnetUtils = new SubnetUtils(cidr);
    subnetUtils.setInclusiveHostCount(true);

    final boolean isInRange = subnetUtils.getInfo().isInRange(ipAddress);

    return isInRange;
}

From source file:org.apache.hadoop.util.MachineList.java

/**
 * Accepts a collection of ip/cidr/host addresses
 * // w  w w.  j a va  2s .  c  o  m
 * @param hostEntries
 * @param addressFactory addressFactory to convert host to InetAddress
 */
public MachineList(Collection<String> hostEntries, InetAddressFactory addressFactory) {
    this.addressFactory = addressFactory;
    if (hostEntries != null) {
        if ((hostEntries.size() == 1) && (hostEntries.contains(WILDCARD_VALUE))) {
            all = true;
            ipAddresses = null;
            hostNames = null;
            cidrAddresses = null;
        } else {
            all = false;
            Set<String> ips = new HashSet<String>();
            List<SubnetUtils.SubnetInfo> cidrs = new LinkedList<SubnetUtils.SubnetInfo>();
            Set<String> hosts = new HashSet<String>();
            for (String hostEntry : hostEntries) {
                //ip address range
                if (hostEntry.indexOf("/") > -1) {
                    try {
                        SubnetUtils subnet = new SubnetUtils(hostEntry);
                        subnet.setInclusiveHostCount(true);
                        cidrs.add(subnet.getInfo());
                    } catch (IllegalArgumentException e) {
                        LOG.warn("Invalid CIDR syntax : " + hostEntry);
                        throw e;
                    }
                } else if (InetAddresses.isInetAddress(hostEntry)) { //ip address
                    ips.add(hostEntry);
                } else { //hostname
                    hosts.add(hostEntry);
                }
            }
            ipAddresses = (ips.size() > 0) ? ips : null;
            cidrAddresses = (cidrs.size() > 0) ? cidrs : null;
            hostNames = (hosts.size() > 0) ? hosts : null;
        }
    } else {
        all = false;
        ipAddresses = null;
        hostNames = null;
        cidrAddresses = null;
    }
}

From source file:org.apache.nifi.cluster.firewall.impl.FileBasedClusterNodeFirewall.java

private void parseConfig(final File config) throws IOException {

    // clear old information
    subnetInfos.clear();/*  www  .  j ava  2 s.  co m*/
    try (BufferedReader br = new BufferedReader(new FileReader(config))) {

        String ipOrHostLine;
        String ipCidr;
        int totalIpsAdded = 0;
        while ((ipOrHostLine = br.readLine()) != null) {

            // cleanup whitespace
            ipOrHostLine = ipOrHostLine.trim();

            if (ipOrHostLine.isEmpty() || ipOrHostLine.startsWith("#")) {
                // skip empty lines or comments
                continue;
            } else if (ipOrHostLine.contains("#")) {
                // parse out comments in IP containing lines
                ipOrHostLine = ipOrHostLine.substring(0, ipOrHostLine.indexOf("#")).trim();
            }

            // if given a complete IP, then covert to CIDR
            if (ipOrHostLine.contains("/")) {
                ipCidr = ipOrHostLine;
            } else if (ipOrHostLine.contains("\\")) {
                logger.warn(
                        "CIDR IP notation uses forward slashes '/'.  Replacing backslash '\\' with forward slash'/' for '{}'",
                        ipOrHostLine);
                ipCidr = ipOrHostLine.replace("\\", "/");
            } else {
                try {
                    ipCidr = InetAddress.getByName(ipOrHostLine).getHostAddress();
                    if (!ipOrHostLine.equals(ipCidr)) {
                        logger.debug("Resolved host '{}' to ip '{}'", ipOrHostLine, ipCidr);
                    }
                    ipCidr += "/32";
                    logger.debug("Adding CIDR to exact IP: '{}'", ipCidr);
                } catch (final UnknownHostException uhe) {
                    logger.warn("Firewall is skipping unknown host address: '{}'", ipOrHostLine);
                    continue;
                }
            }

            try {
                logger.debug("Adding CIDR IP to firewall: '{}'", ipCidr);
                final SubnetUtils subnetUtils = new SubnetUtils(ipCidr);
                subnetUtils.setInclusiveHostCount(true);
                subnetInfos.add(subnetUtils.getInfo());
                totalIpsAdded++;
            } catch (final IllegalArgumentException iae) {
                logger.warn("Firewall is skipping invalid CIDR address: '{}'", ipOrHostLine);
            }

        }

        if (totalIpsAdded == 0) {
            logger.info("No IPs added to firewall.  Firewall will accept all requests.");
        } else {
            logger.info(
                    "Added {} IP(s) to firewall.  Only requests originating from the configured IPs will be accepted.",
                    totalIpsAdded);
        }

    }
}

From source file:org.openbmp.db_rest.resources.Orr.java

/**
 * Lookup the IGP metric for the prefix (e.g. next hop) passed
 *
 * @param prefix            IP in print form (this is the next-hop)
 * @param igpMap            IGP RIB map/*from   w ww.  ja  v a2  s .  c  om*/
 *
 * @return null if no match, otherwise the column def list that matches is returned
 */
List<DbColumnDef> getIgpPrefixMetric(String prefix, Map<String, List<DbColumnDef>> igpMap) {
    List<DbColumnDef> found_cols = null;

    System.out.println("Lookup IGP metric cost for prefix " + prefix);

    for (Map.Entry<String, List<DbColumnDef>> row : igpMap.entrySet()) {
        // Prefix,PrefixLen,LocalPref,ASPath_Count,Origin,MED,NH
        List<DbColumnDef> cols = row.getValue();

        SubnetUtils subU = new SubnetUtils(cols.get(0).getValue() + '/' + cols.get(1).getValue());
        subU.setInclusiveHostCount(true);

        if (subU.getInfo().isInRange(prefix)) {
            System.out.println("    Found matching prefix, metric is " + cols.get(6).getValue());
            found_cols = cols;
            break;
        }
    }

    return found_cols;
}

From source file:org.ow2.sirocco.cloudmanager.connector.vcd.VcdCloudProvider.java

private void fromVappNetworkToNetwork(final VappNetwork vappNetwork, final Network n) {
    ReferenceType vappNetworkReferenceType = vappNetwork.getReference();
    n.setName(vappNetworkReferenceType.getName());
    n.setProviderAssignedId(vappNetworkReferenceType.getHref());
    n.setState(Network.State.STARTED);

    // Mapping Rule
    /* If the vAppNetwork is not isolated and its name = the CIMI public network configuration parameter 
     * then the CIMI network is set to PUBLIC else to PRIVATE */
    /* Applying this rule with a vApp created outside Sirocco might not work properly ! 
     * A workaround in this case is to use the OrgVdcNetwork to which the vAppNetwork is connected */
    /*if (!vappNetwork.getResource().getConfiguration().getFenceMode().equals(FenceModeValuesType.ISOLATED.value())
    && vappNetworkReferenceType.getName().equals(this.vCloudContext.getCimiPublicOrgVdcNetworkName())) {
    n.setNetworkType(Network.Type.PUBLIC);
    } else {//from  w w  w .  ja  v  a 2s  .c  om
    n.setNetworkType(Network.Type.PRIVATE);
    }*/

    // subnet
    List<Subnet> subnets = new ArrayList<Subnet>();
    n.setSubnets(subnets);
    /*SubnetUtils utils = new SubnetUtils(vappNetwork.getResource().getConfiguration().getIpScope().getGateway(), vappNetwork
    .getResource().getConfiguration().getIpScope().getNetmask());*/
    SubnetUtils utils = new SubnetUtils(
            vappNetwork.getResource().getConfiguration().getIpScopes().getIpScope().get(0).getGateway(),
            vappNetwork.getResource().getConfiguration().getIpScopes().getIpScope().get(0).getNetmask());
    utils = new SubnetUtils(utils.getInfo().getNetworkAddress(), utils.getInfo().getNetmask());
    utils.setInclusiveHostCount(false);
    SubnetInfo info = utils.getInfo();
    Subnet subnet = new Subnet();
    subnet.setCidr(info.getCidrSignature());
    // subnet.setName(????);
    // subnet.setEnableDhcp(???);
    // subnet.setProviderAssignedId(???);
    subnet.setState(Subnet.State.AVAILABLE);
    subnet.setProtocol("IPv4");
    subnets.add(subnet);
}

From source file:org.ow2.sirocco.cloudmanager.connector.vcd.VcdCloudProvider.java

private void fromOrgVdcNetworkToNetwork(final OrgVdcNetwork orgVdcNetwork, final Network n) {
    ReferenceType orgVdcNetworkReferenceType = orgVdcNetwork.getReference();
    n.setName(orgVdcNetworkReferenceType.getName());
    n.setProviderAssignedId(orgVdcNetworkReferenceType.getHref());
    n.setState(Network.State.STARTED);

    // Mapping Rule
    /* If the orgVdcNetwork name = the CIMI public network configuration parameter 
     * then the CIMI network is set to PUBLIC else to PRIVATE */
    /*if (orgVdcNetworkReferenceType.getName().equals(this.vCloudContext.getCimiPublicOrgVdcNetworkName())) {
    n.setNetworkType(Network.Type.PUBLIC);
    } else {//from  w  ww  . j a  va2s.c  o m
    n.setNetworkType(Network.Type.PRIVATE);
    }*/

    // subnet
    List<Subnet> subnets = new ArrayList<Subnet>();
    n.setSubnets(subnets);
    /*SubnetUtils utils = new SubnetUtils(orgVdcNetwork.getResource().getConfiguration().getIpScope().getGateway(), orgVdcNetwork
    .getResource().getConfiguration().getIpScope().getNetmask());*/
    SubnetUtils utils = new SubnetUtils(
            orgVdcNetwork.getResource().getConfiguration().getIpScopes().getIpScope().get(0).getGateway(),
            orgVdcNetwork.getResource().getConfiguration().getIpScopes().getIpScope().get(0).getNetmask());
    utils = new SubnetUtils(utils.getInfo().getNetworkAddress(), utils.getInfo().getNetmask());
    utils.setInclusiveHostCount(false);
    SubnetInfo info = utils.getInfo();
    Subnet subnet = new Subnet();
    subnet.setCidr(info.getCidrSignature());
    // subnet.setName(????);
    // subnet.setEnableDhcp(???);
    // subnet.setProviderAssignedId(???);
    subnet.setState(Subnet.State.AVAILABLE);
    subnet.setProtocol("IPv4");
    subnets.add(subnet);
}

From source file:org.ow2.sirocco.cloudmanager.connector.vcd.VcdCloudProvider.java

VAppNetworkConfigurationType createIsolatedVAppNetworkConfigurationType(final String networkName,
        final NetworkConfiguration networkConfiguration) throws ConnectorException {
    VAppNetworkConfigurationType private_vAppNetworkConfigurationType = new VAppNetworkConfigurationType();
    NetworkConfigurationType private_networkConfigurationType = new NetworkConfigurationType();
    VcdCloudProvider.logger.info("vAppNetworkConfiguration Isolated:" + networkName);
    private_vAppNetworkConfigurationType.setNetworkName(networkName);
    // private_networkConfigurationType.setParentNetwork(vdc.getAvailableNetworkRefByName(this.cimiPublicOrgVdcNetworkName));
    private_networkConfigurationType.setFenceMode(FenceModeValuesType.ISOLATED.value());
    private_networkConfigurationType.setRetainNetInfoAcrossDeployments(true);

    // Configure Internal IP Settings
    if (networkConfiguration.getSubnets().size() != 1) {
        throw new ConnectorException(
                "validation error on field 'networkConfiguration.subnets.size': should be equal to 1");
    }//from www.j  a v a  2s. c  o  m
    SubnetUtils utils = new SubnetUtils(networkConfiguration.getSubnets().get(0).getCidr());
    utils.setInclusiveHostCount(false);
    SubnetInfo info = utils.getInfo();
    if (info.getAddressCount() < 2) { /* gateway @ + IP range @ >= 2 */
        throw new ConnectorException("no usable addresses");
    }

    IpScopeType ipScope = new IpScopeType();
    /*ipScope.setNetmask("255.255.255.0");
    ipScope.setGateway("192.168.2.1");*/
    ipScope.setNetmask(info.getNetmask());
    ipScope.setGateway(info.getLowAddress());
    ipScope.setIsEnabled(true);
    ipScope.setIsInherited(false); // ???

    IpRangesType ipRangesType = new IpRangesType();
    IpRangeType ipRangeType = new IpRangeType();
    /*ipRangeType.setStartAddress("192.168.2.100");
    ipRangeType.setEndAddress("192.168.2.199");*/
    ipRangeType.setStartAddress(info.getAllAddresses()[1]);
    ipRangeType.setEndAddress(info.getHighAddress());

    ipRangesType.getIpRange().add(ipRangeType);

    ipScope.setIpRanges(ipRangesType);
    ipScope.setIsEnabled(true);
    IpScopesType ipScopes = new IpScopesType();
    ipScopes.getIpScope().add(ipScope);
    private_networkConfigurationType.setIpScopes(ipScopes);

    private_vAppNetworkConfigurationType.setConfiguration(private_networkConfigurationType);
    return private_vAppNetworkConfigurationType;
}

From source file:org.wikimedia.analytics.kraken.pageview.CidrFilter.java

/**
 *
 * @param subnetInput a comma separated list of subnets using the CIDR notation.
 *//*from   ww  w. j a va2  s  .  co m*/
public CidrFilter(final String subnetInput) {
    for (String subnet : subnetInput.split(",")) {
        SubnetUtils subnetUtil = new SubnetUtils(subnet);
        subnetUtil.setInclusiveHostCount(true);
        this.subnets.add(subnetUtil);
    }
}