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.controller.networkconfig.neutron.NeutronSubnet.java

public boolean isValidIP(String ipAddress) {
    try {//from   ww w. j  a  v  a  2s.  com
        SubnetUtils util = new SubnetUtils(cidr);
        SubnetInfo info = util.getInfo();
        return info.isInRange(ipAddress);
    } catch (Exception e) {
        return false;
    }
}

From source file:org.opendaylight.faas.fabrics.vxlan.adapters.ovs.pipeline.PipelineL3Routing.java

public void programRouterInterface(Long dpid, Long sourceSegId, Long destSegId, String macAddress,
        IpAddress address, int mask, boolean isWriteFlow) {

    String nodeName = Constants.OPENFLOW_NODE_PREFIX + dpid;

    MatchBuilder matchBuilder = new MatchBuilder();
    NodeBuilder nodeBuilder = Openflow13Provider.createNodeBuilder(nodeName);
    FlowBuilder flowBuilder = new FlowBuilder();

    // Instructions List Stores Individual Instructions
    InstructionsBuilder isb = new InstructionsBuilder();
    List<Instruction> instructions = Lists.newArrayList();
    InstructionBuilder ib = new InstructionBuilder();
    ApplyActionsBuilder aab = new ApplyActionsBuilder();
    ActionBuilder ab = new ActionBuilder();
    List<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action> actionList = Lists
            .newArrayList();//w  w  w.jav  a2 s.c  om

    OfMatchUtils.createTunnelIDMatch(matchBuilder, BigInteger.valueOf(sourceSegId.longValue()));

    SubnetUtils addressSubnetInfo = new SubnetUtils(address.getIpv4Address().getValue() + "/" + mask);
    final String prefixString = addressSubnetInfo.getInfo().getNetworkAddress() + "/" + mask;
    OfMatchUtils.createDstL3IPv4Match(matchBuilder, prefixString);

    String flowId = "Routing_" + sourceSegId + "_" + destSegId + "_" + prefixString;
    flowBuilder.setId(new FlowId(flowId));
    FlowKey key = new FlowKey(new FlowId(flowId));
    flowBuilder.setBarrier(true);
    flowBuilder.setTableId(this.getTable());
    flowBuilder.setKey(key);
    flowBuilder.setPriority(BASE_ROUTING_PRIORITY + mask);
    flowBuilder.setFlowName(flowId);
    flowBuilder.setHardTimeout(0);
    flowBuilder.setIdleTimeout(0);
    flowBuilder.setMatch(matchBuilder.build());

    if (isWriteFlow) {
        // Set source Mac address
        ab.setAction(OfActionUtils.setDlSrcAction(macAddress));
        ab.setOrder(actionList.size());
        ab.setKey(new ActionKey(actionList.size()));
        actionList.add(ab.build());

        // DecTTL
        ab.setAction(OfActionUtils.decNwTtlAction());
        ab.setOrder(actionList.size());
        ab.setKey(new ActionKey(actionList.size()));
        actionList.add(ab.build());

        // Set Destination Tunnel ID
        ab.setAction(OfActionUtils.setTunnelIdAction(BigInteger.valueOf(destSegId.longValue())));
        ab.setOrder(actionList.size());
        ab.setKey(new ActionKey(actionList.size()));
        actionList.add(ab.build());

        // Create Apply Actions Instruction
        aab.setAction(actionList);
        ib.setInstruction(new ApplyActionsCaseBuilder().setApplyActions(aab.build()).build());
        ib.setOrder(instructions.size());
        ib.setKey(new InstructionKey(instructions.size()));
        instructions.add(ib.build());

        // Goto Next Table
        ib = getMutablePipelineInstructionBuilder();
        ib.setOrder(instructions.size());
        ib.setKey(new InstructionKey(instructions.size()));
        instructions.add(ib.build());

        flowBuilder.setInstructions(isb.setInstruction(instructions).build());

        writeFlow(flowBuilder, nodeBuilder);
    } else {
        removeFlow(flowBuilder, nodeBuilder);
    }
}

From source file:org.opendaylight.genius.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   ww w  . j  av a 2 s . c  o m*/
        LOG.trace("InValid IP");
        return false;
    }
}

From source file:org.opendaylight.genius.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 transaction = 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,
                    new String(firstEndPt.getIpAddress().getValue()), new String(extIp.getValue()), tunTypeStr);
            char[] subnetMaskArray = firstEndPt.getSubnetMask().getValue();
            boolean useOfTunnel = ItmUtils.falseIfNull(firstEndPt.isOptionOfTunnel());
            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();
            LOG.debug(/*from  w  w  w .j a v a  2s.c  o m*/
                    " 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, ITMConstants.DEFAULT_MONITOR_PROTOCOL, null, useOfTunnel);

            LOG.debug(" Trunk Interface builder - {} ", iface);
            InstanceIdentifier<Interface> trunkIdentifier = ItmUtils.buildId(trunkInterfaceName);
            LOG.debug(" Trunk Interface Identifier - {} ", trunkIdentifier);
            LOG.trace(" Writing Trunk Interface to Config DS {}, {} ", trunkIdentifier, iface);
            transaction.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);
            transaction.merge(LogicalDatastoreType.CONFIGURATION, path, tnl, true);
        }
        futures.add(transaction.submit());
    }
    return futures;
}

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

public static VtepConfigSchema validateVtepConfigSchema(VtepConfigSchema schema) {
    Preconditions.checkNotNull(schema);//w w w . j a  va  2  s  .  c  o  m
    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,
                    "Gateway IP address " + strGatewayIp + " is not in subnet range " + subnetCidr);
        }
    }
    ItmUtils.getExcludeIpAddresses(schema.getExcludeIpFilter(), subnetUtils.getInfo());
    return new VtepConfigSchemaBuilder(schema).setTunnelType(schema.getTunnelType()).build();
}

From source file:org.opendaylight.genius.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/* ww  w . jav a 2 s .c  om*/
 *            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<>()).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.groupbasedpolicy.renderer.ofoverlay.arp.ArpTasker.java

private @Nullable Ipv4Address createSenderIpAddress(EndpointL3 l3Ep, ReadTransaction rTx) {
    Subnet subnetOfL3Ep = readSubnet(l3Ep, rTx);
    if (subnetOfL3Ep == null) {
        return null;
    }/*from w  w w .j a va  2  s .com*/
    SubnetInfo subnetInfo = new SubnetUtils(subnetOfL3Ep.getIpPrefix().getIpv4Prefix().getValue()).getInfo();
    String senderIp = subnetInfo.getHighAddress();
    if (senderIp.equals(l3Ep.getKey().getIpAddress().getIpv4Address().getValue())) {
        senderIp = subnetInfo.getLowAddress();
    }
    return new Ipv4Address(senderIp);
}

From source file:org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.ExternalMapper.java

static boolean belongsToSubnet(Ipv4Address ipv4Address, Ipv4Prefix subnetPrefix) {
    SubnetUtils su = new SubnetUtils(subnetPrefix.getValue());
    SubnetInfo si = su.getInfo();/*from   w ww. jav  a2s  . c  o  m*/
    return si.isInRange(ipv4Address.getValue());
}

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

private void setNonNakOptions(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  ww.ja va2s. 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_ROUTERS, gwIp);
        } else {
            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
        LOG.warn("Failed to set option", e);
    }
}

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

protected byte[] convertToClasslessRouteOption(String dest, String router) {
    ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
    if (dest == null || router == null) {
        return null;
    }// w w w  . ja  v a 2s.  c  om

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

    byteArray.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) {
                byteArray.write(netAddr, i, 1);
            }
        }
        byteArray.write(InetAddress.getByName(router).getAddress());
    } catch (IOException e) {
        return null;
    }
    return byteArray.toByteArray();
}