org.apache.commons.net.util.SubnetUtils Java Examples

The following examples show how to use org.apache.commons.net.util.SubnetUtils. 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: NetworkUtils.java    From zstack with Apache License 2.0 6 votes vote down vote up
public static boolean isMulticastCidr(String cidr) {
    try {
        IPv6Network network6 = IPv6Network.fromString(cidr);
        String formatCidr = network6.toString();
        String formatAddress = formatCidr.split("/")[0];
        IPv6Address address6 = IPv6Address.fromString(formatAddress);
        return address6.isMulticast();
    } catch (Exception e) {
        Pattern pattern = Pattern.compile("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\\/(\\d|[1-2]\\d|3[0-2]))$");
        Matcher matcher = pattern.matcher(cidr);
        if (!matcher.find()) {
            return false;
        }

        SubnetUtils sub = new SubnetUtils(cidr);
        String address = sub.getInfo().getAddress();
        return isIpv4MulticastAddress(address);
    }
}
 
Example #2
Source File: ReservationStep.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public void execute() throws EnvironmentModificationException, PeerException
{

    Set<Peer> newPeers = peerManager.resolve( topology.getAllPeers() );

    //remove already participating peers
    newPeers.removeAll( environment.getPeers() );

    if ( newPeers.isEmpty() )
    {
        return;
    }

    //obtain reserved net resources
    final Map<Peer, UsedNetworkResources> reservedNetResources = obtainReservedNetResources( newPeers );


    //check availability of network resources
    SubnetUtils subnetUtils = new SubnetUtils( environment.getSubnetCidr() );
    final String containerSubnet = subnetUtils.getInfo().getNetworkAddress();

    checkResourceAvailablility( reservedNetResources, containerSubnet );

    //reserve network resources
    reserveNetworkResources( newPeers, containerSubnet );
}
 
Example #3
Source File: SubnetUtilsTest.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Test
public void testIp()
{
    SubnetUtils utils = new SubnetUtils( "10.12.0.1/24" );
    final SubnetUtils.SubnetInfo info = utils.getInfo();
    assertEquals( "10.12.0.1", info.getAddress() );
    assertEquals( "10.12.0.0", info.getNetworkAddress() );
    assertEquals( "10.12.0.255", info.getBroadcastAddress() );
    assertEquals( 254, info.getAddressCount() );
    assertEquals( "10.12.0.1/24", info.getCidrSignature() );
    assertEquals( "10.12.0.1", info.getLowAddress() );
    assertEquals( "10.12.0.254", info.getHighAddress() );
    assertEquals( "255.255.255.0", info.getNetmask() );
    assertEquals( true, info.isInRange( "10.12.0.100" ) );
    assertEquals( false, info.isInRange( "10.11.0.1" ) );
}
 
Example #4
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 #5
Source File: VirtualRouterApiInterceptor.java    From zstack with Apache License 2.0 6 votes vote down vote up
private Boolean isNetworkAddressEqual(String networkUuid1, String networkUuid2) {
    if (networkUuid1.equals(networkUuid2)) {
        return true;
    }
    L3NetworkVO l3vo1 = Q.New(L3NetworkVO.class).eq(L3NetworkVO_.uuid, networkUuid1).find();
    L3NetworkVO l3vo2 = Q.New(L3NetworkVO.class).eq(L3NetworkVO_.uuid, networkUuid2).find();
    if (!l3vo1.getIpVersion().equals(l3vo2.getIpVersion())) {
        return false;
    }
    List<IpRangeInventory> ipInvs1 = IpRangeHelper.getNormalIpRanges(l3vo1);
    List<IpRangeInventory> ipInvs2 = IpRangeHelper.getNormalIpRanges(l3vo2);
    if (ipInvs1.isEmpty() || ipInvs2.isEmpty()) {
        return false;
    }

    if (l3vo1.getIpVersion() == IPv6Constants.IPv4) {
        String netAddr1 = new SubnetUtils(ipInvs1.get(0).getGateway(), ipInvs1.get(0).getNetmask()).getInfo().getNetworkAddress();
        String netAddr2 = new SubnetUtils(ipInvs2.get(0).getGateway(), ipInvs2.get(0).getNetmask()).getInfo().getNetworkAddress();
        return netAddr1.equals(netAddr2);
    } else if (l3vo1.getIpVersion() == IPv6Constants.IPv6) {
        return IPv6NetworkUtils.isIpv6CidrEqual(ipInvs1.get(0).getNetworkCidr(), ipInvs2.get(0).getNetworkCidr());
    }
    return false;
}
 
Example #6
Source File: EipApiInterceptor.java    From zstack with Apache License 2.0 6 votes vote down vote up
private void isVipInVmNicSubnet(String vipUuid, String guestIpUuid) {
    VipVO vip = dbf.findByUuid(vipUuid, VipVO.class);
    UsedIpVO vipIp = dbf.findByUuid(vip.getUsedIpUuid(), UsedIpVO.class);
    NormalIpRangeVO vipRange = dbf.findByUuid(vipIp.getIpRangeUuid(), NormalIpRangeVO.class);

    UsedIpVO guestIp = dbf.findByUuid(guestIpUuid, UsedIpVO.class);
    NormalIpRangeVO guestRange = dbf.findByUuid(guestIp.getIpRangeUuid(), NormalIpRangeVO.class);

    if (!vipIp.getIpVersion().equals(guestIp.getIpVersion())) {
        throw new ApiMessageInterceptionException(operr("vip ipVersion [%d] is different from guestIp ipVersion [%d].",
                vipIp.getIpVersion(), guestIp.getIpVersion()));
    }

    if (vipIp.getIpVersion() == IPv6Constants.IPv4) {
        SubnetUtils guestSub = new SubnetUtils(guestRange.getGateway(), guestRange.getNetmask());
        if (guestSub.getInfo().isInRange(vipIp.getIp())) {
            throw new ApiMessageInterceptionException(operr("Vip[%s] is in the guest ip range [%s, %s]",
                    vipIp.getIp(), guestRange.getStartIp(), guestRange.getEndIp()));
        }
    } else {
        if (IPv6NetworkUtils.isIpv6InCidrRange(vipIp.getIp(), guestRange.getNetworkCidr())){
            throw new ApiMessageInterceptionException(operr("Vip[%s] is in the guest ip range [%s, %s]",
                    vipIp.getIp(), guestRange.getStartIp(), guestRange.getEndIp()));
        }
    }
}
 
Example #7
Source File: MachineList.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * returns the contents of the MachineList as a Collection<String>
 * This can be used for testing 
 * @return contents of the MachineList
 */
@VisibleForTesting
public Collection<String> getCollection() {
  Collection<String> list = new ArrayList<String>();
  if (all) {
    list.add("*"); 
  } else {
    if (ipAddresses != null) {
      list.addAll(ipAddresses);
    }
    if (hostNames != null) {
      list.addAll(hostNames);
    }
    if (cidrAddresses != null) {
      for(SubnetUtils.SubnetInfo cidrAddress : cidrAddresses) {
        list.add(cidrAddress.getCidrSignature());
      }
    }
  }
  return list;
}
 
Example #8
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 #9
Source File: AwsNetworkService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private String calculateSubnet(String stackName, Vpc vpc, Iterable<String> subnetCidrs) {
    SubnetInfo vpcInfo = new SubnetUtils(vpc.getCidrBlock()).getInfo();
    String[] cidrParts = vpcInfo.getCidrSignature().split("/");
    int netmask = Integer.parseInt(cidrParts[cidrParts.length - 1]);
    int netmaskBits = CIDR_PREFIX - netmask;
    if (netmaskBits <= 0) {
        throw new CloudConnectorException("The selected VPC has to be in a bigger CIDR range than /24");
    }
    int numberOfSubnets = Double.valueOf(Math.pow(2, netmaskBits)).intValue();
    int targetSubnet = 0;
    if (stackName != null) {
        byte[] b = stackName.getBytes(Charset.forName("UTF-8"));
        for (byte ascii : b) {
            targetSubnet += ascii;
        }
    }
    targetSubnet = Long.valueOf(targetSubnet % numberOfSubnets).intValue();
    String cidr = getSubnetCidrInRange(vpc, subnetCidrs, targetSubnet, numberOfSubnets);
    if (cidr == null) {
        cidr = getSubnetCidrInRange(vpc, subnetCidrs, 0, targetSubnet);
    }
    if (cidr == null) {
        throw new CloudConnectorException("Cannot find non-overlapping CIDR range");
    }
    return cidr;
}
 
Example #10
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 #11
Source File: NetworkFunctions.java    From metron with Apache License 2.0 6 votes vote down vote up
@Override
public Object apply(List<Object> list) {
  if(list.size() < 2) {
    throw new IllegalStateException("IN_SUBNET expects at least two args: [ip, cidr1, cidr2, ...]"
            + " where cidr is the subnet mask in cidr form"
    );
  }
  String ip = (String) list.get(0);
  if(ip == null) {
    return false;
  }
  boolean inSubnet = false;
  for(int i = 1;i < list.size() && !inSubnet;++i) {
    String cidr = (String) list.get(i);
    if(cidr == null) {
      continue;
    }
    inSubnet |= new SubnetUtils(cidr).getInfo().isInRange(ip);
  }

  return inSubnet;
}
 
Example #12
Source File: MachineList.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * returns the contents of the MachineList as a Collection<String>
 * This can be used for testing 
 * @return contents of the MachineList
 */
@VisibleForTesting
public Collection<String> getCollection() {
  Collection<String> list = new ArrayList<String>();
  if (all) {
    list.add("*"); 
  } else {
    if (ipAddresses != null) {
      list.addAll(ipAddresses);
    }
    if (hostNames != null) {
      list.addAll(hostNames);
    }
    if (cidrAddresses != null) {
      for(SubnetUtils.SubnetInfo cidrAddress : cidrAddresses) {
        list.add(cidrAddress.getCidrSignature());
      }
    }
  }
  return list;
}
 
Example #13
Source File: SubnetValidator.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }
    if (value.isEmpty()) {
        return subnetType.equals(SubnetType.RFC_1918_COMPLIANT_ONLY_OR_EMPTY);
    }
    try {


        SubnetInfo info = new SubnetUtils(value).getInfo();
        if (!info.getAddress().equals(info.getNetworkAddress())) {
            return false;
        }
        switch (subnetType) {
            case CUSTOM:
                return true;
            case RFC_1918_COMPLIANT_ONLY:
            default:
                return isRfc1918CompliantSubnet(info);
        }
    } catch (IllegalArgumentException exception) {
        return false;
    }
}
 
Example #14
Source File: NetworkConfigurationValidator.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public boolean validateNetworkForStack(Network network, Iterable<InstanceGroup> instanceGroups) {
    if (network.getSubnetCIDR() != null) {
        SubnetUtils utils = new SubnetUtils(network.getSubnetCIDR());
        int addressCount = utils.getInfo().getAddressCount();
        int nodeCount = 0;
        for (InstanceGroup instanceGroup : instanceGroups) {
            nodeCount += instanceGroup.getNodeCount();
        }
        if (addressCount < nodeCount) {
            LOGGER.info("Cannot assign more than {} addresses in the selected subnet.", addressCount);
            throw new BadRequestException(
                    String.format("Cannot assign more than %s addresses in the selected subnet.", addressCount));
        }
    }
    return true;
}
 
Example #15
Source File: IpRangeInventory.java    From zstack with Apache License 2.0 6 votes vote down vote up
public static IpRangeInventory fromMessage(APIAddIpRangeMsg msg) {
    IpRangeInventory ipr = new IpRangeInventory();
    ipr.setName(msg.getName());
    ipr.setDescription(msg.getDescription());
    ipr.setStartIp(msg.getStartIp());
    ipr.setEndIp(msg.getEndIp());
    ipr.setNetmask(msg.getNetmask());
    ipr.setPrefixLen(NetworkUtils.getPrefixLengthFromNetwork(msg.getNetmask()));
    ipr.setGateway(msg.getGateway());
    ipr.setL3NetworkUuid(msg.getL3NetworkUuid());
    SubnetUtils su = new SubnetUtils(msg.getStartIp(), msg.getNetmask());
    ipr.setNetworkCidr(su.getInfo().getCidrSignature());
    ipr.setUuid(msg.getResourceUuid());
    ipr.setIpVersion(IPv6Constants.IPv4);
    ipr.setIpRangeType(IpRangeType.valueOf(msg.getIpRangeType()));
    return ipr;
}
 
Example #16
Source File: IPUtils.java    From SkaETL with Apache License 2.0 6 votes vote down vote up
public static Boolean isInSubnet(String ip, String subnet) {
    if (subnet.contains("*")) {
        String[] subnetGroup = subnet.split("\\.");
        String[] ipGroup = ip.split("\\.");
        for (int i = 0; i < ipGroup.length; i++) {
            if ("*".equals(subnetGroup[i])) {
                continue;
            }
            if (!subnetGroup[i].equals(ipGroup[i])) {
                return false;
            }
        }
        return true;
    }

    SubnetUtils utils = new SubnetUtils(subnet);
    return utils.getInfo().isInRange(ip);
}
 
Example #17
Source File: SubnetServiceImp.java    From alcor with Apache License 2.0 6 votes vote down vote up
@Override
public String[] cidrToFirstIpAndLastIp(String cidr) {
    if (cidr == null) {
        return null;
    }
    SubnetUtils utils = new SubnetUtils(cidr);
    String highIp = utils.getInfo().getHighAddress();
    String lowIp = utils.getInfo().getLowAddress();
    if (highIp == null || lowIp == null) {
        return null;
    }
    String[] res = new String[2];
    res[0] = lowIp;
    res[1] = highIp;
    return res;
}
 
Example #18
Source File: DefaultSubnetCidrProvider.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private String calculateSubnet(String networkCidr, Iterable<NetworkSubnetRequest> subnetCidrs) {
    SubnetUtils.SubnetInfo vpcInfo = new SubnetUtils(networkCidr).getInfo();
    String[] cidrParts = vpcInfo.getCidrSignature().split("/");
    int netmask = Integer.parseInt(cidrParts[cidrParts.length - 1]);
    int netmaskBits = CIDR_PREFIX - netmask;
    if (netmaskBits <= 0) {
        throw new CloudConnectorException("The selected VPC has to be in a bigger CIDR range than /24");
    }
    int numberOfSubnets = Double.valueOf(Math.pow(2, netmaskBits)).intValue();
    int targetSubnet = 0;
    targetSubnet = Long.valueOf(targetSubnet % numberOfSubnets).intValue();
    String cidr = getSubnetCidrInRange(networkCidr, subnetCidrs, targetSubnet, numberOfSubnets);
    if (cidr == null) {
        cidr = getSubnetCidrInRange(networkCidr, subnetCidrs, 0, targetSubnet);
    }
    if (cidr == null) {
        throw new CloudConnectorException("Cannot find non-overlapping CIDR range");
    }
    return cidr;
}
 
Example #19
Source File: PrivateDNS.java    From PacketProxy with Apache License 2.0 6 votes vote down vote up
SpoofAddrFactory() throws Exception {
	Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
	for (NetworkInterface netint : Collections.list(nets)) {
		for (InterfaceAddress intAddress : netint.getInterfaceAddresses()) {
			InetAddress addr = intAddress.getAddress();
			if (addr instanceof Inet4Address) {
				String cidr = String.format("%s/%d", addr.getHostAddress(), intAddress.getNetworkPrefixLength());
				SubnetUtils subnet = new SubnetUtils(cidr);
				subnets.add(subnet.getInfo());
				if (defaultAddr == null) {
					defaultAddr = addr.getHostAddress();
				} else if (defaultAddr.equals("127.0.0.1")) {
					defaultAddr = addr.getHostAddress();
				}
			}
		}
	}
}
 
Example #20
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 #21
Source File: ipInRange.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the SubnetInfo block from the input parameters
 * @param _session
 * @param argStruct
 * @return
 * @throws cfmRunTimeException
 */
protected SubnetInfo	getInfo(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
	String ipaddress	= getNamedStringParam(argStruct, "ip", null);
	if ( ipaddress == null )
		throwException(_session, "Missing ip paramter" );
	
	if ( ipaddress.lastIndexOf("/") == -1 ){
		String mask	= getNamedStringParam(argStruct, "mask", null);
		if ( mask == null )
			throwException(_session, "Since IP address is not in CIDR notation, please provide a mask" );
		
		return new SubnetUtils(ipaddress, mask).getInfo();
	}else
		return new SubnetUtils(ipaddress).getInfo();
}
 
Example #22
Source File: NetworkOrganizer.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns specified number of IP addresses from original list of addresses, that are NOT listen in primary collection
 *
 * @param numShards
 * @param primary Collection of IP addresses that shouldn't be in result
 * @return
 */
public List<String> getSubset(int numShards, Collection<String> primary) {
    /**
     * If netmask in unset, we'll use manual
     */
    if (networkMask == null)
        return getIntersections(numShards, primary);

    List<String> addresses = new ArrayList<>();

    SubnetUtils utils = new SubnetUtils(networkMask);

    Collections.shuffle(informationCollection);

    for (NetworkInformation information : informationCollection) {
        for (String ip : information.getIpAddresses()) {
            if (primary != null && primary.contains(ip))
                continue;

            if (utils.getInfo().isInRange(ip)) {
                log.debug("Picked {} as {}", ip, primary == null ? "Shard" : "Backup");
                addresses.add(ip);
            }

            if (addresses.size() >= numShards)
                break;
        }

        if (addresses.size() >= numShards)
            break;
    }

    return addresses;
}
 
Example #23
Source File: FileBasedClusterNodeFirewall.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isPermissible(final String hostOrIp) {
    try {

        // if no rules, then permit everything
        if (subnetInfos.isEmpty()) {
            return true;
        }

        final String ip;
        try {
            ip = InetAddress.getByName(hostOrIp).getHostAddress();
        } catch (final UnknownHostException uhe) {
            logger.warn("Blocking unknown host '{}'", hostOrIp, uhe);
            return false;
        }

        // check each subnet to see if IP is in range
        for (final SubnetUtils.SubnetInfo subnetInfo : subnetInfos) {
            if (subnetInfo.isInRange(ip)) {
                return true;
            }
        }

        // no match
        logger.debug("Blocking host '{}' because it does not match our allowed list.", hostOrIp);
        return false;

    } catch (final IllegalArgumentException iae) {
        logger.debug("Blocking requested host, '{}', because it is malformed.", hostOrIp, iae);
        return false;
    }
}
 
Example #24
Source File: DefaultSubnetCidrProvider.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private String getSubnetCidrInRange(String networkCidr, Iterable<NetworkSubnetRequest> subnetCidrs, int start, int end) {
    SubnetUtils.SubnetInfo vpcInfo = new SubnetUtils(networkCidr).getInfo();
    String lowProbe = incrementIp(vpcInfo.getLowAddress());
    String highProbe = new SubnetUtils(toSubnetCidr(lowProbe)).getInfo().getHighAddress();
    // start from the target subnet
    for (int i = 0; i < start - 1; i++) {
        lowProbe = incrementIp(lowProbe);
        highProbe = incrementIp(highProbe);
    }
    boolean foundProbe = false;
    for (int i = start; i < end; i++) {
        boolean overlapping = false;
        for (NetworkSubnetRequest subnetCidr : subnetCidrs) {
            SubnetUtils.SubnetInfo subnetInfo = new SubnetUtils(subnetCidr.getCidr()).getInfo();
            if (isInRange(lowProbe, subnetInfo) || isInRange(highProbe, subnetInfo)) {
                overlapping = true;
                break;
            }
        }
        if (overlapping) {
            lowProbe = incrementIp(lowProbe);
            highProbe = incrementIp(highProbe);
        } else {
            foundProbe = true;
            break;
        }
    }
    if (foundProbe && isInRange(highProbe, vpcInfo)) {
        String subnet = toSubnetCidr(lowProbe);
        LOGGER.debug("The following subnet cidr found: {} for VPC: {}", subnet, networkCidr);
        return subnet;
    } else {
        return null;
    }
}
 
Example #25
Source File: NetworkOrganizer.java    From nd4j with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns specified number of IP addresses from original list of addresses, that are NOT listen in primary collection
 *
 * @param numShards
 * @param primary Collection of IP addresses that shouldn't be in result
 * @return
 */
public List<String> getSubset(int numShards, Collection<String> primary) {
    /**
     * If netmask in unset, we'll use manual
     */
    if (networkMask == null)
        return getIntersections(numShards, primary);

    List<String> addresses = new ArrayList<>();

    SubnetUtils utils = new SubnetUtils(networkMask);

    Collections.shuffle(informationCollection);

    for (NetworkInformation information : informationCollection) {
        for (String ip : information.getIpAddresses()) {
            if (primary != null && primary.contains(ip))
                continue;

            if (utils.getInfo().isInRange(ip)) {
                log.debug("Picked {} as {}", ip, primary == null ? "Shard" : "Backup");
                addresses.add(ip);
            }

            if (addresses.size() >= numShards)
                break;
        }

        if (addresses.size() >= numShards)
            break;
    }

    return addresses;
}
 
Example #26
Source File: ipGetCount.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the SubnetInfo block from the input parameters
 * @param _session
 * @param argStruct
 * @return
 * @throws cfmRunTimeException
 */
protected SubnetInfo	getInfo(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
	String ipaddress	= getNamedStringParam(argStruct, "ip", null);
	if ( ipaddress == null )
		throwException(_session, "Missing ip paramter" );
	
	if ( ipaddress.lastIndexOf("/") == -1 ){
		String mask	= getNamedStringParam(argStruct, "mask", null);
		if ( mask == null )
			throwException(_session, "Since IP address is not in CIDR notation, please provide a mask" );
		
		return new SubnetUtils(ipaddress, mask).getInfo();
	}else
		return new SubnetUtils(ipaddress).getInfo();
}
 
Example #27
Source File: ipAsInteger.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public cfData execute(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
	String ipaddress	= getNamedStringParam(argStruct, "ip", null);
	if ( ipaddress == null )
		throwException(_session, "Missing ip paramter" );
	
	return new cfNumberData( new SubnetUtils("10.0.0.1","255.255.255.255").getInfo().asInteger(ipaddress) );
}
 
Example #28
Source File: IpRangeAO.java    From zstack with Apache License 2.0 5 votes vote down vote up
public String getNetworkCidr() {
    if (networkCidr != null) {
        return networkCidr;
    }

    SubnetUtils su = new SubnetUtils(gateway, netmask);
    return su.getInfo().getCidrSignature();
}
 
Example #29
Source File: IpRangeInventory.java    From zstack with Apache License 2.0 5 votes vote down vote up
public static IpRangeInventory fromMessage(APIAddIpRangeByNetworkCidrMsg msg) {
    SubnetUtils utils = new SubnetUtils(msg.getNetworkCidr());
    SubnetInfo subnet = utils.getInfo();

    IpRangeInventory ipr = new IpRangeInventory();
    ipr.setNetworkCidr(msg.getNetworkCidr());
    ipr.setName(msg.getName());
    ipr.setDescription(msg.getDescription());

    ipr.setIpRangeType(IpRangeType.valueOf(msg.getIpRangeType()));

    if (ipr.getIpRangeType() == IpRangeType.Normal) {
        String lowAddress = NetworkUtils.longToIpv4String(NetworkUtils.ipv4StringToLong(subnet.getLowAddress()));
        String highAddress = NetworkUtils.longToIpv4String(NetworkUtils.ipv4StringToLong(subnet.getHighAddress()));
        if (msg.getGateway() == null || msg.getGateway().equals(lowAddress)) {
            ipr.setGateway(lowAddress);
            ipr.setStartIp(NetworkUtils.longToIpv4String(NetworkUtils.ipv4StringToLong(subnet.getLowAddress()) + 1));
            ipr.setEndIp(subnet.getHighAddress());
        } else if (msg.getGateway().equals(highAddress)) {
            ipr.setGateway(highAddress);
            ipr.setStartIp(lowAddress);
            ipr.setEndIp(NetworkUtils.longToIpv4String(NetworkUtils.ipv4StringToLong(subnet.getHighAddress()) - 1));
        }
    } else {
        ipr.setGateway(NetworkUtils.longToIpv4String(NetworkUtils.ipv4StringToLong(subnet.getLowAddress())));
        ipr.setStartIp(NetworkUtils.longToIpv4String(NetworkUtils.ipv4StringToLong(subnet.getLowAddress()) - 1));
        ipr.setEndIp(NetworkUtils.longToIpv4String(NetworkUtils.ipv4StringToLong(subnet.getHighAddress()) + 1));
    }
    ipr.setNetmask(subnet.getNetmask());
    ipr.setPrefixLen(NetworkUtils.getPrefixLengthFromNetwork(subnet.getNetmask()));
    ipr.setL3NetworkUuid(msg.getL3NetworkUuid());
    ipr.setUuid(msg.getResourceUuid());
    ipr.setIpVersion(IPv6Constants.IPv4);
    return ipr;
}
 
Example #30
Source File: IPAddrUtil.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Match an address against a list of IP CIDR addresses
 * 
 * @param addrlist
 *        The comma-separated list of addresses
 * @param addr
 *        The IP address to match
 * @return true if address is contained in one or more of the CIDR network blocks listed in addrlist, false if not
 */
public static boolean matchIPList(String addrlist, String addr)
{
	log.info("Checking login IP '" + addr + "' is contained in whitelist '" + addrlist + "'");

	// TODO Support IPv6

	if (StringUtils.isBlank(addrlist) || StringUtils.isBlank(addr))
		return false;

	boolean match = false;

	for (String netaddr : Arrays.asList(addrlist.split(","))) {
		if (netaddr.contains("/")) {
			// Contained in subnet?
			try {
				SubnetUtils.SubnetInfo subnet = new SubnetUtils(netaddr.trim()).getInfo();
				if (subnet.isInRange(addr)) {
					log.debug("IP Address " + addr + " is in network range " + subnet.getCidrSignature());
					match = true;
					break;
				}
			} catch (IllegalArgumentException e) {
				log.warn("IP network address '" + netaddr + "' is not a valid CIDR format");
			}
		} else {
			// Exact match?
			if (netaddr.trim().equals(addr)) {
				match = true;
				break;
			}
		}
	}
	return match;
}