get Mac Address - Android java.net

Android examples for java.net:Mac Address

Description

get Mac Address

Demo Code

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

public class Main {

  private static byte[] mMacAddress = null;

  public static byte[] getMacAddress() {
    final int hwAddrLengthInBytes = 6;
    if (mMacAddress == null) {
      try {/*w w w  .j a v a  2  s. c  o  m*/
        Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();

        while (netInterfaces.hasMoreElements()) {
          NetworkInterface ni = netInterfaces.nextElement();
          byte[] addrBytes = ni.getHardwareAddress();
          if (!ni.isLoopback() && addrBytes != null && hwAddrLengthInBytes == addrBytes.length) {
            mMacAddress = addrBytes;
            break;
          }
        }
      } catch (SocketException e) {
        e.printStackTrace();
      }

      if (null == mMacAddress) {
        mMacAddress = new byte[hwAddrLengthInBytes];
        for (int i = 0; i < hwAddrLengthInBytes; ++i) {
          mMacAddress[i] = (byte) (Math.random() * 0xff);
        }
      }
    }

    return mMacAddress;
  }

}

Related Tutorials