Example usage for java.net NetworkInterface isLoopback

List of usage examples for java.net NetworkInterface isLoopback

Introduction

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

Prototype


public boolean isLoopback() throws SocketException 

Source Link

Document

Returns whether a network interface is a loopback interface.

Usage

From source file:com.oneops.inductor.Config.java

/**
 * Retruns the inductor IP address (IPV4 address). If there are multiple
 * NICs/IfAddresses, it selects the first one. Openstack VMs normally has
 * only one network interface (eth0).//from w  w w  .  j  av  a2s . c  o  m
 * 
 * @return IPV4 address of inductor with interface name. Returns
 *         <code>null</code> if it couldn't find anything.
 */
private String getInductorIPv4Addr() {
    try {
        Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
        while (nics.hasMoreElements()) {
            NetworkInterface nic = nics.nextElement();
            if (nic.isUp() && !nic.isLoopback()) {
                Enumeration<InetAddress> addrs = nic.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress add = addrs.nextElement();
                    // Print only IPV4 address
                    if (add instanceof Inet4Address && !add.isLoopbackAddress()) {
                        // Log the first one.
                        String ip = add.getHostAddress() + " (" + nic.getDisplayName() + ")";
                        logger.info("Inductor IP : " + ip);
                        return ip;
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.warn("Error getting inductor IP address", e);
        // Skip any errors
    }
    return null;
}

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  www .  j a  v a  2 s .  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:com.portfolio.data.attachment.FileServlet.java

@Override
public void init(ServletConfig config) {
    /// List possible local address
    try {/* w  ww  . j a  v a2s .c o m*/
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual())
                continue;
            Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress current_addr = addresses.nextElement();
                if (current_addr instanceof Inet4Address)
                    ourIPs.add(current_addr.getHostAddress());
            }
        }
    } catch (Exception e) {
    }

    servContext = config.getServletContext();
    backend = config.getServletContext().getInitParameter("backendserver");
    server = config.getServletContext().getInitParameter("fileserver");
    try {
        String dataProviderName = config.getInitParameter("dataProviderClass");
        dataProvider = (DataProvider) Class.forName(dataProviderName).newInstance();

        InitialContext cxt = new InitialContext();
        if (cxt == null) {
            throw new Exception("no context found!");
        }

        /// Init this here, might fail depending on server hosting
        ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/portfolio-backend");
        if (ds == null) {
            throw new Exception("Data  jdbc/portfolio-backend source not found!");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.analytics.dataservice.indexing.AnalyticsDataIndexer.java

private String getLocalUniqueId() {
    String id = null;/*from w w  w.  j  a v a 2  s .c om*/
    Enumeration<NetworkInterface> interfaces;
    NetworkInterface nif;
    try {
        interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            nif = interfaces.nextElement();
            if (!nif.isLoopback()) {
                byte[] addr = nif.getHardwareAddress();
                if (addr != null) {
                    id = this.byteArrayToHexString(addr);
                }
                /* only try first valid one, if we can't get it from here, 
                 * we wont be able to get it */
                break;
            }
        }
    } catch (SocketException ignore) {
        /* ignore */
    }
    if (id == null) {
        log.warn("CANNOT LOOK UP UNIQUE LOCAL ID USING A VALID NETWORK INTERFACE HARDWARE ADDRESS, "
                + "REVERTING TO LOCAL SINGLE NODE MODE, THIS WILL NOT WORK PROPERLY IN A CLUSTER, "
                + "AND MAY CAUSE INDEX CORRUPTION");
        /* a last effort to get a unique number, Java system properties should also take in account of the 
         * server's port offset */
        id = LOCAL_NODE_ID + ":" + (System.getenv().hashCode() + System.getProperties().hashCode());
    }
    return id;
}

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.  com

    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:com.jagornet.dhcp.server.JagornetDhcpServer.java

/**
 * Gets all IPv6 network interfaces on the local host.
 * //from w  w  w.  ja  v  a2  s  .  c o m
 * @return the list NetworkInterfaces
 */
private List<NetworkInterface> getAllIPv6NetIfs() throws SocketException {
    List<NetworkInterface> netIfs = new ArrayList<NetworkInterface>();
    Enumeration<NetworkInterface> localInterfaces = NetworkInterface.getNetworkInterfaces();
    if (localInterfaces != null) {
        while (localInterfaces.hasMoreElements()) {
            NetworkInterface netIf = localInterfaces.nextElement();
            // for multicast, the loopback interface is excluded
            if (netIf.supportsMulticast() && !netIf.isLoopback()) {
                Enumeration<InetAddress> ifAddrs = netIf.getInetAddresses();
                while (ifAddrs.hasMoreElements()) {
                    InetAddress ip = ifAddrs.nextElement();
                    if (ip instanceof Inet6Address) {
                        netIfs.add(netIf);
                        break; // out to next interface
                    }
                }
            }
        }
    } else {
        log.error("No network interfaces found!");
    }
    return netIfs;
}

From source file:org.wso2.carbon.appmanager.integration.ui.APPManagerIntegrationTest.java

protected String getNetworkIPAddress() {
    String networkIpAddress = null;
    try {/*from   w w w . j av  a  2  s.co m*/
        String localhost = InetAddress.getLocalHost().getHostAddress();
        Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface ni = (NetworkInterface) e.nextElement();
            if (ni.isLoopback())
                continue;
            if (ni.isPointToPoint())
                continue;
            Enumeration<InetAddress> addresses = ni.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = (InetAddress) addresses.nextElement();
                if (address instanceof Inet4Address) {
                    String ip = address.getHostAddress();
                    if (!ip.equals(localhost)) {
                        networkIpAddress = ip;
                    }

                }
            }
        }
    } catch (UnknownHostException e) {
        log.error("Error occurred due to an unknown host.", e);
    } catch (SocketException e) {
        log.error("Error occurred with Socket connections", e);
    }
    return networkIpAddress;
}

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

/**
 * Gets the IPv6 network interfaces for the supplied interface names.
 * //w ww .  j  a  v a2 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:org.chromium.ChromeSocket.java

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