List of usage examples for org.apache.commons.net.util SubnetUtils SubnetUtils
public SubnetUtils(String cidrNotation)
From source file:org.opendaylight.vpnservice.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//from ww w . j a v a2s . co m * @param sourceAddress - internal ip address/port pair * @return external ip address/port */ 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 = new StringBuilder(64).append(sourceAddress.getIpAddress()).append(":") .append(sourceAddress.getPortNumber()).toString(); // 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>(); 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)) { String[] externalIpSplit = externalIp.split("/"); String extIp = externalIpSplit[0]; externalIp = extIp; //remove /32 what we got from checkIpMap } 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(); SessionAddress externalIpPort = new SessionAddress(extIp, extPort); // 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(broker, 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(broker, segmentId, internalIpAddress, protocolType); if (portList == null) { portList = Lists.newArrayList(); } portList.add(ipPort); IntIpProtoTypeBuilder builder = new IntIpProtoTypeBuilder(); IntIpProtoType intIpProtocolType = builder.setKey(new IntIpProtoTypeKey(protocolType)) .setPorts(portList).build(); try { MDSALUtil.syncWrite(broker, 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()); } 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.vpnservice.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 .j a v a 2s .co 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(broker, 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().toString(); 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().toString(); 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.vtn.javaapi.openstack.convertor.StaticRouteResourceGenerator.java
/** * Convert response for static-ip-route from UNC format to OpenStack format * /*from ww w . j a v a 2 s. c om*/ * @param responseBody * - UNC formatted response body * @return - OpenStack formatted response body */ public static JsonObject convertListResponseBody(JsonObject responseBody) { final JsonObject openStackResponse = new JsonObject(); final JsonArray routes = new JsonArray(); final JsonArray staticRoutes = responseBody.get(VtnServiceJsonConsts.STATIC_IPROUTES).getAsJsonArray(); for (final JsonElement staticRoute : staticRoutes) { final String[] staticIpRouteId = staticRoute.getAsJsonObject().get(VtnServiceJsonConsts.STATICIPROUTEID) .getAsString().split(VtnServiceConsts.HYPHEN); final String destination = staticIpRouteId[0] + VtnServiceConsts.SLASH + staticIpRouteId[2]; final String nexthop = staticIpRouteId[1]; String routeId = null; if (staticIpRouteId[2].equals(VtnServiceConsts.ZERO)) { routeId = staticIpRouteId[0] + VtnServiceConsts.HYPHEN + staticIpRouteId[1] + VtnServiceConsts.HYPHEN + VtnServiceConsts.DEFAULT_IP; } else { final SubnetUtils subnetUtils = new SubnetUtils(destination); routeId = staticIpRouteId[0] + VtnServiceConsts.HYPHEN + staticIpRouteId[1] + VtnServiceConsts.HYPHEN + subnetUtils.getInfo().getNetmask(); } final JsonObject route = new JsonObject(); route.addProperty(VtnServiceOpenStackConsts.ID, routeId); route.addProperty(VtnServiceOpenStackConsts.DESTNATION, destination); route.addProperty(VtnServiceOpenStackConsts.NEXTHOP, nexthop); routes.add(route); } openStackResponse.add(VtnServiceOpenStackConsts.ROUTES, routes); return openStackResponse; }
From source file:org.opendaylight.vtn.javaapi.resources.openstack.RoutesResource.java
/** * Generate UNC formatted route_id//from ww w.j a va 2 s. c om * * @param requestBody * - OpenStack request body * @return - generated route_id */ private String convertRouteId(JsonObject requestBody) { String destination = requestBody.get(VtnServiceOpenStackConsts.DESTNATION).getAsString(); String ipAndPrefix[] = destination.split(VtnServiceConsts.SLASH); int prefix = Integer.parseInt(ipAndPrefix[1]); String routeId = null; if (prefix == 0) { routeId = ipAndPrefix[0] + VtnServiceConsts.HYPHEN + requestBody.get(VtnServiceOpenStackConsts.NEXTHOP).getAsString() + VtnServiceConsts.HYPHEN + VtnServiceConsts.DEFAULT_IP; } else { final SubnetUtils subnetUtils = new SubnetUtils(destination); routeId = ipAndPrefix[0] + VtnServiceConsts.HYPHEN + requestBody.get(VtnServiceOpenStackConsts.NEXTHOP).getAsString() + VtnServiceConsts.HYPHEN + subnetUtils.getInfo().getNetmask(); } return routeId; }
From source file:org.openhab.binding.dscalarm.internal.discovery.EnvisalinkBridgeDiscovery.java
/** * Method for Bridge Discovery.//from w w w. j a va 2 s .co m */ public synchronized void discoverBridge() { logger.debug("Starting Envisalink Bridge Discovery."); SubnetUtils subnetUtils = null; SubnetInfo subnetInfo = null; long lowIP = 0; long highIP = 0; try { InetAddress localHost = InetAddress.getLocalHost(); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost); subnetUtils = new SubnetUtils(localHost.getHostAddress() + "/" + networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength()); subnetInfo = subnetUtils.getInfo(); lowIP = convertIPToNumber(subnetInfo.getLowAddress()); highIP = convertIPToNumber(subnetInfo.getHighAddress()); } catch (IllegalArgumentException e) { logger.error("discoverBridge(): Illegal Argument Exception - {}", e.toString()); return; } catch (Exception e) { logger.error("discoverBridge(): Error - Unable to get Subnet Information! {}", e.toString()); return; } logger.debug(" Local IP Address: {} - {}", subnetInfo.getAddress(), convertIPToNumber(subnetInfo.getAddress())); logger.debug(" Subnet: {} - {}", subnetInfo.getNetworkAddress(), convertIPToNumber(subnetInfo.getNetworkAddress())); logger.debug(" Network Prefix: {}", subnetInfo.getCidrSignature().split("/")[1]); logger.debug(" Network Mask: {}", subnetInfo.getNetmask()); logger.debug(" Low IP: {}", convertNumberToIP(lowIP)); logger.debug(" High IP: {}", convertNumberToIP(highIP)); for (long ip = lowIP; ip <= highIP; ip++) { try (Socket socket = new Socket()) { ipAddress = convertNumberToIP(ip); socket.setReuseAddress(true); socket.setReceiveBufferSize(32); socket.connect(new InetSocketAddress(ipAddress, ENVISALINK_BRIDGE_PORT), CONNECTION_TIMEOUT); if (socket.isConnected()) { String message = ""; socket.setSoTimeout(SO_TIMEOUT); try (BufferedReader input = new BufferedReader( new InputStreamReader(socket.getInputStream()))) { message = input.readLine(); } catch (SocketTimeoutException e) { logger.error("discoverBridge(): No Message Read from Socket at [{}] - {}", ipAddress, e.getMessage()); continue; } catch (Exception e) { logger.error("discoverBridge(): Exception Reading from Socket! {}", e.toString()); continue; } if (message.substring(0, 3).equals(ENVISALINK_DISCOVERY_RESPONSE)) { logger.debug("discoverBridge(): Bridge Found - [{}]! Message - '{}'", ipAddress, message); dscAlarmBridgeDiscovery.addEnvisalinkBridge(ipAddress); } else { logger.debug("discoverBridge(): No Response from Connection - [{}]! Message - '{}'", ipAddress, message); } } } catch (IllegalArgumentException e) { logger.error("discoverBridge(): Illegal Argument Exception - {}", e.toString()); } catch (SocketTimeoutException e) { logger.trace("discoverBridge(): No Connection on Port 4025! [{}]", ipAddress); } catch (SocketException e) { logger.error("discoverBridge(): Socket Exception! [{}] - {}", ipAddress, e.toString()); } catch (IOException e) { logger.error("discoverBridge(): IO Exception! [{}] - {}", ipAddress, e.toString()); } } }
From source file:org.openhab.binding.network.internal.utils.NetworkUtils.java
/** * Takes the interfaceIPs and fetches every IP which can be assigned on their network * * @param networkIPs The IPs which are assigned to the Network Interfaces * @param maximumPerInterface The maximum of IP addresses per interface or 0 to get all. * @return Every single IP which can be assigned on the Networks the computer is connected to *///from w ww . j av a 2 s.com public Set<String> getNetworkIPs(Set<String> interfaceIPs, int maximumPerInterface) { LinkedHashSet<String> networkIPs = new LinkedHashSet<>(); for (String string : interfaceIPs) { try { // gets every ip which can be assigned on the given network SubnetUtils utils = new SubnetUtils(string); String[] addresses = utils.getInfo().getAllAddresses(); int len = addresses.length; if (maximumPerInterface != 0 && maximumPerInterface < len) { len = maximumPerInterface; } for (int i = 0; i < len; i++) { networkIPs.add(addresses[i]); } } catch (Exception ex) { } } return networkIPs; }
From source file:org.openhab.binding.network.service.NetworkService.java
/** * Takes the interfaceIPs and fetches every IP which can be assigned on their network * * @param networkIPs The IPs which are assigned to the Network Interfaces * @return Every single IP which can be assigned on the Networks the computer is connected to *//* ww w .j a v a 2s.c o m*/ private static LinkedHashSet<String> getNetworkIPs(TreeSet<String> interfaceIPs) { LinkedHashSet<String> networkIPs = new LinkedHashSet<String>(); for (Iterator<String> it = interfaceIPs.iterator(); it.hasNext();) { try { // gets every ip which can be assigned on the given network SubnetUtils utils = new SubnetUtils(it.next()); String[] addresses = utils.getInfo().getAllAddresses(); for (int i = 0; i < addresses.length; i++) { networkIPs.add(addresses[i]); } } catch (Exception ex) { } } return networkIPs; }
From source file:org.openhab.binding.network.service.NetworkUtils.java
/** * Takes the interfaceIPs and fetches every IP which can be assigned on their network * * @param networkIPs The IPs which are assigned to the Network Interfaces * @return Every single IP which can be assigned on the Networks the computer is connected to *///from ww w . j av a 2s. c om public static LinkedHashSet<String> getNetworkIPs(TreeSet<String> interfaceIPs) { LinkedHashSet<String> networkIPs = new LinkedHashSet<String>(); for (Iterator<String> it = interfaceIPs.iterator(); it.hasNext();) { try { // gets every ip which can be assigned on the given network SubnetUtils utils = new SubnetUtils(it.next()); String[] addresses = utils.getInfo().getAllAddresses(); for (int i = 0; i < addresses.length; i++) { networkIPs.add(addresses[i]); } } catch (Exception ex) { } } return networkIPs; }
From source file:org.openhab.binding.networkhealth.discovery.NetworkHealthDiscoveryService.java
/** * Takes the interfaceIPs and fetches every IP which can be assigned on their network * @param networkIPs The IPs which are assigned to the Network Interfaces * @return Every single IP which can be assigned on the Networks the computer is connected to *///from www . j a va2 s. c om private Queue<String> getNetworkIPs(TreeSet<String> interfaceIPs) { Queue<String> networkIPs = new LinkedBlockingQueue<String>(); for (Iterator<String> it = interfaceIPs.iterator(); it.hasNext();) { try { // gets every ip which can be assigned on the given network SubnetUtils utils = new SubnetUtils(it.next()); String[] addresses = utils.getInfo().getAllAddresses(); for (int i = 0; i < addresses.length; i++) { networkIPs.add(addresses[i]); } } catch (Exception ex) { } } return networkIPs; }
From source file:org.openhab.binding.opensprinkler.discovery.OpenSprinklerDiscoveryService.java
/** * Provide a string list of all the IP addresses associated with the network interfaces on * this machine.//w ww. j a v a2 s. c o m * * @return String list of IP addresses. * @throws UnknownHostException * @throws SocketException */ private List<String> getIpAddressScanList() throws UnknownHostException, SocketException { List<String> results = new ArrayList<String>(); InetAddress localHost = InetAddress.getLocalHost(); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost); for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { InetAddress ipAddress = address.getAddress(); String cidrSubnet = ipAddress.getHostAddress() + "/" + DISCOVERY_SUBNET_MASK; /* Apache Subnet Utils only supports IP v4 for creating string list of IP's */ if (ipAddress instanceof Inet4Address) { logger.debug("Found interface IPv4 address to scan: {}", cidrSubnet); SubnetUtils utils = new SubnetUtils(cidrSubnet); results.addAll(Arrays.asList(utils.getInfo().getAllAddresses())); } else if (ipAddress instanceof Inet6Address) { logger.debug("Found interface IPv6 address to scan: {}", cidrSubnet); } else { logger.debug("Found interface unknown IP type address to scan: {}", cidrSubnet); } } return results; }