Example usage for java.net InterfaceAddress getNetworkPrefixLength

List of usage examples for java.net InterfaceAddress getNetworkPrefixLength

Introduction

In this page you can find the example usage for java.net InterfaceAddress getNetworkPrefixLength.

Prototype

public short getNetworkPrefixLength() 

Source Link

Document

Returns the network prefix length for this address.

Usage

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  ww.j a  va  2  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 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.openhab.binding.vera.internal.discovery.VeraBridgeDiscoveryService.java

private void scan() {
    logger.debug("Starting scan for Vera controller");

    ValidateIPV4 validator = new ValidateIPV4();

    try {// w w  w . j  ava 2 s  .  c  o 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.network.internal.utils.NetworkUtils.java

/**
 * Gets every IPv4 Address on each Interface except the loopback
 * The Address format is ip/subnet/*  ww  w . j a v a 2  s  .c  o m*/
 *
 * @return The collected IPv4 Addresses
 */
public Set<String> getInterfaceIPs() {
    Set<String> interfaceIPs = new HashSet<>();

    Enumeration<NetworkInterface> interfaces;
    try {
        interfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException ignored) {
        // If we are not allowed to enumerate, we return an empty result set.
        return interfaceIPs;
    }

    // For each interface ...
    for (Enumeration<NetworkInterface> en = interfaces; en.hasMoreElements();) {
        NetworkInterface networkInterface = en.nextElement();
        boolean isLoopback = true;
        try {
            isLoopback = networkInterface.isLoopback();
        } catch (SocketException ignored) {
        }
        if (!isLoopback) {
            // .. and for each address ...
            for (Iterator<InterfaceAddress> it = networkInterface.getInterfaceAddresses().iterator(); it
                    .hasNext();) {

                // ... get IP and Subnet
                InterfaceAddress interfaceAddress = it.next();
                interfaceIPs.add(interfaceAddress.getAddress().getHostAddress() + "/"
                        + interfaceAddress.getNetworkPrefixLength());
            }
        }
    }

    return interfaceIPs;
}

From source file:com.hypersocket.client.hosts.HostsFileManager.java

private boolean checkRange(int _8bits, int _16bits, int _24bits) throws SocketException, UnknownHostException {

    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()) {
        NetworkInterface net = e.nextElement();
        for (InterfaceAddress i : net.getInterfaceAddresses()) {
            String range = _8bits + "." + _16bits + "." + _24bits;
            if (log.isInfoEnabled()) {
                log.info("Checking interface " + i.toString());
            }/* w ww.j  a v  a2  s .  c o  m*/
            if (i.getNetworkPrefixLength() > 0 && i.getNetworkPrefixLength() <= 31) {

                CIDR c = CIDR4.newCIDR(range + ".0" + "/" + i.getNetworkPrefixLength());

                if (c.contains(i.getAddress())) {
                    if (log.isInfoEnabled()) {
                        log.warn(i.getAddress() + " appears to be in our chosen range " + range + ".0" + "/"
                                + i.getNetworkPrefixLength());
                    }
                    return false;
                }
            }
        }
    }
    return true;
}

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  2s.  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.chromium.ChromeSystemNetwork.java

private void getNetworkInterfaces(final CordovaArgs args, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override//  ww  w.j a v  a 2s  .  co m
        public void run() {
            try {
                JSONArray ret = new JSONArray();
                ArrayList<NetworkInterface> interfaces = Collections
                        .list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface iface : interfaces) {
                    if (iface.isLoopback()) {
                        continue;
                    }
                    for (InterfaceAddress interfaceAddress : iface.getInterfaceAddresses()) {
                        InetAddress address = interfaceAddress.getAddress();
                        if (address == null) {
                            continue;
                        }
                        JSONObject data = new JSONObject();
                        data.put("name", iface.getDisplayName());
                        // Strip address scope zones for IPv6 address.
                        data.put("address", address.getHostAddress().replaceAll("%.*", ""));
                        data.put("prefixLength", interfaceAddress.getNetworkPrefixLength());

                        ret.put(data);
                    }
                }

                callbackContext.success(ret);
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error occured while getting network interfaces", e);
                callbackContext.error("Could not get network interfaces");
            }
        }
    });
}

From source file:com.cloud.utils.net.NetUtils.java

public static String[] getLocalCidrs() {
    final String defaultHostIp = getDefaultHostIp();

    final List<String> cidrList = new ArrayList<String>();
    try {//from   ww w .jav a  2 s . co  m
        for (final NetworkInterface ifc : IteratorUtil
                .enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
            if (ifc.isUp() && !ifc.isVirtual() && !ifc.isLoopback()) {
                for (final InterfaceAddress address : ifc.getInterfaceAddresses()) {
                    final InetAddress addr = address.getAddress();
                    final int prefixLength = address.getNetworkPrefixLength();
                    if (prefixLength < MAX_CIDR && prefixLength > 0) {
                        final String ip = ipFromInetAddress(addr);
                        if (ip.equalsIgnoreCase(defaultHostIp)) {
                            cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
                        }
                    }
                }
            }
        }
    } catch (final SocketException e) {
        s_logger.warn("UnknownHostException in getLocalCidrs().", e);
    }

    return cidrList.toArray(new String[0]);
}

From source file:com.vuze.plugin.azVPN_Helper.CheckerCommon.java

public int getNetworkPrefixLength(NetworkInterface networkInterface, InetAddress address) {
    int networkPrefixLength = -1;
    List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
    for (InterfaceAddress interfaceAddress : interfaceAddresses) {
        if (!interfaceAddress.getAddress().equals(address)) {
            continue;
        }//  w w w  .  ja  v a 2s.  c o m
        networkPrefixLength = interfaceAddress.getNetworkPrefixLength();
        // JDK-7107883 : getNetworkPrefixLength() does not return correct prefix length
        // networkPrefixLength will be zero on Java <= 7 when there is no
        // Broadcast address.
        // I'm guessing there is no broadcast address returned when mask is 32
        // on linux, but I can't confirm (I've seen it though)
        if (networkPrefixLength == 0 && interfaceAddress.getBroadcast() == null) {
            networkPrefixLength = 32;
        }
    }
    return networkPrefixLength;
}

From source file:com.cloud.utils.net.NetUtils.java

public static String[] getNetworkParams(final NetworkInterface nic) {
    final List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
    if (addrs == null || addrs.size() == 0) {
        return null;
    }/*w  ww .j a  v a2  s  .c om*/
    InterfaceAddress addr = null;
    for (final InterfaceAddress iaddr : addrs) {
        final InetAddress inet = iaddr.getAddress();
        if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress()
                && inet.getAddress().length == 4) {
            addr = iaddr;
            break;
        }
    }
    if (addr == null) {
        return null;
    }
    final String[] result = new String[3];
    result[0] = addr.getAddress().getHostAddress();
    try {
        final byte[] mac = nic.getHardwareAddress();
        result[1] = byte2Mac(mac);
    } catch (final SocketException e) {
        s_logger.debug("Caught exception when trying to get the mac address ", e);
    }

    result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
    return result;
}

From source file:org.chromium.ChromeSocket.java

private void getNetworkList(CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
    try {//from  w  w  w. j a va2  s .c o m
        JSONArray list = new JSONArray();
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        NetworkInterface iface;
        // Enumerations are a crappy legacy API, can't use the for (foo : bar) syntax.
        while (interfaces.hasMoreElements()) {
            iface = interfaces.nextElement();
            if (iface.isLoopback()) {
                continue;
            }
            for (InterfaceAddress interfaceAddress : iface.getInterfaceAddresses()) {
                InetAddress address = interfaceAddress.getAddress();
                if (address != null) {
                    JSONObject data = new JSONObject();
                    data.put("name", iface.getDisplayName());
                    // Strip percent suffix off of ipv6 addresses to match desktop behaviour.
                    data.put("address", address.getHostAddress().replaceAll("%.*", ""));
                    data.put("prefixLength", interfaceAddress.getNetworkPrefixLength());
                    list.put(data);
                }
            }
        }

        callbackContext.success(list);
    } catch (SocketException se) {
        callbackContext.error("SocketException: " + se);
    }
}