Example usage for java.net NetworkInterface getInterfaceAddresses

List of usage examples for java.net NetworkInterface getInterfaceAddresses

Introduction

In this page you can find the example usage for java.net NetworkInterface getInterfaceAddresses.

Prototype

public java.util.List<InterfaceAddress> getInterfaceAddresses() 

Source Link

Document

Get a List of all or a subset of the InterfaceAddresses of this network interface.

Usage

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 {//  ww w. j  a  va  2s .c om
        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:ch.cyberduck.core.socket.NetworkInterfaceAwareSocketFactory.java

private NetworkInterface findIPv6Interface(Inet6Address address) throws IOException {
    if (blacklisted.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("Ignore IP6 default network interface setup with empty blacklist");
        }/*from ww  w . j a v  a  2s  . c  o  m*/
        return null;
    }
    if (address.getScopeId() != 0) {
        if (log.isDebugEnabled()) {
            log.debug(String.format(
                    "Ignore IP6 default network interface setup for address with scope identifier %d",
                    address.getScopeId()));
        }
        return null;
    }
    // If we find an interface name en0 that supports IPv6 make it the default.
    // We must use the index of the network interface. Referencing the interface by name will still
    // set the scope id to '0' referencing the awdl0 interface that is first in the list of enumerated
    // network interfaces instead of its correct index in <code>java.net.Inet6Address</code>
    // Use private API to defer the numeric format for the address
    List<Integer> indexes = new ArrayList<Integer>();
    final Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
    while (enumeration.hasMoreElements()) {
        indexes.add(enumeration.nextElement().getIndex());
    }
    for (Integer index : indexes) {
        final NetworkInterface n = NetworkInterface.getByIndex(index);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Evaluate interface with %s index %d", n, index));
        }
        if (!n.isUp()) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Ignore interface %s not up", n));
            }
            continue;
        }
        if (blacklisted.contains(n.getName())) {
            log.warn(String.format("Ignore network interface %s disabled with blacklist", n));
            continue;
        }
        for (InterfaceAddress i : n.getInterfaceAddresses()) {
            if (i.getAddress() instanceof Inet6Address) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Selected network interface %s", n));
                }
                return n;
            }
        }
        log.warn(String.format("No IPv6 for interface %s", n));
    }
    log.warn("No network interface found for IPv6");
    return null;
}

From source file:gov.nrel.bacnet.consumer.BACnet.java

private void initialize(Config config) throws IOException {
    LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(1000);
    RejectedExecutionHandler rejectedExec = new RejectedExecHandler();
    // schedule polling on single threaded service because local device instance is not threadsafe
    execSvc = Executors.newFixedThreadPool(config.getNumThreads());
    //give databus recording 2 threads to match old code
    recorderSvc = new ThreadPoolExecutor(20, 20, 120, TimeUnit.SECONDS, queue, rejectedExec);
    schedSvc = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(config.getNumThreads());
    exec = new OurExecutor(schedSvc, execSvc, recorderSvc);
    String devname = config.getNetworkDevice();
    int device_id = config.getDeviceId();
    NetworkInterface networkinterface = null;

    try {/*from   w ww.  ja va  2 s  .  c  om*/
        networkinterface = java.net.NetworkInterface.getByName(devname);
    } catch (Exception ex) {
        System.out.println("Unable to open device: " + devname);
        System.exit(-1);
    }

    if (networkinterface == null) {
        System.out.println("Unable to open device: " + devname);
        System.exit(-1);
    }

    List<InterfaceAddress> addresses = networkinterface.getInterfaceAddresses();

    String sbroadcast = null;
    String saddress = null;
    //InterfaceAddress ifaceaddr = null;

    for (InterfaceAddress address : addresses) {
        logger.fine("Evaluating address: " + address.toString());
        if (address.getAddress().getAddress().length == 4) {
            logger.info("Address is ipv4, selecting: " + address.toString());
            sbroadcast = address.getBroadcast().toString().substring(1);
            saddress = address.getAddress().toString().substring(1);
            //ifaceaddr = address;
            break;
        } else {
            logger.info("Address is not ipv4, not selecting: " + address.toString());
        }
    }

    logger.info("Binding to: " + saddress + " " + sbroadcast);

    localDevice = new LocalDevice(device_id, sbroadcast);
    localDevice.setPort(LocalDevice.DEFAULT_PORT);
    localDevice.setTimeout(localDevice.getTimeout() * 3);
    localDevice.setSegTimeout(localDevice.getSegTimeout() * 3);
    try {
        localDevice.initialize();
        localDevice.setRetries(0); //don't retry as it seems to really be a waste.
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    if (config.getSlaveDeviceEnabled()) {
        slaveDeviceTimer = new Timer();
        slaveDeviceTimer.schedule(new gov.nrel.bacnet.SlaveDevice(localDevice, config), 1000,
                config.getSlaveDeviceUpdateInterval() * 1000);
    }

    int counter = 0;

    String username = config.getDatabusUserName();
    String key = config.getDatabusKey();

    logger.info("user=" + username + " key=" + key);

    DatabusSender sender = null;

    if (config.getDatabusEnabled()) {
        sender = new DatabusSender(username, key, execSvc, config.getDatabusUrl(), config.getDatabusPort(),
                true);
    }
    logger.info("databus sender: " + sender);
    writer = new DatabusDataWriter(new DataPointWriter(sender));
    logger.info("databus writer" + writer);
}

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;
        }/*from  ww  w .j a  v  a  2  s . 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.entertailion.java.fling.FlingFrame.java

private InterfaceAddress getPreferredInetAddress(String prefix) {
    InterfaceAddress selectedInterfaceAddress = null;
    try {//from   www  .  j a  v a2 s . c o  m
        Enumeration<NetworkInterface> list = NetworkInterface.getNetworkInterfaces();

        while (list.hasMoreElements()) {
            NetworkInterface iface = list.nextElement();
            if (iface == null)
                continue;
            Log.d(LOG_TAG, "interface=" + iface.getName());
            Iterator<InterfaceAddress> it = iface.getInterfaceAddresses().iterator();
            while (it.hasNext()) {
                InterfaceAddress interfaceAddress = it.next();
                if (interfaceAddress == null)
                    continue;
                InetAddress address = interfaceAddress.getAddress();
                Log.d(LOG_TAG, "address=" + address);
                if (address instanceof Inet4Address) {
                    // Only pick an interface that is likely to be on the
                    // same subnet as the selected ChromeCast device
                    if (address.getHostAddress().toString().startsWith(prefix)) {
                        return interfaceAddress;
                    }
                }
            }
        }
    } catch (Exception ex) {
    }
    return selectedInterfaceAddress;
}

From source file:com.jagornet.dhcpv6.server.DhcpV6Server.java

/**
 * Gets the IPv6 network interfaces for the supplied interface names.
 * //w w w.j av  a 2 s .c  o m
 * @param ifnames the interface names to locate NetworkInterfaces by
 * 
 * @return the list of NetworkInterfaces that are up, support multicast,
 * and have at least one IPv6 address configured
 * 
 * @throws SocketException the socket exception
 */
private List<NetworkInterface> getIPv6NetIfs(String[] ifnames) throws SocketException {
    List<NetworkInterface> netIfs = new ArrayList<NetworkInterface>();
    for (String ifname : ifnames) {
        if (ifname.equals("*")) {
            return getAllIPv6NetIfs();
        }
        NetworkInterface netIf = NetworkInterface.getByName(ifname);
        if (netIf == null) {
            // if not found by name, see if the name is actually an address
            try {
                InetAddress ipaddr = InetAddress.getByName(ifname);
                netIf = NetworkInterface.getByInetAddress(ipaddr);
            } catch (UnknownHostException ex) {
                log.warn("Unknown interface: " + ifname + ": " + ex);
            }
        }
        if (netIf != null) {
            if (netIf.isUp()) {
                // for multicast, the loopback interface is excluded
                if (netIf.supportsMulticast() && !netIf.isLoopback()) {
                    boolean isV6 = false;
                    List<InterfaceAddress> ifAddrs = netIf.getInterfaceAddresses();
                    for (InterfaceAddress ifAddr : ifAddrs) {
                        if (ifAddr.getAddress() instanceof Inet6Address) {
                            netIfs.add(netIf);
                            isV6 = true;
                            break;
                        }
                    }
                    if (!isV6) {
                        System.err.println("Interface is not configured for IPv6: " + netIf.getDisplayName());
                        return null;
                    }
                } else {
                    System.err.println("Interface does not support multicast: " + netIf.getDisplayName());
                    return null;
                }
            } else {
                System.err.println("Interface is not up: " + netIf.getDisplayName());
                return null;
            }
        } else {
            System.err.println("Interface not found or inactive: " + ifname);
            return null;
        }
    }
    return netIfs;
}

From source file:fr.inria.ucn.collectors.NetworkStateCollector.java

private JSONArray getIfconfig(Map<String, JSONObject> stats) throws JSONException {
    JSONArray ifaces = new JSONArray();

    // make sure the stats is read
    networkStats();// w w w .  j  av a 2 s  . c  om

    Enumeration<NetworkInterface> en = null;
    try {
        en = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        Log.d(Constants.LOGTAG, "failed to list interfaces", e);
    }

    if (en != null) {
        while (en.hasMoreElements()) {
            NetworkInterface intf = en.nextElement();

            JSONObject iface = new JSONObject();
            iface.put("display_name", intf.getDisplayName());
            iface.put("name", intf.getName());
            iface.put("is_virtual", intf.isVirtual());
            iface.put("stats", stats.get(intf.getName()));

            try {
                iface.put("mtu", intf.getMTU());
                iface.put("is_loopback", intf.isLoopback());
                iface.put("is_ptop", intf.isPointToPoint());
                iface.put("is_up", intf.isUp());
            } catch (SocketException e) {
                Log.d(Constants.LOGTAG, "failed to read interface data", e);
            }

            JSONArray ips = new JSONArray();
            List<InterfaceAddress> ilist = intf.getInterfaceAddresses();
            for (InterfaceAddress ia : ilist) {
                ips.put(ia.getAddress().getHostAddress());
            }
            iface.put("addresses", ips);

            ifaces.put(iface);
        }
    } else {
        for (String name : stats.keySet()) {
            JSONObject iface = new JSONObject();
            iface.put("name", name);
            iface.put("stats", stats.get(name));
            ifaces.put(iface);
        }
    }

    return ifaces;
}

From source file:org.chromium.ChromeSocket.java

private void getNetworkList(CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
    try {/*from  ww w  .j a v  a  2s.  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);
    }
}

From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java

private NetworkInterface getIPv4NetIf(String ifname) throws SocketException {
    NetworkInterface netIf = NetworkInterface.getByName(ifname);
    if (netIf == null) {
        // if not found by name, see if the name is actually an address
        try {/*from   www.  j  a v a2 s  .  c o  m*/
            InetAddress ipaddr = InetAddress.getByName(ifname);
            netIf = NetworkInterface.getByInetAddress(ipaddr);
        } catch (UnknownHostException ex) {
            log.warn("Unknown interface: " + ifname + ": " + ex);
        }
    }
    if (netIf != null) {
        if (netIf.isUp()) {
            // the loopback interface is excluded
            if (!netIf.isLoopback()) {
                boolean isV4 = false;
                List<InterfaceAddress> ifAddrs = netIf.getInterfaceAddresses();
                for (InterfaceAddress ifAddr : ifAddrs) {
                    if (ifAddr.getAddress() instanceof Inet4Address) {
                        isV4 = true;
                        break;
                    }
                }
                if (!isV4) {
                    System.err.println("Interface is not configured for IPv4: " + netIf);
                    return null;
                }
            } else {
                System.err.println("Interface is loopback: " + netIf);
                return null;
            }
        } else {
            System.err.println("Interface is not up: " + netIf);
            return null;
        }
    } else {
        System.err.println("Interface not found or inactive: " + ifname);
        return null;
    }
    return netIf;
}

From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java

/**
 * Gets the IPv6 network interfaces for the supplied interface names.
 * //from  w w  w . j av  a  2 s  .  com
 * @param ifnames the interface names to locate NetworkInterfaces by
 * 
 * @return the list of NetworkInterfaces that are up, support multicast,
 * and have at least one IPv6 address configured
 * 
 * @throws SocketException the socket exception
 */
private List<NetworkInterface> getIPv6NetIfs(String[] ifnames) throws SocketException {
    List<NetworkInterface> netIfs = new ArrayList<NetworkInterface>();
    for (String ifname : ifnames) {
        if (ifname.equals("*")) {
            return getAllIPv6NetIfs();
        }
        NetworkInterface netIf = NetworkInterface.getByName(ifname);
        if (netIf == null) {
            // if not found by name, see if the name is actually an address
            try {
                InetAddress ipaddr = InetAddress.getByName(ifname);
                netIf = NetworkInterface.getByInetAddress(ipaddr);
            } catch (UnknownHostException ex) {
                log.warn("Unknown interface: " + ifname + ": " + ex);
            }
        }
        if (netIf != null) {
            if (netIf.isUp()) {
                // for multicast, the loopback interface is excluded
                if (netIf.supportsMulticast() && !netIf.isLoopback()) {
                    boolean isV6 = false;
                    List<InterfaceAddress> ifAddrs = netIf.getInterfaceAddresses();
                    for (InterfaceAddress ifAddr : ifAddrs) {
                        if (ifAddr.getAddress() instanceof Inet6Address) {
                            netIfs.add(netIf);
                            isV6 = true;
                            break;
                        }
                    }
                    if (!isV6) {
                        System.err.println("Interface is not configured for IPv6: " + netIf);
                        return null;
                    }
                } else {
                    System.err.println("Interface does not support multicast: " + netIf);
                    return null;
                }
            } else {
                System.err.println("Interface is not up: " + netIf);
                return null;
            }
        } else {
            System.err.println("Interface not found or inactive: " + ifname);
            return null;
        }
    }
    return netIfs;
}