Example usage for java.net NetworkInterface getNetworkInterfaces

List of usage examples for java.net NetworkInterface getNetworkInterfaces

Introduction

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

Prototype

public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException 

Source Link

Document

Returns an Enumeration of all the interfaces on this machine.

Usage

From source file:org.graphwalker.Util.java

protected static InetAddress getInternetAddr(final String nic) {
    // Find the real network interface
    NetworkInterface iface = null;
    InetAddress ia = null;/*from w w w. jav a  2s . co  m*/
    boolean foundNIC = false;
    try {
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
                .hasMoreElements() && foundNIC == false;) {
            iface = ifaces.nextElement();
            Util.logger.debug("Interface: " + iface.getDisplayName());
            for (Enumeration<InetAddress> ips = iface.getInetAddresses(); ips.hasMoreElements()
                    && foundNIC == false;) {
                ia = ips.nextElement();
                Util.logger.debug(ia.getCanonicalHostName() + " " + ia.getHostAddress());
                if (!ia.isLoopbackAddress()) {
                    Util.logger.debug("  Not a loopback address...");
                    if (!ia.getHostAddress().contains(":") && nic.equals(iface.getDisplayName())) {
                        Util.logger.debug("  Host address does not contain ':'");
                        Util.logger.debug("  Interface: " + iface.getName()
                                + " seems to be InternetInterface. I'll take it...");
                        foundNIC = true;
                    }
                }
            }
        }
    } catch (SocketException e) {
        Util.logger.error(e.getMessage());
    } finally {
        if (!foundNIC && nic != null) {
            Util.logger.error("Could not bind to network interface: " + nic);
            throw new RuntimeException("Could not bind to network interface: " + nic);
        } else if (!foundNIC) {
            Util.logger.error("Could not bind to any network interface");
            throw new RuntimeException("Could not bind to any network interface: ");
        }
    }
    return ia;
}

From source file:org.mobisocial.corral.ContentCorral.java

public static String getLocalIpAddress() {
    try {/* w ww  . j a v  a2 s  .co m*/
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    // not ready for IPv6, apparently.
                    if (!inetAddress.getHostAddress().contains(":")) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        }
    } catch (SocketException ex) {

    }
    return null;
}

From source file:it.isislab.sof.core.engine.hadoop.sshclient.connection.SofManager.java

private static String getSimID() {
    InetAddress addr;/*from w ww  .j  a  v a 2  s. c  o  m*/
    try {
        addr = InetAddress.getLocalHost();
        Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
        while (networks.hasMoreElements()) {
            NetworkInterface network = networks.nextElement();
            byte[] mac = network.getHardwareAddress();

            if (mac != null) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < mac.length; i++) {
                    sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                }
                return DigestUtils.md5Hex(sb.toString() + (System.currentTimeMillis() + ""));
            }
        }
        return null;
    } catch (UnknownHostException e) {
        e.printStackTrace();
        return null;
    } catch (SocketException e) {
        e.printStackTrace();
        return null;
    }

    //return System.currentTimeMillis()+"";
}

From source file:net.fenyo.gnetwatch.GUI.GUI.java

private void appendNetworkInterfaces() {
    try {/*from w  w  w . ja  v a 2  s.c o m*/
        // should be localized
        String str = "<HR/><B>Local network interfaces</B>";
        str += "<TABLE BORDER='0' BGCOLOR='black' cellspacing='1' cellpadding='1'>";
        for (final Enumeration nifs = NetworkInterface.getNetworkInterfaces(); nifs.hasMoreElements();) {
            final NetworkInterface nif = (NetworkInterface) nifs.nextElement();
            str += "<TR><TD bgcolor='lightyellow' align='right'><B>" + htmlFace("interface name")
                    + "</B></TD><TD bgcolor='lightyellow'><B>" + htmlFace(nif.getName()) + "</B></TD></TR>";
            str += "<TR><TD bgcolor='lightyellow' align='right'>" + htmlFace("display name")
                    + "</TD><TD bgcolor='lightyellow'>" + htmlFace(nif.getDisplayName()) + "</TD></TR>";
            for (final Enumeration addrs = nif.getInetAddresses(); addrs.hasMoreElements();) {
                final InetAddress addr = (InetAddress) addrs.nextElement();
                if (Inet4Address.class.isInstance(addr))
                    str += "<TR><TD bgcolor='lightyellow' align='right'>" + htmlFace("IPv4 address")
                            + "</TD><TD bgcolor='lightyellow'>" + htmlFace(addr.getHostAddress())
                            + "</TD></TR>";
                if (Inet6Address.class.isInstance(addr))
                    str += "<TR><TD bgcolor='lightyellow' align='right'>" + htmlFace("IPv6 address")
                            + "</TD><TD bgcolor='lightyellow'>" + htmlFace(addr.getHostAddress())
                            + "</TD></TR>";
            }
        }
        str += "</TABLE>";
        appendConsole(str);
    } catch (final SocketException ex) {
        log.error("Exception", ex);
    }
}

From source file:com.safi.asterisk.handler.SafletEngine.java

public List<String> getLocalIPAddresses() {
    List<String> iplist = new ArrayList<String>();
    NetworkInterface iface = null;
    try {//from   ww  w . ja  va 2  s.  c o  m
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
                .hasMoreElements();) {
            iface = ifaces.nextElement();
            System.out.println("Interface:" + iface.getDisplayName());
            InetAddress ia = null;
            for (Enumeration<InetAddress> ips = iface.getInetAddresses(); ips.hasMoreElements();) {
                ia = ips.nextElement();
                if (Pattern.matches(AbstractConnectionManager.PATTERN_IP, ia.getHostAddress())) {
                    iplist.add(ia.getHostAddress());
                }
            }
        }
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return iplist;
}

From source file:configuration.Util.java

/**
 * Code from : http://stackoverflow.com/questions/8083479/java-getting-my-ip-address
 *
 * @return// ww  w .j a v  a 2  s. c  om
 */
public String ip() {
    String ip;
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            // filters out 127.0.0.1 and inactive interfaces
            if (iface.isLoopback() || !iface.isUp())
                continue;

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                ip = addr.getHostAddress();
                return ip;
                //System.out.println(iface.getDisplayName() + " " + ip);
            }
        }
    } catch (Exception e) {
        System.out.println("Ip Failed!");
        System.out.println(e);
        return "";
    }
    return "";
}

From source file:com.master.metehan.filtereagle.ServiceSinkhole.java

private Builder getBuilder(List<Rule> listAllowed, List<Rule> listRule) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean subnet = prefs.getBoolean("subnet", false);
    boolean tethering = prefs.getBoolean("tethering", false);
    boolean lan = prefs.getBoolean("lan", false);
    boolean ip6 = prefs.getBoolean("ip6", true);
    boolean filter = prefs.getBoolean("filter", false);
    boolean system = prefs.getBoolean("manage_system", false);

    // Build VPN service
    Builder builder = new Builder();
    builder.setSession(getString(R.string.app_name));

    // VPN address
    String vpn4 = prefs.getString("vpn4", "10.1.10.1");
    Log.i(TAG, "vpn4=" + vpn4);
    builder.addAddress(vpn4, 32);//from  ww  w.  j a v  a 2  s . co  m
    if (ip6) {
        String vpn6 = prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1");
        Log.i(TAG, "vpn6=" + vpn6);
        builder.addAddress(vpn6, 128);
    }

    // DNS address
    if (filter)
        for (InetAddress dns : getDns(ServiceSinkhole.this)) {
            if (ip6 || dns instanceof Inet4Address) {
                Log.i(TAG, "dns=" + dns);
                builder.addDnsServer(dns);
            }
        }

    // Subnet routing
    if (subnet) {
        // Exclude IP ranges
        List<IPUtil.CIDR> listExclude = new ArrayList<>();
        listExclude.add(new IPUtil.CIDR("127.0.0.0", 8)); // localhost

        if (tethering) {
            // USB Tethering 192.168.42.x
            // Wi-Fi Tethering 192.168.43.x
            listExclude.add(new IPUtil.CIDR("192.168.42.0", 23));
        }

        if (lan) {
            try {
                Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
                while (nis.hasMoreElements()) {
                    NetworkInterface ni = nis.nextElement();
                    if (ni != null && ni.isUp() && !ni.isLoopback() && ni.getName() != null
                            && !ni.getName().startsWith("tun"))
                        for (InterfaceAddress ia : ni.getInterfaceAddresses())
                            if (ia.getAddress() instanceof Inet4Address) {
                                IPUtil.CIDR local = new IPUtil.CIDR(ia.getAddress(),
                                        ia.getNetworkPrefixLength());
                                Log.i(TAG, "Excluding " + ni.getName() + " " + local);
                                listExclude.add(local);
                            }
                }
            } catch (SocketException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        }

        Configuration config = getResources().getConfiguration();
        if (config.mcc == 310 && config.mnc == 260) {
            // T-Mobile Wi-Fi calling
            listExclude.add(new IPUtil.CIDR("66.94.2.0", 24));
            listExclude.add(new IPUtil.CIDR("66.94.6.0", 23));
            listExclude.add(new IPUtil.CIDR("66.94.8.0", 22));
            listExclude.add(new IPUtil.CIDR("208.54.0.0", 16));
        }
        listExclude.add(new IPUtil.CIDR("224.0.0.0", 3)); // broadcast

        Collections.sort(listExclude);

        try {
            InetAddress start = InetAddress.getByName("0.0.0.0");
            for (IPUtil.CIDR exclude : listExclude) {
                Log.i(TAG, "Exclude " + exclude.getStart().getHostAddress() + "..."
                        + exclude.getEnd().getHostAddress());
                for (IPUtil.CIDR include : IPUtil.toCIDR(start, IPUtil.minus1(exclude.getStart())))
                    try {
                        builder.addRoute(include.address, include.prefix);
                    } catch (Throwable ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }
                start = IPUtil.plus1(exclude.getEnd());
            }
            for (IPUtil.CIDR include : IPUtil.toCIDR("224.0.0.0", "255.255.255.255"))
                try {
                    builder.addRoute(include.address, include.prefix);
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
        } catch (UnknownHostException ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
    } else
        builder.addRoute("0.0.0.0", 0);

    Log.i(TAG, "IPv6=" + ip6);
    if (ip6)
        builder.addRoute("0:0:0:0:0:0:0:0", 0);

    // MTU
    int mtu = jni_get_mtu();
    Log.i(TAG, "MTU=" + mtu);
    builder.setMtu(mtu);

    // Add list of allowed applications
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        if (last_connected && !filter)
            for (Rule rule : listAllowed)
                try {
                    builder.addDisallowedApplication(rule.info.packageName);
                } catch (PackageManager.NameNotFoundException ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
        else if (filter)
            for (Rule rule : listRule)
                if (!rule.apply || (!system && rule.system))
                    try {
                        Log.i(TAG, "Not routing " + rule.info.packageName);
                        builder.addDisallowedApplication(rule.info.packageName);
                    } catch (PackageManager.NameNotFoundException ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }

    // Build configure intent
    Intent configure = new Intent(this, ActivityMain.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, configure, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setConfigureIntent(pi);

    return builder;
}

From source file:org.uguess.android.sysinfo.SiragonManager.java

static String getNetAddressInfo() {
    try {/*ww w  .ja v  a 2  s  .co  m*/
        StringBuffer sb = new StringBuffer();

        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    String addr = inetAddress.getHostAddress();

                    if (!TextUtils.isEmpty(addr)) {
                        if (sb.length() == 0) {
                            sb.append(addr);
                        } else {
                            sb.append(", ").append(addr); //$NON-NLS-1$
                        }
                    }
                }
            }
        }

        String netAddress = sb.toString();

        if (!TextUtils.isEmpty(netAddress)) {
            return netAddress;
        }
    } catch (SocketException e) {
        Log.e(SiragonManager.class.getName(), e.getLocalizedMessage(), e);
    }

    return null;
}

From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java

public static List<InetAddress> getDns(Context context) {
    List<InetAddress> listDns = new ArrayList<>();
    List<String> sysDns = Util.getDefaultDNS(context);

    // Get custom DNS servers
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String vpnDns1 = prefs.getString("dns", null);
    String vpnDns2 = prefs.getString("dns2", null);
    Log.i(TAG, "DNS system=" + TextUtils.join(",", sysDns) + " VPN1=" + vpnDns1 + " VPN2=" + vpnDns2);

    if (vpnDns1 != null)
        try {/*from  w  w  w.j av a2 s . co m*/
            InetAddress dns = InetAddress.getByName(vpnDns1);
            if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress()))
                listDns.add(dns);
        } catch (Throwable ignored) {
        }

    if (vpnDns2 != null)
        try {
            InetAddress dns = InetAddress.getByName(vpnDns2);
            if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress()))
                listDns.add(dns);
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

    // Use system DNS servers only when no two custom DNS servers specified
    if (listDns.size() <= 1)
        for (String def_dns : sysDns)
            try {
                InetAddress ddns = InetAddress.getByName(def_dns);
                if (!listDns.contains(ddns) && !(ddns.isLoopbackAddress() || ddns.isAnyLocalAddress()))
                    listDns.add(ddns);
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

    // Remove local DNS servers when not routing LAN
    boolean lan = prefs.getBoolean("lan", false);
    if (lan) {
        List<InetAddress> listLocal = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
            if (nis != null)
                while (nis.hasMoreElements()) {
                    NetworkInterface ni = nis.nextElement();
                    if (ni != null && ni.isUp() && !ni.isLoopback()) {
                        List<InterfaceAddress> ias = ni.getInterfaceAddresses();
                        if (ias != null)
                            for (InterfaceAddress ia : ias) {
                                InetAddress hostAddress = ia.getAddress();
                                BigInteger host = new BigInteger(1, hostAddress.getAddress());

                                int prefix = ia.getNetworkPrefixLength();
                                BigInteger mask = BigInteger.valueOf(-1)
                                        .shiftLeft(hostAddress.getAddress().length * 8 - prefix);

                                for (InetAddress dns : listDns)
                                    if (hostAddress.getAddress().length == dns.getAddress().length) {
                                        BigInteger ip = new BigInteger(1, dns.getAddress());

                                        if (host.and(mask).equals(ip.and(mask))) {
                                            Log.i(TAG, "Local DNS server host=" + hostAddress + "/" + prefix
                                                    + " dns=" + dns);
                                            listLocal.add(dns);
                                        }
                                    }
                            }
                    }
                }
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

        List<InetAddress> listDns4 = new ArrayList<>();
        List<InetAddress> listDns6 = new ArrayList<>();
        try {
            listDns4.add(InetAddress.getByName("8.8.8.8"));
            listDns4.add(InetAddress.getByName("8.8.4.4"));
            listDns6.add(InetAddress.getByName("2001:4860:4860::8888"));
            listDns6.add(InetAddress.getByName("2001:4860:4860::8844"));

        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

        for (InetAddress dns : listLocal) {
            listDns.remove(dns);
            if (dns instanceof Inet4Address) {
                if (listDns4.size() > 0) {
                    listDns.add(listDns4.get(0));
                    listDns4.remove(0);
                }
            } else {
                if (listDns6.size() > 0) {
                    listDns.add(listDns6.get(0));
                    listDns6.remove(0);
                }
            }
        }
    }

    // Prefer IPv4 addresses
    Collections.sort(listDns, new Comparator<InetAddress>() {
        @Override
        public int compare(InetAddress a, InetAddress b) {
            boolean a4 = (a instanceof Inet4Address);
            boolean b4 = (b instanceof Inet4Address);
            if (a4 && !b4)
                return -1;
            else if (!a4 && b4)
                return 1;
            else
                return 0;
        }
    });

    return listDns;
}

From source file:org.apache.nifi.web.server.JettyServer.java

private void dumpUrls() throws SocketException {
    final List<String> urls = new ArrayList<>();

    for (Connector connector : server.getConnectors()) {
        if (connector instanceof ServerConnector) {
            final ServerConnector serverConnector = (ServerConnector) connector;

            Set<String> hosts = new HashSet<>();

            // determine the hosts
            if (StringUtils.isNotBlank(serverConnector.getHost())) {
                hosts.add(serverConnector.getHost());
            } else {
                Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
                if (networkInterfaces != null) {
                    for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) {
                        for (InetAddress inetAddress : Collections.list(networkInterface.getInetAddresses())) {
                            hosts.add(inetAddress.getHostAddress());
                        }// w  ww  .j a  v  a2 s. co  m
                    }
                }
            }

            // ensure some hosts were found
            if (!hosts.isEmpty()) {
                String scheme = "http";
                if (props.getSslPort() != null && serverConnector.getPort() == props.getSslPort()) {
                    scheme = "https";
                }

                // dump each url
                for (String host : hosts) {
                    urls.add(String.format("%s://%s:%s", scheme, host, serverConnector.getPort()));
                }
            }
        }
    }

    if (urls.isEmpty()) {
        logger.warn(
                "NiFi has started, but the UI is not available on any hosts. Please verify the host properties.");
    } else {
        // log the ui location
        logger.info("NiFi has started. The UI is available at the following URLs:");
        for (final String url : urls) {
            logger.info(String.format("%s/nifi", url));
        }
    }
}