List of usage examples for org.apache.commons.net.util SubnetUtils SubnetUtils
public SubnetUtils(String cidrNotation)
From source file:org.openhab.binding.plclogo.internal.discovery.PLCDiscoveryService.java
@Override protected void startScan() { stopScan();//from w ww.ja v a2 s . co m logger.debug("Start scan for LOGO! bridge"); Enumeration<NetworkInterface> devices = null; try { devices = NetworkInterface.getNetworkInterfaces(); } catch (SocketException exception) { logger.warn("LOGO! bridge discovering: {}.", exception.toString()); } Set<String> addresses = new TreeSet<>(); while ((devices != null) && devices.hasMoreElements()) { NetworkInterface device = devices.nextElement(); try { if (!device.isUp() || device.isLoopback()) { continue; } } catch (SocketException exception) { logger.warn("LOGO! bridge discovering: {}.", exception.toString()); } for (InterfaceAddress iface : device.getInterfaceAddresses()) { InetAddress address = iface.getAddress(); if (address instanceof Inet4Address) { String prefix = String.valueOf(iface.getNetworkPrefixLength()); SubnetUtils utilities = new SubnetUtils(address.getHostAddress() + "/" + prefix); addresses.addAll(Arrays.asList(utilities.getInfo().getAllAddresses())); } } } ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); for (String address : addresses) { try { executor.execute(new Runner(address)); } catch (RejectedExecutionException exception) { logger.warn("LOGO! bridge discovering: {}.", exception.toString()); } } try { executor.awaitTermination(CONNECTION_TIMEOUT * addresses.size(), TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { logger.warn("LOGO! bridge discovering: {}.", exception.toString()); } executor.shutdown(); stopScan(); }
From source file:org.openhab.binding.russound.internal.discovery.RioSystemDiscovery.java
/** * Starts the scan. For each network interface (that is up and not a loopback), all addresses will be iterated * and checked for something open on port 9621. If that port is open, a russound controller "type" command will be * issued. If the response is a correct pattern, we assume it's a rio system device and will emit a * {{@link #thingDiscovered(DiscoveryResult)} *///from w w w . j a v a 2 s. c o m @Override protected void startScan() { final List<NetworkInterface> interfaces; try { interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); } catch (SocketException e1) { logger.debug("Exception getting network interfaces: {}", e1.getMessage(), e1); return; } nbrNetworkInterfacesScanning = interfaces.size(); executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 10); for (final NetworkInterface networkInterface : interfaces) { try { if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; } } catch (SocketException e) { continue; } for (Iterator<InterfaceAddress> it = networkInterface.getInterfaceAddresses().iterator(); it .hasNext();) { final InterfaceAddress interfaceAddress = it.next(); // don't bother with ipv6 addresses (russound doesn't support) if (interfaceAddress.getAddress() instanceof Inet6Address) { continue; } final String subnetRange = interfaceAddress.getAddress().getHostAddress() + "/" + interfaceAddress.getNetworkPrefixLength(); logger.debug("Scanning subnet: {}", subnetRange); final SubnetUtils utils = new SubnetUtils(subnetRange); final String[] addresses = utils.getInfo().getAllAddresses(); for (final String address : addresses) { executorService.execute(new Runnable() { @Override public void run() { scanAddress(address); } }); } } } // Finishes the scan and cleans up stopScan(); }
From source file:org.openhab.binding.vera.internal.discovery.VeraBridgeDiscoveryService.java
private void scan() { logger.debug("Starting scan for Vera controller"); ValidateIPV4 validator = new ValidateIPV4(); try {//from ww w .jav a2 s . com Enumeration<NetworkInterface> enumNetworkInterface = NetworkInterface.getNetworkInterfaces(); while (enumNetworkInterface.hasMoreElements()) { NetworkInterface networkInterface = enumNetworkInterface.nextElement(); if (networkInterface.isUp() && !networkInterface.isVirtual() && !networkInterface.isLoopback()) { for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { if (validator.isValidIPV4(address.getAddress().getHostAddress())) { String ipAddress = address.getAddress().getHostAddress(); Short prefix = address.getNetworkPrefixLength(); logger.debug("Scan IP address for Vera Controller: {}", ipAddress); String subnet = ipAddress + "/" + prefix; SubnetUtils utils = new SubnetUtils(subnet); String[] addresses = utils.getInfo().getAllAddresses(); for (String addressInSubnet : addresses) { scheduler.execute(new VeraControllerScan(addressInSubnet)); } } } } } } catch (SocketException e) { logger.warn("Error occurred while searching Vera controller: ", e); } }
From source file:org.openhab.binding.zway.internal.discovery.ZWayBridgeDiscoveryService.java
private void scan() { logger.debug("Starting scan for Z-Way Server"); ValidateIPV4 validator = new ValidateIPV4(); try {/*from w w w .j av a2 s. co m*/ Enumeration<NetworkInterface> enumNetworkInterface = NetworkInterface.getNetworkInterfaces(); while (enumNetworkInterface.hasMoreElements()) { NetworkInterface networkInterface = enumNetworkInterface.nextElement(); if (networkInterface.isUp() && !networkInterface.isVirtual() && !networkInterface.isLoopback()) { for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { if (validator.isValidIPV4(address.getAddress().getHostAddress())) { String ipAddress = address.getAddress().getHostAddress(); Short prefix = address.getNetworkPrefixLength(); logger.debug("Scan IP address for Z-Way Server: {}", ipAddress); // Search on localhost first scheduler.execute(new ZWayServerScan(ipAddress)); String subnet = ipAddress + "/" + prefix; SubnetUtils utils = new SubnetUtils(subnet); String[] addresses = utils.getInfo().getAllAddresses(); for (String addressInSubnet : addresses) { scheduler.execute(new ZWayServerScan(addressInSubnet)); } } } } } } catch (SocketException e) { logger.warn("Error occurred while searching Z-Way servers ({})", e.getMessage()); } }
From source file:org.openo.sdnhub.sptndriver.utils.Ipv4Util.java
/** * Transform integer mask to string dot mask. * * @param intMask Integer value of mask, like 24 * @return Mask in form of "255.255.255.0" *//*from w ww . j a v a 2 s .c om*/ private static String ipInt2DotStr(int intMask) { String cidr = "255.255.255.255/" + intMask; SubnetUtils subnet = new SubnetUtils(cidr); return subnet.getInfo().getNetmask(); }
From source file:org.ow2.sirocco.cloudmanager.connector.vcd.VcdCloudProvider.java
VAppNetworkConfigurationType createIsolatedVAppNetworkConfigurationType(final String networkName, final NetworkConfiguration networkConfiguration) throws ConnectorException { VAppNetworkConfigurationType private_vAppNetworkConfigurationType = new VAppNetworkConfigurationType(); NetworkConfigurationType private_networkConfigurationType = new NetworkConfigurationType(); VcdCloudProvider.logger.info("vAppNetworkConfiguration Isolated:" + networkName); private_vAppNetworkConfigurationType.setNetworkName(networkName); // private_networkConfigurationType.setParentNetwork(vdc.getAvailableNetworkRefByName(this.cimiPublicOrgVdcNetworkName)); private_networkConfigurationType.setFenceMode(FenceModeValuesType.ISOLATED.value()); private_networkConfigurationType.setRetainNetInfoAcrossDeployments(true); // Configure Internal IP Settings if (networkConfiguration.getSubnets().size() != 1) { throw new ConnectorException( "validation error on field 'networkConfiguration.subnets.size': should be equal to 1"); }/*from w ww .ja v a2 s . c o m*/ SubnetUtils utils = new SubnetUtils(networkConfiguration.getSubnets().get(0).getCidr()); utils.setInclusiveHostCount(false); SubnetInfo info = utils.getInfo(); if (info.getAddressCount() < 2) { /* gateway @ + IP range @ >= 2 */ throw new ConnectorException("no usable addresses"); } IpScopeType ipScope = new IpScopeType(); /*ipScope.setNetmask("255.255.255.0"); ipScope.setGateway("192.168.2.1");*/ ipScope.setNetmask(info.getNetmask()); ipScope.setGateway(info.getLowAddress()); ipScope.setIsEnabled(true); ipScope.setIsInherited(false); // ??? IpRangesType ipRangesType = new IpRangesType(); IpRangeType ipRangeType = new IpRangeType(); /*ipRangeType.setStartAddress("192.168.2.100"); ipRangeType.setEndAddress("192.168.2.199");*/ ipRangeType.setStartAddress(info.getAllAddresses()[1]); ipRangeType.setEndAddress(info.getHighAddress()); ipRangesType.getIpRange().add(ipRangeType); ipScope.setIpRanges(ipRangesType); ipScope.setIsEnabled(true); IpScopesType ipScopes = new IpScopesType(); ipScopes.getIpScope().add(ipScope); private_networkConfigurationType.setIpScopes(ipScopes); private_vAppNetworkConfigurationType.setConfiguration(private_networkConfigurationType); return private_vAppNetworkConfigurationType; }
From source file:org.ow2.sirocco.cloudmanager.SecurityGroupRuleCreationDialog.java
private boolean fillAndValidate(final SecurityGroupRuleParams ruleParams) { ruleParams.setIpProtocol((String) this.protocolBox.getValue()); if (this.portField.getValue().isEmpty()) { this.errorMessage("Missing port"); return false; }/*w ww. j a v a 2s . co m*/ try { if (this.portField.getValue().contains("-")) { String[] range = this.portField.getValue().split("-"); if (range.length != 2) { this.errorMessage("Invalid port range"); return false; } int fromPort = Integer.parseInt(range[0]); int toPort = Integer.parseInt(range[1]); if (fromPort < 1 || fromPort > 65535 || toPort < 1 || toPort > 65535 || fromPort > toPort) { this.errorMessage("Invalid port range"); return false; } ruleParams.setFromPort(fromPort); ruleParams.setToPort(toPort); } else { int port = Integer.parseInt(this.portField.getValue()); ruleParams.setFromPort(port); ruleParams.setToPort(port); } } catch (NumberFormatException e) { this.errorMessage("Invalid port number"); return false; } if (this.sourceChoice.getValue().equals("CIDR")) { if (this.sourceIpRangeField.getValue().isEmpty()) { this.errorMessage("Missing cidr"); return false; } try { new SubnetUtils(this.sourceIpRangeField.getValue()); } catch (IllegalArgumentException e) { // XXX issue with commons-net library 3.3 if (!this.sourceIpRangeField.getValue().equals("0.0.0.0/0")) { this.errorMessage("Invalid cidr"); return false; } } ruleParams.setSourceIpRange(this.sourceIpRangeField.getValue()); } else { ruleParams.setSourceGroupUuid((String) this.sourceSecGroupBox.getValue()); } return true; }
From source file:org.restcomm.sbc.chain.impl.NATHelperProcessor.java
private boolean isRoutedAddress(String ipAddress) { List<String> localNetworks = ConfigurationCache.getLocalNetworks(); for (String localNetwork : localNetworks) { if (LOG.isTraceEnabled()) { LOG.trace("Traversing localNetworks " + localNetwork); }/*w w w. j a v a 2s . c om*/ SubnetUtils utils = new SubnetUtils(localNetwork); if (utils.getInfo().isInRange(ipAddress)) { if (LOG.isTraceEnabled()) { LOG.trace("ipAddress " + ipAddress + " Is in network " + localNetwork); } return true; } if (LOG.isTraceEnabled()) { LOG.trace("ipAddress " + ipAddress + " Is NOT in network " + localNetwork); } } return false; }
From source file:org.sakaiproject.util.IPAddrUtil.java
/** * Match an address against a list of IP CIDR addresses * /*from w w w.j a v a 2 s.c o m*/ * @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; }
From source file:org.sipfoundry.sipxconfig.time.NtpConfigTest.java
@Test public void writeNtpYaml() throws IOException { StringWriter actual = new StringWriter(); List<String> servers = new ArrayList<String>(); servers.add("0.pool.ntp.org"); servers.add("1.pool.ntp.org"); servers.add("2.pool.ntp.org"); servers.add("3.pool.ntp.org"); List<SubnetInfo> subnetInfo = new ArrayList<SubnetUtils.SubnetInfo>(); subnetInfo.add(new SubnetUtils("192.168.0.5/16").getInfo()); subnetInfo.add(new SubnetUtils("10.5.1.0/32").getInfo()); m_config.writeNtpdConfig(actual, true, servers, true, subnetInfo, true, true, "/var/lib/ntp/drift"); String expected = IOUtils.toString(getClass().getResourceAsStream("ntp-test.yml")); assertEquals(expected, actual.toString()); }