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

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

Introduction

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

Prototype

public SubnetUtils(String cidrNotation) 

Source Link

Document

Constructor that takes a CIDR-notation string, e.g.

Usage

From source file:org.opendaylight.opendove.odmc.OpenDoveGwIpv4.java

public static OpenDoveGwIpv4 assignEGWs(Object o, OpenDoveServiceAppliance target, String subnetCIDR,
        String subnetGatewayIP, String gwAddress, NeutronRouter router) {
    IfSBDoveGwIpv4CRUD gatewayIPDB = OpenDoveCRUDInterfaces.getIfSBDoveGwIpv4CRUD(o);
    SubnetUtils util = new SubnetUtils(subnetCIDR);
    SubnetInfo info = util.getInfo();/*  w w  w.  j  a v  a 2s.c  om*/
    OpenDoveGwIpv4 newGWIP = null;
    List<OpenDoveGwIpv4> gwIPs = gatewayIPDB.getGwIpv4Pool();
    Iterator<OpenDoveGwIpv4> ipIterator = gwIPs.iterator();
    boolean found = false;

    while (ipIterator.hasNext()) {
        OpenDoveGwIpv4 gwIP = ipIterator.next();

        if (gwIP.getGWUUID().equalsIgnoreCase(target.getUUID()) && info.isInRange(gwIP.getIP())
                && gwIP.getType().equalsIgnoreCase("external")) {
            found = true;
        }
    }

    if (!found) {
        newGWIP = new OpenDoveGwIpv4(gwAddress, OpenDoveSubnet.getIPMask(subnetCIDR), subnetGatewayIP,
                "external", target.getUUID(), 0, router);
        //TODO: this needs to be outside
        //newGWIP.setNeutronSubnet(neutronSubnet);
        gatewayIPDB.addGwIpv4(newGWIP.getUUID(), newGWIP);
        // Set the External IP for EGW, will be used by SNAT Pool Configuration
        target.setEGWExtIP(newGWIP);
    }

    return newGWIP;
}

From source file:org.opendaylight.opendove.odmc.OpenDoveServiceAppliance.java

public static OpenDoveServiceAppliance selectAssignedDGW(Object o, String cidr) {
    List<OpenDoveServiceAppliance> answer = new ArrayList<OpenDoveServiceAppliance>();
    IfOpenDoveServiceApplianceCRUD serviceApplianceDB = OpenDoveCRUDInterfaces.getIfDoveServiceApplianceCRUD(o);
    for (OpenDoveServiceAppliance oDSA : serviceApplianceDB.getAppliances()) {
        if (oDSA.get_isDGW() && oDSA.getDoveTunnel() != null && oDSA.getEGWExtIP() != null) {
            String ip = oDSA.getEGWExtIP().getIP();
            SubnetUtils util = new SubnetUtils(cidr);
            SubnetInfo info = util.getInfo();
            if (info.isInRange(ip)) {
                answer.add(oDSA);/*from   w  ww  .  ja  va  2  s. com*/
            }
        }
    }
    if (answer.size() > 0) {
        Integer count = answer.size();
        int index = Math.abs(OpenDoveUtils.getNextInt()) % count;
        OpenDoveServiceAppliance target = answer.get(index);
        return target;
    }
    return null;
}

From source file:org.opendaylight.plugin2oc.neutron.SubnetHandler.java

boolean validGatewayIP(NeutronSubnet subnet, String ipAddress) {
    try {/*from ww  w.ja  va2 s.  c  o m*/
        SubnetUtils util = new SubnetUtils(subnet.getCidr());
        SubnetInfo info = util.getInfo();
        boolean inRange = info.isInRange(ipAddress);
        if (!inRange) {
            return false;
        } else {
            // ip available in allocation pool
            Iterator<NeutronSubnet_IPAllocationPool> i = subnet.getAllocationPools().iterator();
            while (i.hasNext()) {
                NeutronSubnet_IPAllocationPool pool = i.next();
                if (pool.contains(ipAddress)) {
                    return true;
                }
            }
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("Exception  :  " + e);
        return false;
    }
}

From source file:org.opendaylight.vpnservice.dhcpservice.DhcpPktHandler.java

private void setCommonOptions(DHCP pkt, DhcpInfo dhcpInfo) {
    pkt.setOptionInt(DHCPConstants.OPT_LEASE_TIME, dhcpMgr.getDhcpLeaseTime());
    if (dhcpMgr.getDhcpDefDomain() != null) {
        pkt.setOptionString(DHCPConstants.OPT_DOMAIN_NAME, dhcpMgr.getDhcpDefDomain());
    }/*  w  w w .j a va2 s  .  c o  m*/
    if (dhcpMgr.getDhcpLeaseTime() > 0) {
        pkt.setOptionInt(DHCPConstants.OPT_REBINDING_TIME, dhcpMgr.getDhcpRebindingTime());
        pkt.setOptionInt(DHCPConstants.OPT_RENEWAL_TIME, dhcpMgr.getDhcpRenewalTime());
    }
    SubnetUtils util = null;
    SubnetInfo info = null;
    util = new SubnetUtils(dhcpInfo.getCidr());
    info = util.getInfo();
    String gwIp = dhcpInfo.getGatewayIp();
    List<String> dnServers = dhcpInfo.getDnsServers();
    try {
        /*
         * setParameterListOptions may have initialized some of these
         * options to maintain order. If we can't fill them, unset to avoid
         * sending wrong information in reply.
         */
        if (gwIp != null) {
            pkt.setOptionInetAddr(DHCPConstants.OPT_SERVER_IDENTIFIER, gwIp);
            pkt.setOptionInetAddr(DHCPConstants.OPT_ROUTERS, gwIp);
        } else {
            pkt.unsetOption(DHCPConstants.OPT_SERVER_IDENTIFIER);
            pkt.unsetOption(DHCPConstants.OPT_ROUTERS);
        }
        if (info != null) {
            pkt.setOptionInetAddr(DHCPConstants.OPT_SUBNET_MASK, info.getNetmask());
            pkt.setOptionInetAddr(DHCPConstants.OPT_BROADCAST_ADDRESS, info.getBroadcastAddress());
        } else {
            pkt.unsetOption(DHCPConstants.OPT_SUBNET_MASK);
            pkt.unsetOption(DHCPConstants.OPT_BROADCAST_ADDRESS);
        }
        if ((dnServers != null) && (dnServers.size() > 0)) {
            pkt.setOptionStrAddrs(DHCPConstants.OPT_DOMAIN_NAME_SERVERS, dnServers);
        } else {
            pkt.unsetOption(DHCPConstants.OPT_DOMAIN_NAME_SERVERS);
        }
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.opendaylight.vpnservice.dhcpservice.DhcpPktHandler.java

protected byte[] convertToClasslessRouteOption(String dest, String router) {
    ByteArrayOutputStream bArr = new ByteArrayOutputStream();
    if ((dest == null || router == null)) {
        return null;
    }/*  w w w.j  av  a2 s  .co  m*/

    //get prefix
    Short prefix = null;
    String[] parts = dest.split("/");
    if (parts.length < 2) {
        prefix = new Short((short) 0);
    } else {
        prefix = Short.valueOf(parts[1]);
    }

    bArr.write(prefix.byteValue());
    SubnetUtils util = new SubnetUtils(dest);
    SubnetInfo info = util.getInfo();
    String strNetAddr = info.getNetworkAddress();
    try {
        byte[] netAddr = InetAddress.getByName(strNetAddr).getAddress();
        //Strip any trailing 0s from netAddr
        for (int i = 0; i < netAddr.length; i++) {
            if (netAddr[i] != 0) {
                bArr.write(netAddr, i, 1);
            }
        }
        bArr.write(InetAddress.getByName(router).getAddress());
    } catch (IOException e) {
        return null;
    }
    return bArr.toByteArray();
}

From source file:org.opendaylight.vpnservice.itm.cli.TepCommandHelper.java

private boolean validateIPs(String ipAddress, String subnetMask, String gatewayIp) {
    SubnetUtils utils = new SubnetUtils(subnetMask);
    if ((utils.getInfo().isInRange(ipAddress))
            && ((gatewayIp == null) || (utils.getInfo().isInRange(gatewayIp)))) {
        return true;
    } else {//from   w w w  .  ja v a 2s .  c  o m
        LOG.trace("InValid IP");
        return false;
    }
}

From source file:org.opendaylight.vpnservice.itm.confighelpers.ItmExternalTunnelAddWorker.java

public static List<ListenableFuture<Void>> buildTunnelsToExternalEndPoint(DataBroker dataBroker,
        IdManagerService idManagerService, List<DPNTEPsInfo> cfgDpnList, IpAddress extIp,
        Class<? extends TunnelTypeBase> tunType) {
    List<ListenableFuture<Void>> futures = new ArrayList<>();
    WriteTransaction t = dataBroker.newWriteOnlyTransaction();
    if (null != cfgDpnList) {
        for (DPNTEPsInfo teps : cfgDpnList) {
            // CHECK -- Assumption -- Only one End Point / Dpn for GRE/Vxlan Tunnels
            TunnelEndPoints firstEndPt = teps.getTunnelEndPoints().get(0);
            String interfaceName = firstEndPt.getInterfaceName();
            String tunTypeStr = tunType.getName();
            String trunkInterfaceName = ItmUtils.getTrunkInterfaceName(idManagerService, interfaceName,
                    firstEndPt.getIpAddress().getIpv4Address().getValue(), extIp.getIpv4Address().getValue(),
                    tunTypeStr);/*  www.  j a  va 2 s .c  o  m*/
            char[] subnetMaskArray = firstEndPt.getSubnetMask().getValue();
            String subnetMaskStr = String.valueOf(subnetMaskArray);
            SubnetUtils utils = new SubnetUtils(subnetMaskStr);
            String dcGwyIpStr = String.valueOf(extIp.getValue());
            IpAddress gatewayIpObj = new IpAddress("0.0.0.0".toCharArray());
            IpAddress gwyIpAddress = (utils.getInfo().isInRange(dcGwyIpStr)) ? gatewayIpObj
                    : firstEndPt.getGwIpAddress();
            logger.debug(
                    " Creating Trunk Interface with parameters trunk I/f Name - {}, parent I/f name - {}, source IP - {}, DC Gateway IP - {} gateway IP - {}",
                    trunkInterfaceName, interfaceName, firstEndPt.getIpAddress(), extIp, gwyIpAddress);
            Interface iface = ItmUtils.buildTunnelInterface(teps.getDPNID(), trunkInterfaceName,
                    String.format("%s %s", ItmUtils.convertTunnelTypetoString(tunType), "Trunk Interface"),
                    true, tunType, firstEndPt.getIpAddress(), extIp, gwyIpAddress, firstEndPt.getVLANID(),
                    false, false, null);
            logger.debug(" Trunk Interface builder - {} ", iface);
            InstanceIdentifier<Interface> trunkIdentifier = ItmUtils.buildId(trunkInterfaceName);
            logger.debug(" Trunk Interface Identifier - {} ", trunkIdentifier);
            logger.trace(" Writing Trunk Interface to Config DS {}, {} ", trunkIdentifier, iface);
            t.merge(LogicalDatastoreType.CONFIGURATION, trunkIdentifier, iface, true);
            // update external_tunnel_list ds
            InstanceIdentifier<ExternalTunnel> path = InstanceIdentifier.create(ExternalTunnelList.class).child(
                    ExternalTunnel.class,
                    new ExternalTunnelKey(extIp.toString(), teps.getDPNID().toString(), tunType));
            ExternalTunnel tnl = ItmUtils.buildExternalTunnel(teps.getDPNID().toString(), extIp.toString(),
                    tunType, trunkInterfaceName);
            t.merge(LogicalDatastoreType.CONFIGURATION, path, tnl, true);
        }
        futures.add(t.submit());
    }
    return futures;
}

From source file:org.opendaylight.vpnservice.itm.impl.ItmUtils.java

public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
    Preconditions.checkNotNull(schema);/*  www  .j a v a  2 s  . com*/
    Preconditions.checkArgument(StringUtils.isNotBlank(schema.getSchemaName()));
    Preconditions.checkArgument(StringUtils.isNotBlank(schema.getPortName()));
    Preconditions.checkArgument((schema.getVlanId() >= 0 && schema.getVlanId() < 4095),
            "Invalid VLAN ID, range (0-4094)");
    Preconditions.checkArgument(StringUtils.isNotBlank(schema.getTransportZoneName()));
    Preconditions.checkNotNull(schema.getSubnet());
    String subnetCidr = getSubnetCidrAsString(schema.getSubnet());
    SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);
    IpAddress gatewayIp = schema.getGatewayIp();
    if (gatewayIp != null) {
        String strGatewayIp = String.valueOf(gatewayIp.getValue());
        if (!strGatewayIp.equals(ITMConstants.DUMMY_IP_ADDRESS)
                && !subnetUtils.getInfo().isInRange(strGatewayIp)) {
            Preconditions.checkArgument(false, new StringBuilder("Gateway IP address ").append(strGatewayIp)
                    .append(" is not in subnet range ").append(subnetCidr).toString());
        }
    }
    ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
    return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
}

From source file:org.opendaylight.vpnservice.itm.listeners.VtepConfigSchemaListener.java

/**
 * Calculate available IPs from the subnet mask specified in the schema.
 * Pushes the available and allocated IP address to config DS.
 *
 * @param schema/*from  w  w  w . jav a2  s. c  o  m*/
 *            the schema
 */
private VtepIpPool processAvailableIps(final VtepConfigSchema schema) {
    String subnetCidr = ItmUtils.getSubnetCidrAsString(schema.getSubnet());
    SubnetUtils subnetUtils = new SubnetUtils(subnetCidr);

    List<IpAddress> availableIps = calculateAvailableIps(subnetUtils, schema.getExcludeIpFilter(),
            schema.getGatewayIp());
    VtepIpPool vtepIpPool = new VtepIpPoolBuilder().setSubnetCidr(subnetCidr)
            .setAvailableIpaddress(availableIps).setAllocatedIpaddress(new ArrayList<IpAddress>()).build();

    MDSALUtil.syncWrite(this.dataBroker, LogicalDatastoreType.CONFIGURATION,
            ItmUtils.getVtepIpPoolIdentifier(subnetCidr), vtepIpPool);
    LOG.info("Vtep IP Pool with key:{} added to config DS", subnetCidr);
    return vtepIpPool;
}

From source file:org.opendaylight.vpnservice.natservice.internal.NaptManager.java

/**
 * this method is used to inform this service of what external IP address to be used
 * as mapping when requested one for the internal IP address given in the input
 * @param segmentId  segmentation in which the mapping to be used. Eg; routerid
 * @param internal subnet prefix or ip address
 * @param external subnet prefix or ip address
 *///from   ww  w  .  j  av  a  2  s  .  c  o m

public void registerMapping(long segmentId, IPAddress internal, IPAddress external) {

    LOG.debug(
            "NAPT Service : registerMapping called with segmentid {}, internalIp {}, prefix {}, externalIp {} and prefix {} ",
            segmentId, internal.getIpAddress(), internal.getPrefixLength(), external.getIpAddress(),
            external.getPrefixLength());
    // Create Pool per ExternalIp and not for all IPs in the subnet. Create new Pools during getExternalAddressMapping if exhausted.
    String externalIpPool;
    if (external.getPrefixLength() != 0 && external.getPrefixLength() != NatConstants.DEFAULT_PREFIX) { // subnet case
        String externalSubnet = new StringBuilder(64).append(external.getIpAddress()).append("/")
                .append(external.getPrefixLength()).toString();
        LOG.debug("NAPT Service : externalSubnet is : {}", externalSubnet);
        SubnetUtils subnetUtils = new SubnetUtils(externalSubnet);
        SubnetInfo subnetInfo = subnetUtils.getInfo();
        externalIpPool = subnetInfo.getLowAddress();
    } else { // ip case
        externalIpPool = external.getIpAddress();
    }
    createNaptPortPool(externalIpPool);

    // Store the ip to ip map in Operational DS
    String internalIp = internal.getIpAddress();
    if (internal.getPrefixLength() != 0) {
        internalIp = new StringBuilder(64).append(internal.getIpAddress()).append("/")
                .append(internal.getPrefixLength()).toString();
    }
    String externalIp = external.getIpAddress();
    if (external.getPrefixLength() != 0) {
        externalIp = new StringBuilder(64).append(external.getIpAddress()).append("/")
                .append(external.getPrefixLength()).toString();
    }
    updateCounter(segmentId, externalIp, true);
    //update the actual ip-map
    IpMap ipm = new IpMapBuilder().setKey(new IpMapKey(internalIp)).setInternalIp(internalIp)
            .setExternalIp(externalIp).build();
    MDSALUtil.syncWrite(broker, LogicalDatastoreType.OPERATIONAL, getIpMapIdentifier(segmentId, internalIp),
            ipm);
    LOG.debug("NAPT Service : registerMapping exit after updating DS with internalIP {}, externalIP {}",
            internalIp, externalIp);
}