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

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

Introduction

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

Prototype

public final SubnetInfo getInfo() 

Source Link

Document

Return a SubnetInfo instance that contains subnet-specific statistics

Usage

From source file:org.openhab.binding.dscalarm.internal.discovery.EnvisalinkBridgeDiscovery.java

/**
 * Method for Bridge Discovery./*from   ww w .j  a  v a  2s.  c o 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 ww w. ja v a 2 s  .c om*/
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
 *//*from  ww  w  . j  a v  a  2s  .  co  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
 *//* w ww.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   ww  w .j a v  a2s . com
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./*from   ww  w.  java 2s  .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;
}

From source file:org.openhab.binding.plclogo.internal.discovery.PLCDiscoveryService.java

@Override
protected void startScan() {
    stopScan();/* w  w  w  . java  2  s .  c o  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 ww.j  a v a 2  s  .co 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 {/*ww w .  j av a  2 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 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 a v a 2  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());
    }
}