Java Network Interface Get getAllAvailableInterfaces()

Here you can find the source of getAllAvailableInterfaces()

Description

get All Available Interfaces

License

Apache License

Declaration

public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;

public class Main {
    public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException {
        List<NetworkInterface> allInterfaces = new ArrayList<>();
        for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces
                .hasMoreElements();) {/*from   w ww .j a v a 2 s . c om*/
            NetworkInterface networkInterface = interfaces.nextElement();
            allInterfaces.add(networkInterface);
            Enumeration<NetworkInterface> subInterfaces = networkInterface.getSubInterfaces();
            if (subInterfaces.hasMoreElements()) {
                while (subInterfaces.hasMoreElements()) {
                    allInterfaces.add(subInterfaces.nextElement());
                }
            }
        }
        sortInterfaces(allInterfaces);
        return allInterfaces;
    }

    private static List<NetworkInterface> getNetworkInterfaces() throws SocketException {
        List<NetworkInterface> networkInterfaces = new ArrayList<>();
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            networkInterfaces.add(networkInterface);
            Enumeration<NetworkInterface> subInterfaces = networkInterface.getSubInterfaces();
            if (subInterfaces.hasMoreElements()) {
                while (subInterfaces.hasMoreElements()) {
                    networkInterfaces.add(subInterfaces.nextElement());
                }
            }
        }
        sortInterfaces(networkInterfaces);
        return networkInterfaces;
    }

    private static void sortInterfaces(List<NetworkInterface> interfaces) {
        Collections.sort(interfaces, new Comparator<NetworkInterface>() {
            @Override
            public int compare(NetworkInterface o1, NetworkInterface o2) {
                return Integer.compare(o1.getIndex(), o2.getIndex());
            }
        });
    }
}

Related

  1. enumerateInterfaces()
  2. getAllAvailableInterfaces()
  3. getAllAvailableInterfaces()
  4. getAllInterfaces()
  5. getAllInterfaces()
  6. getAllLocalInterfaces()
  7. getAllLocalUsingNetworkInterface()