Android development obtains mobile phone Mac address adapts to all Android versions

  • 2021-11-29 08:25:35
  • OfStack

Recently, due to the need for the record of MAC address in the project, a general adaptation class has been developed. At present, it can adapt to all versions of Android after testing. The equipment system Android 4 5 6 7 7 + I have tested can be obtained. It is simple and simple to go directly to the code without saying much nonsense:

This class is divided into three categories: Android below 6.0, above 6.0, below 7.0 and above 7.0

The first is to get the integration method of MAC:


public static String getMac(Context context) {
 
    String strMac = null;
 
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
      Log.e("=====", "6.0 The following ");
      Toast.makeText(context, "6.0 The following ", Toast.LENGTH_SHORT).show();
      strMac = getLocalMacAddressFromWifiInfo(context);
      return strMac;
    } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N
        && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      Log.e("=====", "6.0 Above 7.0 The following ");
      Toast.makeText(context, "6.0 Above 7.0 The following ", Toast.LENGTH_SHORT).show();
      strMac = getMacAddress(context);
      return strMac;
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
      Log.e("=====", "7.0 Above ");
      if (!TextUtils.isEmpty(getMacAddress())) {
        Log.e("=====", "7.0 Above 1");
        Toast.makeText(context, "7.0 Above 1", Toast.LENGTH_SHORT).show();
        strMac = getMacAddress();
        return strMac;
      } else if (!TextUtils.isEmpty(getMachineHardwareAddress())) {
        Log.e("=====", "7.0 Above 2");
        Toast.makeText(context, "7.0 Above 2", Toast.LENGTH_SHORT).show();
        strMac = getMachineHardwareAddress();
        return strMac;
      } else {
        Log.e("=====", "7.0 Above 3");
        Toast.makeText(context, "7.0 Above 3", Toast.LENGTH_SHORT).show();
        strMac = getLocalMacAddressFromBusybox();
        return strMac;
      }
    }
 
    return "02:00:00:00:00:00";
  }

6.0 The following methods, public methods provided by Google, require permissions

< uses-permission android:name="android.permission.ACCESS_WIFI_STATE" / >


/**
   *  According to wifi Information acquisition local mac
   * @param context
   * @return
   */
  public static String getLocalMacAddressFromWifiInfo(Context context){
    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo winfo = wifi.getConnectionInfo();
    String mac = winfo.getMacAddress();
    return mac;
  }

android 6.0 and above, 7.0 and below

After android 6.0, mac can no longer be obtained through wifimanager, and the obtained mac will be fixed: 02:00: 00:00: 00:00.

However, the sdk I developed is the mac obtained through wifimanager.

android sdk was later adapted to 6.0, and mac address can be obtained on 6.0 through cat/sys/class/net/wlan0/address.


 /**
   * android 6.0 And above, 7.0 The following   Get mac Address 
   *
   * @param context
   * @return
   */
  public static String getMacAddress(Context context) {
 
    //  If it is 6.0 Below, directly through wifimanager Get 
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
      String macAddress0 = getMacAddress0(context);
      if (!TextUtils.isEmpty(macAddress0)) {
        return macAddress0;
      }
    }
    String str = "";
    String macSerial = "";
    try {
      Process pp = Runtime.getRuntime().exec(
          "cat /sys/class/net/wlan0/address");
      InputStreamReader ir = new InputStreamReader(pp.getInputStream());
      LineNumberReader input = new LineNumberReader(ir);
      for (; null != str; ) {
        str = input.readLine();
        if (str != null) {
          macSerial = str.trim();//  To blanks 
          break;
        }
      }
    } catch (Exception ex) {
      Log.e("----->" + "NetInfoManager", "getMacAddress:" + ex.toString());
    }
    if (macSerial == null || "".equals(macSerial)) {
      try {
        return loadFileAsString("/sys/class/net/eth0/address")
            .toUpperCase().substring(0, 17);
      } catch (Exception e) {
        e.printStackTrace();
        Log.e("----->" + "NetInfoManager",
            "getMacAddress:" + e.toString());
      }
 
    }
    return macSerial;
  }
 
  private static String getMacAddress0(Context context) {
    if (isAccessWifiStateAuthorized(context)) {
      WifiManager wifiMgr = (WifiManager) context
          .getSystemService(Context.WIFI_SERVICE);
      WifiInfo wifiInfo = null;
      try {
        wifiInfo = wifiMgr.getConnectionInfo();
        return wifiInfo.getMacAddress();
      } catch (Exception e) {
        Log.e("----->" + "NetInfoManager",
            "getMacAddress0:" + e.toString());
      }
 
    }
    return "";
 
  }
 
  /**
   * Check whether accessing wifi state is permitted
   *
   * @param context
   * @return
   */
  private static boolean isAccessWifiStateAuthorized(Context context) {
    if (PackageManager.PERMISSION_GRANTED == context
        .checkCallingOrSelfPermission("android.permission.ACCESS_WIFI_STATE")) {
      Log.e("----->" + "NetInfoManager", "isAccessWifiStateAuthorized:"
          + "access wifi state is enabled");
      return true;
    } else
      return false;
  }
 
  private static String loadFileAsString(String fileName) throws Exception {
    FileReader reader = new FileReader(fileName);
    String text = loadReaderAsString(reader);
    reader.close();
    return text;
  }
 
  private static String loadReaderAsString(Reader reader) throws Exception {
    StringBuilder builder = new StringBuilder();
    char[] buffer = new char[4096];
    int readLength = reader.read(buffer);
    while (readLength >= 0) {
      builder.append(buffer, 0, readLength);
      readLength = reader.read(buffer);
    }
    return builder.toString();
  }

android 7.0 and above

After android 7.0, the mac address will not be obtained by the above adaptation method.

After investigation and testing, there is still a way to go back to mac address on 7.0:

There are three ways in total:

Get the bound mac address through the ip address Scan each network interface to obtain mac address Get the locally stored mac address through busybox

The code is as follows:


/**
   *  According to IP Address acquisition MAC Address 
   *
   * @return
   */
  public static String getMacAddress() {
    String strMacAddr = null;
    try {
      //  Obtain IpD Address 
      InetAddress ip = getLocalInetAddress();
      byte[] b = NetworkInterface.getByInetAddress(ip)
          .getHardwareAddress();
      StringBuffer buffer = new StringBuffer();
      for (int i = 0; i < b.length; i++) {
        if (i != 0) {
          buffer.append(':');
        }
        String str = Integer.toHexString(b[i] & 0xFF);
        buffer.append(str.length() == 1 ? 0 + str : str);
      }
      strMacAddr = buffer.toString().toUpperCase();
    } catch (Exception e) {
    }
    return strMacAddr;
  }
/**
   *  Get mobile device local IP
   *
   * @return
   */
  private static InetAddress getLocalInetAddress() {
    InetAddress ip = null;
    try {
      //  Enumerate 
      Enumeration<NetworkInterface> en_netInterface = NetworkInterface
          .getNetworkInterfaces();
      while (en_netInterface.hasMoreElements()) {//  Are there any more elements 
        NetworkInterface ni = (NetworkInterface) en_netInterface
            .nextElement();//  Get the following 1 Elements 
        Enumeration<InetAddress> en_ip = ni.getInetAddresses();//  Get 1 A ip Enumeration of addresses 
        while (en_ip.hasMoreElements()) {
          ip = en_ip.nextElement();
          if (!ip.isLoopbackAddress()
              && ip.getHostAddress().indexOf(":") == -1)
            break;
          else
            ip = null;
        }
 
        if (ip != null) {
          break;
        }
      }
    } catch (SocketException e) {
 
      e.printStackTrace();
    }
    return ip;
  }
 
  /**
   *  Get local IP
   *
   * @return
   */
  private static String getLocalIpAddress() {
    try {
      for (Enumeration<NetworkInterface> en = NetworkInterface
          .getNetworkInterfaces(); en.hasMoreElements(); ) {
        NetworkInterface intf = en.nextElement();
        for (Enumeration<InetAddress> enumIpAddr = intf
            .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
          InetAddress inetAddress = enumIpAddr.nextElement();
          if (!inetAddress.isLoopbackAddress()) {
            return inetAddress.getHostAddress().toString();
          }
        }
      }
    } catch (SocketException ex) {
      ex.printStackTrace();
    }
    return null;
  }

 /**
   * android 7.0 And above   ( 2 ) Scanning various network interfaces for mac Address 
   *
   */
  /**
   *  Acquisition device HardwareAddress Address 
   *
   * @return
   */
  public static String getMachineHardwareAddress() {
    Enumeration<NetworkInterface> interfaces = null;
    try {
      interfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
      e.printStackTrace();
    }
    String hardWareAddress = null;
    NetworkInterface iF = null;
    if (interfaces == null) {
      return null;
    }
    while (interfaces.hasMoreElements()) {
      iF = interfaces.nextElement();
      try {
        hardWareAddress = bytesToString(iF.getHardwareAddress());
        if (hardWareAddress != null)
          break;
      } catch (SocketException e) {
        e.printStackTrace();
      }
    }
    return hardWareAddress;
  }
 
  /***
   * byte Convert to String
   *
   * @param bytes
   * @return
   */
  private static String bytesToString(byte[] bytes) {
    if (bytes == null || bytes.length == 0) {
      return null;
    }
    StringBuilder buf = new StringBuilder();
    for (byte b : bytes) {
      buf.append(String.format("%02X:", b));
    }
    if (buf.length() > 0) {
      buf.deleteCharAt(buf.length() - 1);
    }
    return buf.toString();
  }

 /**
   * android 7.0 And above   ( 3 ) Pass busybox Gets the locally stored mac Address 
   *
   */
 
  /**
   *  According to busybox Get local Mac
   *
   * @return
   */
  public static String getLocalMacAddressFromBusybox() {
    String result = "";
    String Mac = "";
    result = callCmd("busybox ifconfig", "HWaddr");
    //  If the returned result == null The network is not desirable 
    if (result == null) {
      return " Network anomaly ";
    }
    //  Parse the data of this row 
    //  For example: eth0 Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67
    if (result.length() > 0 && result.contains("HWaddr") == true) {
      Mac = result.substring(result.indexOf("HWaddr") + 6,
          result.length() - 1);
      result = Mac;
    }
    return result;
  }
 
  private static String callCmd(String cmd, String filter) {
    String result = "";
    String line = "";
    try {
      Process proc = Runtime.getRuntime().exec(cmd);
      InputStreamReader is = new InputStreamReader(proc.getInputStream());
      BufferedReader br = new BufferedReader(is);
 
      while ((line = br.readLine()) != null
          && line.contains(filter) == false) {
        result += line;
      }
 
      result = line;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }

This article mainly explains the Android access to mobile phone Mac address example source code, more about Android access to mobile phone Mac address skills please see the following links


Related articles: