Search code examples
javanetwork-interface

Determine which NetworkInterface is currently being used


I am trying to figure out which network interface is currently being used by the local machine. I can use NetworkInterface.getNetworkInterfaces() to get all the interfaces installed on my machine, but I cannot determine which interface the computer is using to access the internet.

I tried to filter out the inactive and loop-back interfaces, then print the remaining ones:

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
    NetworkInterface face = interfaces.nextElement();

    if (face.isLoopback() || !face.isUp()) {
        continue;
    }

    System.out.println(face.getDisplayName());
}

The results are below:

Qualcomm Atheros AR9485 802.11b/g/n WiFi Adapter
Microsoft ISATAP Adapter #5

As you can see, there are two interfaces listed. The one my computer is currently using to connect to the internet is the Qualcomm Atheros adapter. I could just test the interface name to see if it was the Qualcomm adapter, but this would only work until I used the other Qualcomm adapter to establish an Ethernet connection.

I saw a similar question on Superuser that determined the route based on the metric.

Is there a clean way of doing this in Java?


Solution

  • I found a neat little way to do this:

    public static NetworkInterface getCurrentInterface() throws SocketException, UnknownHostException {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress myAddr = InetAddress.getLocalHost();
        while (interfaces.hasMoreElements()) {
            NetworkInterface face = interfaces.nextElement();
    
            if (Collections.list(face.getInetAddresses()).contains(myAddr))
                return face;
        }
        return null;
    }
    

    As you can see, I simply iterate through the network interfaces and check each one to see if the local host is bound to it. So far, I have not had any problems with this method.