Java Mac Address Get getMACAddress()

Here you can find the source of getMACAddress()

Description

Returns the MacAddress of the first physical network interface or a default MacAddress if the there are no network interfaces.

License

Apache License

Return

byte[] MacAddress of the first physical Network Interface or default

Declaration

public static synchronized byte[] getMACAddress() 

Method Source Code

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

import java.net.NetworkInterface;

import java.util.Enumeration;

public class Main {
    public static final byte[] MAC_ADDRESS_DEFAULT = { (byte) 0, (byte) 0x17, (byte) 0x9A, (byte) 0x2D, (byte) 0x78,
            (byte) 0xEF };
    private static byte[] macAddress = MAC_ADDRESS_DEFAULT;

    /**/*from w w w.  ja  v  a2 s . c  o m*/
     * Returns the MacAddress of the first physical network interface or a default
     * MacAddress if the there are no network interfaces.  The default MacAddress
     * is from a D-Link router that was taken out of circulation.
     *
     * @return  byte[]      MacAddress of the first physical Network Interface or default
     */
    public static synchronized byte[] getMACAddress() {

        // Once we find a non-default MAC Address, use it
        if (macAddress == MAC_ADDRESS_DEFAULT) {
            // Try to get MAC Address is MAC address is using default value
            try {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                byte[] mac = null;

                // Find first interface that isn't
                while (interfaces.hasMoreElements() && (mac == null || mac.length != 6)) {
                    NetworkInterface netInterface = interfaces.nextElement();

                    // Skip Loopback and Virtual Interfaces
                    if (netInterface.isLoopback() || netInterface.isVirtual()) {
                        continue;
                    }

                    mac = netInterface.getHardwareAddress();
                }

                // If NetworkInterface is found then use it.  Otherwise node will be default
                if (mac != null) {
                    macAddress = mac;
                }

            } catch (Exception e) {
                throw new RuntimeException("Could not get MAC address");
            }
        }

        return macAddress;
    }
}

Related

  1. getMac()
  2. getMacAddr()
  3. getMacAddress()
  4. getMACAddress()
  5. getMacAddress()
  6. getMacAddress()
  7. getMacAddress()
  8. getMacAddress()
  9. getMacAddress()