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.netvirt.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
 *///  w  w  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;
    // subnet case
    if (external.getPrefixLength() != 0 && external.getPrefixLength() != NatConstants.DEFAULT_PREFIX) {
        String externalSubnet = external.getIpAddress() + "/" + external.getPrefixLength();
        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 = internal.getIpAddress() + "/" + internal.getPrefixLength();
    }
    String externalIp = external.getIpAddress();
    if (external.getPrefixLength() != 0) {
        externalIp = external.getIpAddress() + "/" + external.getPrefixLength();
    }
    updateCounter(segmentId, externalIp, true);
    //update the actual ip-map
    IpMap ipm = new IpMapBuilder().setKey(new IpMapKey(internalIp)).setInternalIp(internalIp)
            .setExternalIp(externalIp).build();
    MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.OPERATIONAL, getIpMapIdentifier(segmentId, internalIp),
            ipm);
    LOG.debug("NAPT Service : registerMapping exit after updating DS with internalIP {}, externalIP {}",
            internalIp, externalIp);
}

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

/**
 * method to get external ip/port mapping when provided with internal ip/port pair
 * If already a mapping exist for the given input, then the existing mapping is returned
 * instead of overwriting with new ip/port pair.
 *
 * @param segmentId     - Router ID/*from  ww  w .  j a v  a  2 s.co  m*/
 * @param sourceAddress - internal ip address/port pair
 * @param protocol      - TCP/UDP
 * @return external ip address/port
 */
// TODO Clean up the exception handling
@SuppressWarnings("checkstyle:IllegalCatch")
public SessionAddress getExternalAddressMapping(long segmentId, SessionAddress sourceAddress,
        NAPTEntryEvent.Protocol protocol) {
    LOG.debug("NAPT Service : getExternalAddressMapping called with segmentId {}, internalIp {} and port {}",
            segmentId, sourceAddress.getIpAddress(), sourceAddress.getPortNumber());
    /*
     1. Get Internal IP, Port in IP:Port format
     2. Inside DB with routerId get the list of entries and check if it matches with existing IP:Port
     3. If True return SessionAddress of ExternalIp and Port
     4. Else check ip Map and Form the ExternalIp and Port and update DB and then return ExternalIp and Port
     */

    //SessionAddress externalIpPort = new SessionAddress();
    String internalIpPort = sourceAddress.getIpAddress() + ":" + sourceAddress.getPortNumber();

    // First check existing Port Map.
    SessionAddress existingIpPort = checkIpPortMap(segmentId, internalIpPort, protocol);
    if (existingIpPort != null) {
        // populate externalIpPort from IpPortMap and return
        LOG.debug("NAPT Service : getExternalAddressMapping successfully returning existingIpPort as {} and {}",
                existingIpPort.getIpAddress(), existingIpPort.getPortNumber());
        return existingIpPort;
    } else {
        // Now check in ip-map
        String externalIp = checkIpMap(segmentId, sourceAddress.getIpAddress());
        if (externalIp == null) {
            LOG.error("NAPT Service : getExternalAddressMapping, Unexpected error, internal to external "
                    + "ip map does not exist");
            return null;
        } else {
            /* Logic assuming internalIp is always ip and not subnet
             * case 1: externalIp is ip
             *        a) goto externalIp pool and getPort and return
             *        b) else return error
             * case 2: externalIp is subnet
             *        a) Take first externalIp and goto that Pool and getPort
             *             if port -> return
             *             else Take second externalIp and create that Pool and getPort
             *             if port ->return
             *             else
             *             Continue same with third externalIp till we exhaust subnet
             *        b) Nothing worked return error
             */
            SubnetUtils externalIpSubnet;
            List<String> allIps = new ArrayList<>();
            String subnetPrefix = "/" + String.valueOf(NatConstants.DEFAULT_PREFIX);
            if (!externalIp.contains(subnetPrefix)) {
                EXTSUBNET_FLAG = true;
                externalIpSubnet = new SubnetUtils(externalIp);
                allIps = Arrays.asList(externalIpSubnet.getInfo().getAllAddresses());
                LOG.debug("NAPT Service : total count of externalIps available {}",
                        externalIpSubnet.getInfo().getAddressCount());
            } else {
                LOG.debug("NAPT Service : getExternalAddress single ip case");
                if (externalIp.contains(subnetPrefix)) {
                    //remove /32 what we got from checkIpMap
                    externalIp = externalIp.substring(0, externalIp.indexOf(subnetPrefix));
                }
                allIps.add(externalIp);
            }

            for (String extIp : allIps) {
                LOG.info("NAPT Service : Looping externalIPs with externalIP now as {}", extIp);
                if (NEXT_EXTIP_FLAG) {
                    createNaptPortPool(extIp);
                    LOG.debug("NAPT Service : Created Pool for next Ext IP {}", extIp);
                }
                AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(extIp)
                        .setIdKey(internalIpPort).build();
                try {
                    Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
                    RpcResult<AllocateIdOutput> rpcResult;
                    if ((result != null) && (result.get().isSuccessful())) {
                        LOG.debug("NAPT Service : Got id from idManager");
                        rpcResult = result.get();
                    } else {
                        LOG.error("NAPT Service : getExternalAddressMapping, idManager could not "
                                + "allocate id retry if subnet");
                        if (!EXTSUBNET_FLAG) {
                            LOG.error(
                                    "NAPT Service : getExternalAddressMapping returning null for single IP case,"
                                            + " may be ports exhausted");
                            return null;
                        }
                        LOG.debug("NAPT Service : Could be ports exhausted case, try with another externalIP"
                                + " if possible");
                        NEXT_EXTIP_FLAG = true;
                        continue;
                    }
                    int extPort = rpcResult.getResult().getIdValue().intValue();
                    // Write to ip-port-map before returning
                    IpPortExternalBuilder ipExt = new IpPortExternalBuilder();
                    IpPortExternal ipPortExt = ipExt.setIpAddress(extIp).setPortNum(extPort).build();
                    IpPortMap ipm = new IpPortMapBuilder().setKey(new IpPortMapKey(internalIpPort))
                            .setIpPortInternal(internalIpPort).setIpPortExternal(ipPortExt).build();
                    LOG.debug(
                            "NAPT Service : getExternalAddressMapping writing into ip-port-map with "
                                    + "externalIP {} and port {}",
                            ipPortExt.getIpAddress(), ipPortExt.getPortNum());
                    try {
                        MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION,
                                getIpPortMapIdentifier(segmentId, internalIpPort, protocol), ipm);
                    } catch (UncheckedExecutionException uee) {
                        LOG.error("NAPT Service : Failed to write into ip-port-map with exception {}",
                                uee.getMessage());
                    }

                    // Write to snat-internal-ip-port-info
                    String internalIpAddress = sourceAddress.getIpAddress();
                    int ipPort = sourceAddress.getPortNumber();
                    ProtocolTypes protocolType = NatUtil.getProtocolType(protocol);
                    List<Integer> portList = NatUtil.getInternalIpPortListInfo(dataBroker, segmentId,
                            internalIpAddress, protocolType);
                    if (portList == null) {
                        portList = new ArrayList<>();
                    }
                    portList.add(ipPort);

                    IntIpProtoTypeBuilder builder = new IntIpProtoTypeBuilder();
                    IntIpProtoType intIpProtocolType = builder.setKey(new IntIpProtoTypeKey(protocolType))
                            .setPorts(portList).build();
                    try {
                        MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION, NatUtil
                                .buildSnatIntIpPortIdentifier(segmentId, internalIpAddress, protocolType),
                                intIpProtocolType);
                    } catch (Exception ex) {
                        LOG.error("NAPT Service : Failed to write into snat-internal-ip-port-info with "
                                + "exception {}", ex.getMessage());
                    }

                    SessionAddress externalIpPort = new SessionAddress(extIp, extPort);
                    LOG.debug(
                            "NAPT Service : getExternalAddressMapping successfully returning externalIP {} "
                                    + "and port {}",
                            externalIpPort.getIpAddress(), externalIpPort.getPortNumber());
                    return externalIpPort;
                } catch (InterruptedException | ExecutionException e) {
                    LOG.error("NAPT Service : getExternalAddressMapping, Exception caught  {}", e);
                    return null;
                }
            } // end of for loop
        } // end of else ipmap present
    } // end of else check ipmap
    LOG.error(
            "NAPT Service: getExternalAddressMapping returning null, nothing worked or externalIPs exhausted");
    return null;
}

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

protected String checkIpMap(long segmentId, String internalIp) {
    LOG.debug("NAPT Service : checkIpMap called with segmentId {} and internalIp {}", segmentId, internalIp);
    String externalIp;//w  ww .ja va2  s.c o  m
    // check if ip-map node is there
    InstanceIdentifierBuilder<IpMapping> idBuilder = InstanceIdentifier.builder(IntextIpMap.class)
            .child(IpMapping.class, new IpMappingKey(segmentId));
    InstanceIdentifier<IpMapping> id = idBuilder.build();
    Optional<IpMapping> ipMapping = MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, id);
    if (ipMapping.isPresent()) {
        List<IpMap> ipMaps = ipMapping.get().getIpMap();
        for (IpMap ipMap : ipMaps) {
            if (ipMap.getInternalIp().equals(internalIp)) {
                LOG.debug("NAPT Service : IpMap : {}", ipMap);
                externalIp = ipMap.getExternalIp();
                LOG.debug("NAPT Service : checkIpMap successfully returning externalIp {}", externalIp);
                return externalIp;
            } else if (ipMap.getInternalIp().contains("/")) { // subnet case
                SubnetUtils subnetUtils = new SubnetUtils(ipMap.getInternalIp());
                SubnetInfo subnetInfo = subnetUtils.getInfo();
                if (subnetInfo.isInRange(internalIp)) {
                    LOG.debug("NAPT Service : internalIp {} found to be IpMap of internalIpSubnet {}",
                            internalIp, ipMap.getInternalIp());
                    externalIp = ipMap.getExternalIp();
                    LOG.debug("NAPT Service : checkIpMap successfully returning externalIp {}", externalIp);
                    return externalIp;
                }
            }
        }
    }
    // return null if not found
    LOG.error("NAPT Service : checkIpMap failed, returning NULL for segmentId {} and internalIp {}", segmentId,
            internalIp);
    return null;
}

From source file:org.opendaylight.netvirt.openstack.netvirt.providers.openflow13.services.RoutingService.java

@Override
public Status programRouterInterface(Long dpid, String sourceSegId, String destSegId, String macAddress,
        InetAddress address, int mask, Action action) {
    if (address instanceof Inet6Address) {
        // WORKAROUND: For now ipv6 is not supported
        // TODO: implement ipv6 case
        LOG.debug("ipv6 address is not implemented yet. address {}", address);
        return new Status(StatusCode.NOTIMPLEMENTED);
    }/*from  ww  w  . java  2  s  . c  o  m*/

    SubnetUtils addressSubnetInfo = new SubnetUtils(address.getHostAddress() + "/" + mask);
    final String prefixString = addressSubnetInfo.getInfo().getNetworkAddress() + "/" + mask;

    NodeBuilder nodeBuilder = FlowUtils.createNodeBuilder(dpid);
    FlowBuilder flowBuilder = new FlowBuilder();
    String flowName = "Routing_" + sourceSegId + "_" + destSegId + "_" + prefixString;
    FlowUtils.initFlowBuilder(flowBuilder, flowName, getTable()).setPriority(2048);

    boolean isExternalNet = sourceSegId.equals(Constants.EXTERNAL_NETWORK);
    MatchBuilder matchBuilder = new MatchBuilder();
    if (isExternalNet) {
        // If matching on external network, use register reserved for InboundNatService to ensure that
        // ip rewrite is meant to be consumed by this destination tunnel id.
        MatchUtils.addNxRegMatch(matchBuilder,
                new MatchUtils.RegMatch(InboundNatService.REG_FIELD, Long.valueOf(destSegId)));
    } else {
        MatchUtils.createTunnelIDMatch(matchBuilder, new BigInteger(sourceSegId));
    }

    MatchUtils.createDstL3IPv4Match(matchBuilder, new Ipv4Prefix(prefixString));
    flowBuilder.setMatch(matchBuilder.build());

    if (action.equals(Action.ADD)) {
        // Instructions List Stores Individual Instructions
        InstructionsBuilder isb = new InstructionsBuilder();
        List<Instruction> instructions = new ArrayList<>();
        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 = new ArrayList<>();

        //if this is an east<->west route, save the src mac in case this is an ICMP echo request
        if (!isExternalNet) {
            ab.setAction(ActionUtils.nxMoveRegAction(
                    new SrcOfEthSrcCaseBuilder().setOfEthSrc(Boolean.TRUE).build(), new DstNxRegCaseBuilder()
                            .setNxReg(IcmpEchoResponderService.SRC_MAC_4_HIGH_BYTES_FIELD).build(),
                    0, 0, 31, false));
            ab.setOrder(actionList.size());
            ab.setKey(new ActionKey(actionList.size()));
            actionList.add(ab.build());

            ab.setAction(ActionUtils.nxMoveRegAction(
                    new SrcOfEthSrcCaseBuilder().setOfEthSrc(Boolean.TRUE).build(), new DstNxRegCaseBuilder()
                            .setNxReg(IcmpEchoResponderService.SRC_MAC_2_LOW_BYTES_FIELD).build(),
                    32, 0, 15, false));
            ab.setOrder(actionList.size());
            ab.setKey(new ActionKey(actionList.size()));
            actionList.add(ab.build());
        }

        // Set source Mac address
        ab.setAction(ActionUtils.setDlSrcAction(new MacAddress(macAddress)));
        ab.setOrder(actionList.size());
        ab.setKey(new ActionKey(actionList.size()));
        actionList.add(ab.build());

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

        // Set Destination Tunnel ID
        ab.setAction(ActionUtils.setTunnelIdAction(new BigInteger(destSegId)));
        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(0);
        ib.setKey(new InstructionKey(0));
        instructions.add(ib.build());

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

        flowBuilder.setInstructions(isb.setInstruction(instructions).build());
        writeFlow(flowBuilder, nodeBuilder);
    } else {
        removeFlow(flowBuilder, nodeBuilder);
    }

    // ToDo: WriteFlow/RemoveFlow should return something we can use to check success
    return new Status(StatusCode.SUCCESS);
}

From source file:org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet.java

public boolean isValidCIDR() {
    // fix for Bug 2290 - need to wrap the existing test as
    // IPv4 because SubnetUtils doesn't support IPv6
    if (ipVersion == IPV4_VERSION) {
        try {/* w  w  w . j  a v a 2s.  c  o  m*/
            SubnetUtils util = new SubnetUtils(cidr);
            SubnetInfo info = util.getInfo();
            if (!info.getNetworkAddress().equals(info.getAddress())) {
                return false;
            }
        } catch (IllegalArgumentException e) {
            LOGGER.warn("Failure in isValidCIDR()", e);
            return false;
        }
        return true;
    }
    if (ipVersion == IPV6_VERSION) {
        // fix for Bug2290 - this is custom code because no classes
        // with ODL-friendly licenses have been found
        // extract address (in front of /) and length (after /)
        String[] parts = cidr.split("/");
        if (parts.length != 2) {
            return false;
        }
        try {
            int length = Integer.parseInt(parts[1]);
            //TODO?: limit check on length
            // convert to byte array
            byte[] addrBytes = InetAddress.getByName(parts[0]).getAddress();
            int i;
            for (i = length; i < IPV6_LENGTH; i++) {
                if (((((int) addrBytes[i / IPV6_LENGTH_BYTES]) & IPV6_LSB_MASK)
                        & (1 << (IPV6_BYTE_OFFSET - (i % IPV6_LENGTH_BYTES)))) != 0) {
                    return (false);
                }
            }
            return (true);
        } catch (UnknownHostException e) {
            LOGGER.warn("Failure in isValidCIDR()", e);
            return (false);
        }
    }
    return false;
}

From source file:org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet.java

public boolean initDefaults() {
    if (enableDHCP == null) {
        enableDHCP = true;// w  w w .  j a  v a 2  s . c  o  m
    }
    if (ipVersion == null) {
        ipVersion = IPV4_VERSION;
    }
    dnsNameservers = new ArrayList<>();
    if (hostRoutes == null) {
        hostRoutes = new ArrayList<>();
    }
    if (allocationPools == null) {
        allocationPools = new ArrayList<>();
        if (ipVersion == IPV4_VERSION) {
            try {
                SubnetUtils util = new SubnetUtils(cidr);
                SubnetInfo info = util.getInfo();
                if (gatewayIP == null || ("").equals(gatewayIP)) {
                    gatewayIP = info.getLowAddress();
                }
                if (allocationPools.size() < 1) {
                    NeutronSubnetIPAllocationPool source = new NeutronSubnetIPAllocationPool(
                            info.getLowAddress(), info.getHighAddress());
                    allocationPools = source.splitPool(gatewayIP);
                }
            } catch (IllegalArgumentException e) {
                LOGGER.warn("Failure in initDefault()", e);
                return false;
            }
        }
        if (ipVersion == IPV6_VERSION) {
            String[] parts = cidr.split("/");
            if (parts.length != 2) {
                return false;
            }
            try {
                int length = Integer.parseInt(parts[1]);
                BigInteger lowAddress_bi = NeutronSubnetIPAllocationPool.convertV6(parts[0]);
                String lowAddress = NeutronSubnetIPAllocationPool
                        .bigIntegerToIP(lowAddress_bi.add(BigInteger.ONE));
                BigInteger mask = BigInteger.ONE.shiftLeft(length).subtract(BigInteger.ONE);
                String highAddress = NeutronSubnetIPAllocationPool
                        .bigIntegerToIP(lowAddress_bi.add(mask).subtract(BigInteger.ONE));
                if (gatewayIP == null || ("").equals(gatewayIP)) {
                    gatewayIP = lowAddress;
                }
                if (allocationPools.size() < 1) {
                    NeutronSubnetIPAllocationPool source = new NeutronSubnetIPAllocationPool(lowAddress,
                            highAddress);
                    allocationPools = source.splitPoolV6(gatewayIP);
                }
            } catch (Exception e) {
                LOGGER.warn("Failure in initDefault()", e);
                return false;
            }
        }
    }
    return true;
}

From source file:org.opendaylight.netvirt.openstack.netvirt.translator.NeutronSubnet.java

public boolean isValidIP(String ipAddress) {
    if (ipVersion == IPV4_VERSION) {
        try {//from w  ww . j  a va 2s  .  c o  m
            SubnetUtils util = new SubnetUtils(cidr);
            SubnetInfo info = util.getInfo();
            return info.isInRange(ipAddress);
        } catch (IllegalArgumentException e) {
            LOGGER.warn("Failure in isValidIP()", e);
            return false;
        }
    }

    if (ipVersion == IPV6_VERSION) {
        String[] parts = cidr.split("/");
        try {
            int length = Integer.parseInt(parts[1]);
            byte[] cidrBytes = InetAddress.getByName(parts[0]).getAddress();
            byte[] ipBytes = InetAddress.getByName(ipAddress).getAddress();
            int i;
            for (i = 0; i < length; i++) {
                if (((((int) cidrBytes[i / IPV6_LENGTH_BYTES]) & IPV6_LSB_MASK) & (1 << (IPV6_BYTE_OFFSET
                        - (i % IPV6_LENGTH_BYTES)))) != ((((int) ipBytes[i / IPV6_LENGTH_BYTES])
                                & IPV6_LSB_MASK) & (1 << (IPV6_BYTE_OFFSET - (i % IPV6_LENGTH_BYTES))))) {
                    return (false);
                }
            }
            return (true);
        } catch (UnknownHostException e) {
            LOGGER.warn("Failure in isValidIP()", e);
            return (false);
        }
    }
    return false;
}

From source file:org.opendaylight.neutron.spi.NeutronSubnet.java

public boolean isValidCIDR() {
    // fix for Bug 2290 - need to wrap the existing test as
    // IPv4 because SubnetUtils doesn't support IPv6
    if (ipVersion == IPV4_VERSION) {
        try {/*from ww  w  .  ja v a2  s . c  om*/
            SubnetUtils util = new SubnetUtils(cidr);
            SubnetInfo info = util.getInfo();
            if (!info.getNetworkAddress().equals(info.getAddress())) {
                return false;
            }
        } catch (IllegalArgumentException e) {
            LOGGER.warn("Failure in isValidCIDR()", e);
            return false;
        }
        return true;
    }
    if (ipVersion == IPV6_VERSION) {
        // fix for Bug2290 - this is custom code because no classes
        // with ODL-friendly licenses have been found
        // extract address (in front of /) and length (after /)
        String[] parts = cidr.split("/");
        if (parts.length != 2) {
            return false;
        }
        try {
            int length = Integer.parseInt(parts[1]);
            //TODO?: limit check on length
            // convert to byte array
            byte[] addrBytes = ((Inet6Address) InetAddress.getByName(parts[0])).getAddress();
            for (int index = length; index < IPV6_LENGTH; index++) {
                if (((((int) addrBytes[index / IPV6_LENGTH_BYTES]) & IPV6_LSB_MASK)
                        & (1 << (IPV6_BYTE_OFFSET - (index % IPV6_LENGTH_BYTES)))) != 0) {
                    return (false);
                }
            }
            return (true);
        } catch (UnknownHostException e) {
            LOGGER.warn("Failure in isValidCIDR()", e);
            return (false);
        }
    }
    return false;
}

From source file:org.opendaylight.neutron.spi.NeutronSubnet.java

@Override
public void initDefaults() {
    if (enableDHCP == null) {
        enableDHCP = true;//from   w w w .  j  av a2s.c  o  m
    }
    if (ipVersion == null) {
        ipVersion = IPV4_VERSION;
    }
    if (dnsNameservers == null) {
        dnsNameservers = new ArrayList<String>();
    }
    if (hostRoutes == null) {
        hostRoutes = new ArrayList<NeutronRoute>();
    }
    if (allocationPools == null) {
        allocationPools = new ArrayList<NeutronSubnetIpAllocationPool>();
        if (ipVersion == IPV4_VERSION) {
            try {
                SubnetUtils util = new SubnetUtils(cidr);
                SubnetInfo info = util.getInfo();
                if (gatewayIp == null || ("").equals(gatewayIp)) {
                    gatewayIp = info.getLowAddress();
                }
                if (allocationPools.size() < 1) {
                    NeutronSubnetIpAllocationPool source = new NeutronSubnetIpAllocationPool(
                            info.getLowAddress(), info.getHighAddress());
                    allocationPools = source.splitPool(gatewayIp);
                }
            } catch (IllegalArgumentException e) {
                LOGGER.warn("Failure in initDefault()", e);
                return;
            }
        }
        if (ipVersion == IPV6_VERSION) {
            String[] parts = cidr.split("/");
            if (parts.length != 2) {
                return;
            }

            int length = Integer.parseInt(parts[1]);
            BigInteger lowAddressBi = NeutronSubnetIpAllocationPool.convertV6(parts[0]);
            String lowAddress = NeutronSubnetIpAllocationPool.bigIntegerToIp(lowAddressBi.add(BigInteger.ONE));
            BigInteger mask = BigInteger.ONE.shiftLeft(length).subtract(BigInteger.ONE);
            String highAddress = NeutronSubnetIpAllocationPool
                    .bigIntegerToIp(lowAddressBi.add(mask).subtract(BigInteger.ONE));
            if (gatewayIp == null || ("").equals(gatewayIp)) {
                gatewayIp = lowAddress;
            }
            if (allocationPools.size() < 1) {
                NeutronSubnetIpAllocationPool source = new NeutronSubnetIpAllocationPool(lowAddress,
                        highAddress);
                allocationPools = source.splitPoolV6(gatewayIp);
            }
        }
    }
}

From source file:org.opendaylight.neutron.spi.NeutronSubnet.java

public boolean isValidIp(String ipAddress) {
    if (ipVersion == IPV4_VERSION) {
        try {//from   ww w.  j  a  va  2  s  .c om
            SubnetUtils util = new SubnetUtils(cidr);
            SubnetInfo info = util.getInfo();
            return info.isInRange(ipAddress);
        } catch (IllegalArgumentException e) {
            LOGGER.warn("Failure in isValidIp()", e);
            return false;
        }
    }

    if (ipVersion == IPV6_VERSION) {
        String[] parts = cidr.split("/");
        try {
            int length = Integer.parseInt(parts[1]);
            byte[] cidrBytes = ((Inet6Address) InetAddress.getByName(parts[0])).getAddress();
            byte[] ipBytes = ((Inet6Address) InetAddress.getByName(ipAddress)).getAddress();
            for (int index = 0; index < length; index++) {
                if (((((int) cidrBytes[index / IPV6_LENGTH_BYTES]) & IPV6_LSB_MASK) & (1 << (IPV6_BYTE_OFFSET
                        - (index % IPV6_LENGTH_BYTES)))) != ((((int) ipBytes[index / IPV6_LENGTH_BYTES])
                                & IPV6_LSB_MASK) & (1 << (IPV6_BYTE_OFFSET - (index % IPV6_LENGTH_BYTES))))) {
                    return (false);
                }
            }
            return (true);
        } catch (UnknownHostException e) {
            LOGGER.warn("Failure in isValidIp()", e);
            return (false);
        }
    }
    return false;
}