Java Code Examples for org.apache.commons.net.util.SubnetUtils#setInclusiveHostCount()

The following examples show how to use org.apache.commons.net.util.SubnetUtils#setInclusiveHostCount() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NetUtils.java    From cosmic with Apache License 2.0 6 votes vote down vote up
public static boolean isIpWithtInCidrRange(final String ipAddress, final String cidr) {
    if (!isValidIp4(ipAddress)) {
        return false;
    }
    if (!isValidIp4Cidr(cidr)) {
        return false;
    }
    if (cidr.equals("0.0.0.0/0")) {
        return true;
    }

    // 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;
}
 
Example 2
Source File: L3NetworkApiInterceptor.java    From zstack with Apache License 2.0 6 votes vote down vote up
private void validate(APIAddIpRangeByNetworkCidrMsg msg) {
    try {
        SubnetUtils utils = new SubnetUtils(msg.getNetworkCidr());
        utils.setInclusiveHostCount(false);
        SubnetInfo subnet = utils.getInfo();
        if (subnet.getAddressCount() == 0) {
            throw new ApiMessageInterceptionException(argerr("%s is not an allowed network cidr, because it doesn't have usable ip range", msg.getNetworkCidr()));
        }

        if (msg.getGateway() != null && !(msg.getGateway().equals(subnet.getLowAddress()) || msg.getGateway().equals(subnet.getHighAddress()))) {
            throw new ApiMessageInterceptionException(argerr("%s is not the first or last address of the cidr %s", msg.getGateway(), msg.getNetworkCidr()));
        }
    } catch (IllegalArgumentException e) {
        throw new ApiMessageInterceptionException(argerr("%s is not a valid network cidr", msg.getNetworkCidr()));
    }

    if (msg.getIpRangeType() == null) {
        msg.setIpRangeType(IpRangeType.Normal.toString());
    }

    IpRangeInventory ipr = IpRangeInventory.fromMessage(msg);
    validate(ipr);
}
 
Example 3
Source File: K8sNetworkingUtil.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Obtains valid IP addresses of the given subnet.
 *
 * @param cidr CIDR
 * @return set of IP addresses
 */
public static Set<IpAddress> getSubnetIps(String cidr) {
    SubnetUtils utils = new SubnetUtils(cidr);
    utils.setInclusiveHostCount(false);
    SubnetUtils.SubnetInfo info = utils.getInfo();
    Set<String> allAddresses =
            new HashSet<>(Arrays.asList(info.getAllAddresses()));

    if (allAddresses.size() > 2) {
        allAddresses.remove(info.getLowAddress());
        allAddresses.remove(info.getHighAddress());
    }

    return allAddresses.stream()
            .map(IpAddress::valueOf).collect(Collectors.toSet());
}
 
Example 4
Source File: NetUtils.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static boolean isIpWithInCidrRange(final String ipAddress, final String cidr) {
    if (!isValidIp4(ipAddress)) {
        return false;
    }
    if (!isValidIp4Cidr(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;
}
 
Example 5
Source File: IpsInterceptorService.java    From heimdall with Apache License 2.0 5 votes vote down vote up
/**
 * Check if ip is present inside CIDR Range, network and broadcast addresses are to be included.
 * @param cidr
 * @param ip
 * @return
 */
private boolean isInterDomainRouting(String cidr, String ip) {
   	SubnetUtils subnet = new SubnetUtils(cidr);
	subnet.setInclusiveHostCount(true);
	
	return subnet.getInfo().isInRange(ip);
   }
 
Example 6
Source File: NetUtils.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public static String getCidrHostAddress(final String cidr) {
    final String[] cidrPair = cidr.split("\\/");
    final String address = cidrPair[0];
    final SubnetUtils subnetUtils = new SubnetUtils(cidr);
    subnetUtils.setInclusiveHostCount(false);

    if (isValidIp4(address) && subnetUtils.getInfo().isInRange(address)) {
        return address;
    }

    return null;
}
 
Example 7
Source File: NetUtils.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public static boolean isNetworkorBroadcastIP(final String ip, final String netmask) {
    final String cidr = getCidrFromGatewayAndNetmask(ip, netmask);
    final SubnetUtils subnetUtils = new SubnetUtils(cidr);
    subnetUtils.setInclusiveHostCount(false);
    final boolean isInRange = subnetUtils.getInfo().isInRange(ip);
    return !isInRange;
}
 
Example 8
Source File: DefaultK8sNetwork.java    From onos with Apache License 2.0 5 votes vote down vote up
private IpAddress getGatewayIp(String cidr) {
    SubnetUtils utils = new SubnetUtils(cidr);
    utils.setInclusiveHostCount(false);
    SubnetUtils.SubnetInfo info = utils.getInfo();

    return IpAddress.valueOf(info.getLowAddress());
}
 
Example 9
Source File: AzureStackViewProvider.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private long getAvailableAddresses(Subnet subnet) {
    SubnetUtils su = new SubnetUtils(subnet.addressPrefix());
    su.setInclusiveHostCount(true);
    long available = su.getInfo().getAddressCountLong();
    long used = subnet.networkInterfaceIPConfigurationCount();
    return available - used - AZURE_NUMBER_OF_RESERVED_IPS;
}
 
Example 10
Source File: NetUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static boolean isNetworkorBroadcastIP(String ip, String netmask){
    String cidr = getCidrFromGatewayAndNetmask(ip,netmask);
    final SubnetUtils subnetUtils = new SubnetUtils(cidr);
    subnetUtils.setInclusiveHostCount(false);
    final boolean isInRange = subnetUtils.getInfo().isInRange(ip);
    return !isInRange;
}
 
Example 11
Source File: FileBasedClusterNodeFirewall.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
private void parseConfig(final File config) throws IOException {

        // clear old information
        subnetInfos.clear();
        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);
            }

        }
    }
 
Example 12
Source File: MachineList.java    From hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * Accepts a collection of ip/cidr/host addresses
 * 
 * @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; 
  }
}
 
Example 13
Source File: MachineList.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * Accepts a collection of ip/cidr/host addresses
 * 
 * @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; 
  }
}
 
Example 14
Source File: FileBasedClusterNodeFirewall.java    From nifi with Apache License 2.0 4 votes vote down vote up
private void parseConfig(final File config) throws IOException {

        // clear old information
        subnetInfos.clear();
        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);
            }

        }
    }