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.mortbay.ijetty.IJetty.java

License:asdf

private void printNetworkInterfaces() {
    try {/*w w w.  j  a  va  2s . c o  m*/
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface ni : Collections.list(nis)) {
            Enumeration<InetAddress> iis = ni.getInetAddresses();
            for (InetAddress ia : Collections.list(iis)) {
                consoleBuffer.append(formatJettyInfoLine("Network interface: %s: %s", ni.getDisplayName(),
                        ia.getHostAddress()));
            }
        }
    } catch (SocketException e) {
        Log.w(TAG, e);
    }
}

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

/**
 * Parses the command line options.//www.ja v  a  2  s  .c  om
 * 
 * @param args the command line argument array
 * 
 * @return true, if all arguments were successfully parsed
 */
protected boolean parseOptions(String[] args) {
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("?")) {
            showHelp();
            System.exit(0);
        }
        if (cmd.hasOption("c")) {
            configFilename = cmd.getOptionValue("c");
        }
        if (cmd.hasOption("6p")) {
            String p = cmd.getOptionValue("6p");
            try {
                v6PortNumber = Integer.parseInt(p);
            } catch (NumberFormatException ex) {
                v6PortNumber = DhcpConstants.V6_SERVER_PORT;
                System.err.println(
                        "Invalid port number: '" + p + "' using default: " + v6PortNumber + " Exception=" + ex);
            }
        }
        if (cmd.hasOption("6m")) {
            String[] ifnames = cmd.getOptionValues("6m");
            if ((ifnames == null) || (ifnames.length < 1)) {
                ifnames = new String[] { "*" };
            }
            v6McastNetIfs = getIPv6NetIfs(ifnames);
            if ((v6McastNetIfs == null) || v6McastNetIfs.isEmpty()) {
                return false;
            }
        }
        if (cmd.hasOption("6u")) {
            String[] addrs = cmd.getOptionValues("6u");
            if ((addrs == null) || (addrs.length < 1)) {
                addrs = new String[] { "*" };
            }
            v6UcastAddrs = getIpAddrs(addrs);
            if ((v6UcastAddrs == null) || v6UcastAddrs.isEmpty()) {
                return false;
            }
        }
        if (cmd.hasOption("4b")) {
            String v4if = cmd.getOptionValue("4b");
            v4BcastNetIf = getIPv4NetIf(v4if);
            if (v4BcastNetIf == null) {
                return false;
            }
        }
        if (cmd.hasOption("4u")) {
            String[] addrs = cmd.getOptionValues("4u");
            if ((addrs == null) || (addrs.length < 1)) {
                addrs = new String[] { "*" };
            }
            v4UcastAddrs = getV4IpAddrs(addrs);
            if ((v4UcastAddrs == null) || v4UcastAddrs.isEmpty()) {
                return false;
            }
        }
        if (cmd.hasOption("4p")) {
            String p = cmd.getOptionValue("4p");
            try {
                v4PortNumber = Integer.parseInt(p);
            } catch (NumberFormatException ex) {
                v4PortNumber = DhcpConstants.V4_SERVER_PORT;
                System.err.println(
                        "Invalid port number: '" + p + "' using default: " + v4PortNumber + " Exception=" + ex);
            }
        }
        if (cmd.hasOption("v")) {
            System.err.println(Version.getVersion());
            System.exit(0);
        }
        if (cmd.hasOption("tc")) {
            try {
                String filename = cmd.getOptionValue("tc");
                System.err.println("Parsing server configuration file: " + filename);
                DhcpServerConfig config = DhcpServerConfiguration.parseConfig(filename);
                if (config != null) {
                    System.err.println("OK: " + filename + " is a valid DHCPv6 server configuration file.");
                }
            } catch (Exception ex) {
                System.err.println("ERROR: " + ex);
            }
            System.exit(0);
        }
        if (cmd.hasOption("li")) {
            Enumeration<NetworkInterface> netIfs = NetworkInterface.getNetworkInterfaces();
            if (netIfs != null) {
                while (netIfs.hasMoreElements()) {
                    NetworkInterface ni = netIfs.nextElement();
                    System.err.println(ni);
                }
            }
            System.exit(0);
        }
    } catch (ParseException pe) {
        System.err.println("Command line option parsing failure: " + pe);
        return false;
    } catch (SocketException se) {
        System.err.println("Network interface socket failure: " + se);
        return false;
    } catch (UnknownHostException he) {
        System.err.println("IP Address failure: " + he);
    }

    return true;
}

From source file:org.apache.solr.cloud.ZkController.java

private String normalizeHostName(String host) throws IOException {

    if (host == null || host.length() == 0) {
        String hostaddress;//  w  w w .j a  v a2  s  .  co  m
        try {
            hostaddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            hostaddress = "127.0.0.1"; // cannot resolve system hostname, fall through
        }
        // Re-get the IP again for "127.0.0.1", the other case we trust the hosts
        // file is right.
        if ("127.0.0.1".equals(hostaddress)) {
            Enumeration<NetworkInterface> netInterfaces = null;
            try {
                netInterfaces = NetworkInterface.getNetworkInterfaces();
                while (netInterfaces.hasMoreElements()) {
                    NetworkInterface ni = netInterfaces.nextElement();
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        InetAddress ip = ips.nextElement();
                        if (ip.isSiteLocalAddress()) {
                            hostaddress = ip.getHostAddress();
                        }
                    }
                }
            } catch (Exception e) {
                SolrException.log(log, "Error while looking for a better host name than 127.0.0.1", e);
            }
        }
        host = hostaddress;
    } else {
        if (URLUtil.hasScheme(host)) {
            host = URLUtil.removeScheme(host);
        }
    }

    return host;
}

From source file:com.distrimind.madkit.kernel.MadkitProperties.java

private static long getMacAddress() {
    long result = 0;
    long result2 = 0;
    try {//from  w  ww . j a va 2 s. c o  m
        final Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            final NetworkInterface ni = e.nextElement();

            if (!ni.isLoopback()) {

                long val = getHardwareAddress(ni.getHardwareAddress());
                if (val != 0 && val != 224) {
                    if (ni.isPointToPoint()) {
                        result2 = val;
                    } else {
                        result = val;
                        break;
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (result == 0)
        result = result2;
    return result;

}

From source file:com.httrack.android.HTTrackActivity.java

/**
 * Return the IPv6 address./*from  ww  w .ja v  a  2 s .co  m*/
 * 
 * @return The ipv6 address, or @c null if no IPv6 connectivity is available.
 */
protected static InetAddress getIPv6Address() {
    try {
        for (final Enumeration<NetworkInterface> interfaces = NetworkInterface
                .getNetworkInterfaces(); interfaces.hasMoreElements();) {
            final NetworkInterface iface = interfaces.nextElement();
            for (final Enumeration<InetAddress> addresses = iface.getInetAddresses(); addresses
                    .hasMoreElements();) {
                final InetAddress address = addresses.nextElement();
                Log.d(HTTrackActivity.class.getSimpleName(), "seen interface: " + address.toString());
                if (address instanceof Inet6Address) {
                    if (!address.isLoopbackAddress() && !address.isLinkLocalAddress()
                            && !address.isSiteLocalAddress() && !address.isMulticastAddress()) {
                        return address;
                    }
                }
            }
        }
    } catch (final SocketException se) {
        Log.w(HTTrackActivity.class.getSimpleName(), "could not enumerate interfaces", se);
    }
    return null;
}

From source file:org.apache.hadoop.hdfs.MiniAvatarCluster.java

/**
 * Retrieves the name of the loopback interface in a platform independent way.
 *//*from   ww  w  .j  a va 2  s .  c  o  m*/
private static String getLoopBackInterface() throws IOException {
    String loopBack = "lo";
    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        if (iface.isLoopback()) {
            loopBack = iface.getName();
            break;
        }
    }
    return loopBack;
}

From source file:sce.JobStoreTXCustom.java

public static String getIpAddress() {
    if (ip == null) {
        try {/*  w w  w. ja  v a2s. co  m*/
            for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = (NetworkInterface) en.nextElement();
                for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        String ipAddress = inetAddress.getHostAddress().toString();
                        ip = (ip == null ? "" : ip + ";") + ipAddress;
                    }
                }
            }
        } catch (SocketException e) {
            return "";
        }
    }
    return ip;
}

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

public static String getNetworkInfo(Context context) {
    StringBuilder sb = new StringBuilder();
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ani = cm.getActiveNetworkInfo();
    List<NetworkInfo> listNI = new ArrayList<>();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        listNI.addAll(Arrays.asList(cm.getAllNetworkInfo()));
    else//  w w  w .ja  v  a 2  s  .co m
        for (Network network : cm.getAllNetworks()) {
            NetworkInfo ni = cm.getNetworkInfo(network);
            if (ni != null)
                listNI.add(ni);
        }

    for (NetworkInfo ni : listNI) {
        sb.append(ni.getTypeName()).append('/').append(ni.getSubtypeName()).append(' ')
                .append(ni.getDetailedState())
                .append(TextUtils.isEmpty(ni.getExtraInfo()) ? "" : " " + ni.getExtraInfo())
                .append(ni.getType() == ConnectivityManager.TYPE_MOBILE
                        ? " " + Util.getNetworkGeneration(ni.getSubtype())
                        : "")
                .append(ni.isRoaming() ? " R" : "")
                .append(ani != null && ni.getType() == ani.getType() && ni.getSubtype() == ani.getSubtype()
                        ? " *"
                        : "")
                .append("\r\n");
    }

    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        if (nis != null)
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                if (ni != null && !ni.isLoopback()) {
                    List<InterfaceAddress> ias = ni.getInterfaceAddresses();
                    if (ias != null)
                        for (InterfaceAddress ia : ias)
                            sb.append(ni.getName()).append(' ').append(ia.getAddress().getHostAddress())
                                    .append('/').append(ia.getNetworkPrefixLength()).append(' ')
                                    .append(ni.getMTU()).append(' ').append(ni.isUp() ? '^' : 'v')
                                    .append("\r\n");
                }
            }
    } catch (Throwable ex) {
        sb.append(ex.toString()).append("\r\n");
    }

    if (sb.length() > 2)
        sb.setLength(sb.length() - 2);

    return sb.toString();
}

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

public static String getNetworkInfo(Context context) {
    StringBuilder sb = new StringBuilder();
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ani = cm.getActiveNetworkInfo();
    List<NetworkInfo> listNI = new ArrayList<>();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        listNI.addAll(Arrays.asList(cm.getAllNetworkInfo()));
    else//  w  w w . ja  v a 2 s.c om
        for (Network network : cm.getAllNetworks()) {
            NetworkInfo ni = cm.getNetworkInfo(network);
            if (ni != null)
                listNI.add(ni);
        }

    for (NetworkInfo ni : listNI) {
        sb.append(ni.getTypeName()).append('/').append(ni.getSubtypeName()).append(' ')
                .append(ni.getDetailedState())
                .append(TextUtils.isEmpty(ni.getExtraInfo()) ? "" : " " + ni.getExtraInfo())
                .append(ni.getType() == ConnectivityManager.TYPE_MOBILE
                        ? " " + Util.getNetworkGeneration(ni.getSubtype())
                        : "")
                .append(ni.isRoaming() ? " R" : "")
                .append(ani != null && ni.getType() == ani.getType() && ni.getSubtype() == ani.getSubtype()
                        ? " *"
                        : "")
                .append("\r\n");
    }

    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        if (nis != null) {
            sb.append("\r\n");
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                if (ni != null) {
                    List<InterfaceAddress> ias = ni.getInterfaceAddresses();
                    if (ias != null)
                        for (InterfaceAddress ia : ias)
                            sb.append(ni.getName()).append(' ').append(ia.getAddress().getHostAddress())
                                    .append('/').append(ia.getNetworkPrefixLength()).append(' ')
                                    .append(ni.getMTU()).append("\r\n");
                }
            }
        }
    } catch (Throwable ex) {
        sb.append(ex.toString()).append("\r\n");
    }

    if (sb.length() > 2)
        sb.setLength(sb.length() - 2);

    return sb.toString();
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

public static InetAddress getLocalInetAddress() throws SocketException {
    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()
                    && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
                return inetAddress;
            }//from  w w  w  . j  av  a 2 s. com
        }
    }

    return null;
}