public static byte [ ] bestAvailableMac ( ) { // Find the best MAC address available. byte [ ] bestMacAddr = EMPTY_BYTES ; InetAddress bestInetAddr = NetUtil . LOCALHOST4 ; // Retrieve the list of available network interfaces. Map < NetworkInterface , InetAddress > ifaces = new LinkedHashMap < NetworkInterface , InetAddress > ( ) ; try { Enumeration < NetworkInterface > interfaces = NetworkInterface . getNetworkInterfaces ( ) ; if ( interfaces != null ) { while ( interfaces . hasMoreElements ( ) ) { NetworkInterface iface = interfaces . nextElement ( ) ; // Use the interface with proper INET addresses only. Enumeration < InetAddress > addrs = SocketUtils . addressesFromNetworkInterface ( iface ) ; if ( addrs . hasMoreElements ( ) ) { InetAddress a = addrs . nextElement ( ) ; if ( ! a . isLoopbackAddress ( ) ) { ifaces . put ( iface , a ) ; } } } } } catch ( SocketException e ) { logger . warn ( "Failed to retrieve the list of available network interfaces" , e ) ; } for ( Entry < NetworkInterface , InetAddress > entry : ifaces . entrySet ( ) ) { NetworkInterface iface = entry . getKey ( ) ; InetAddress inetAddr = entry . getValue ( ) ; if ( iface . isVirtual ( ) ) { continue ; } byte [ ] macAddr ; try { macAddr = SocketUtils . hardwareAddressFromNetworkInterface ( iface ) ; } catch ( SocketException e ) { logger . debug ( "Failed to get the hardware address of a network interface: {}" , iface , e ) ; continue ; } boolean replace = false ; int res = compareAddresses ( bestMacAddr , macAddr ) ; if ( res < 0 ) { // Found a better MAC address. replace = true ; } else if ( res == 0 ) { // Two MAC addresses are of pretty much same quality. res = compareAddresses ( bestInetAddr , inetAddr ) ; if ( res < 0 ) { // Found a MAC address with better INET address. replace = true ; } else if ( res == 0 ) { // Cannot tell the difference. Choose the longer one. if ( bestMacAddr . length < macAddr . length ) { replace = true ; } } } if ( replace ) { bestMacAddr = macAddr ; bestInetAddr = inetAddr ; } } if ( bestMacAddr == EMPTY_BYTES ) { return null ; } switch ( bestMacAddr . length ) { case EUI48_MAC_ADDRESS_LENGTH : // EUI-48 - convert to EUI-64 byte [ ] newAddr = new byte [ EUI64_MAC_ADDRESS_LENGTH ] ; System . arraycopy ( bestMacAddr , 0 , newAddr , 0 , 3 ) ; newAddr [ 3 ] = ( byte ) 0xFF ; newAddr [ 4 ] = ( byte ) 0xFE ; System . arraycopy ( bestMacAddr , 3 , newAddr , 5 , 3 ) ; bestMacAddr = newAddr ; break ; default : // Unknown bestMacAddr = Arrays . copyOf ( bestMacAddr , EUI64_MAC_ADDRESS_LENGTH ) ; } return bestMacAddr ; }
Obtains the best MAC address found on local network interfaces . Generally speaking an active network interface used on public networks is better than a local network interface .