Java Network Interface Get getDefaultNetworkInterface()

Here you can find the source of getDefaultNetworkInterface()

Description

Selects the default network interface

License

Open Source License

Return

network interface

Declaration

public static NetworkInterface getDefaultNetworkInterface() 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class Main {
    /**//from   w  ww  .  ja  v a 2  s. c o m
     * Selects the default network interface
     * @return network interface
     */
    public static NetworkInterface getDefaultNetworkInterface() {
        try {
            Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
            while (networks.hasMoreElements()) {
                NetworkInterface ni = networks.nextElement();
                Enumeration<InetAddress> addresses = ni.getInetAddresses();
                boolean hasAddress = false;
                while (addresses.hasMoreElements()) {
                    InetAddress ia = addresses.nextElement();
                    if (!(ia.isAnyLocalAddress() || ia.isLinkLocalAddress() || ia.isLoopbackAddress()
                            || ia.isSiteLocalAddress() || ni.isPointToPoint())) {
                        if (!hasAddress) {
                            return ni;
                        }
                    }
                }
            }
        } catch (Exception ex) {

        }
        return null;
    }
}

Related

  1. getAllLocalUsingNetworkInterface()
  2. getAvailableNetworkInterface()
  3. getBroadcast()
  4. getCustomMACFormat(NetworkInterface inte)
  5. getDefaultInterface()
  6. getFirstMACAdress()
  7. getFreeTunnelInterface()
  8. getGlobalI()
  9. getGlobalInterfaces()