AndroidTV——获取Mac地址

1,380 阅读1分钟

一、核心工具类

亲测 Android9、Android10 可用
注意:前提条件是,必须联网才能获取到Mac地址,否则为null。

/**
 * @author LQR
 * @time 2020/8/24
 * @desc 获取Mac地址工具类
 * <p>
 * 必须在联网的情况下才能获取到mac地址
 */
public class MacUtil {

    private static final String TAG = "MacUtil";

    private MacUtil() {
    }

    /**
     * 获取当前系统连接网络的网卡的mac地址
     */
    public static final String getMac() {
        byte[] mac = null;
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces != null && netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> address = ni.getInetAddresses();
                while (address.hasMoreElements()) {
                    InetAddress ip = address.nextElement();
                    if (ip.isAnyLocalAddress() || !(ip instanceof Inet4Address) || ip.isLoopbackAddress())
                        continue;
                    if (ip.isSiteLocalAddress()) {
                        mac = ni.getHardwareAddress();
                        Log.e(TAG, "获取Mac地址的网卡名:" + ni.getDisplayName());
                    } else if (!ip.isLinkLocalAddress()) {
                        mac = ni.getHardwareAddress();
                        Log.e(TAG, "获取Mac地址的网卡名:" + ni.getDisplayName());
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return getMacString(mac);
    }

    /**
     * 获取wifi模块的mac地址
     */
    public static String getWifiMac() {
        return getNetworkInterfaceMac("wlan0");
    }

    public static String getP2pMac() {
        return getNetworkInterfaceMac("p2p0");
    }

    public static String getIp6tnl0Mac() {
        return getNetworkInterfaceMac("ip6tnl0");
    }

    public static String getIpVti0Mac() {
        return getNetworkInterfaceMac("ip_vti0");
    }

    public static String getLoMac() {
        return getNetworkInterfaceMac("lo");
    }

    public static String getTeql0Mac() {
        return getNetworkInterfaceMac("teql0");
    }

    public static String getSit0Mac() {
        return getNetworkInterfaceMac("sit0");
    }

    public static String getIp6Vti0Mac() {
        return getNetworkInterfaceMac("ip6_vti0");
    }

    /**
     * 获取有线网卡模块的mac地址
     */
    public static String getEthernetMac() {
        return getNetworkInterfaceMac("eth0");
    }

    /**
     * 获取指定网卡mac地址
     */
    private static String getNetworkInterfaceMac(String networkInterfaceName) {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni = networkInterfaces.nextElement();
                if (networkInterfaceName.equals(ni.getName())) {
                    return getMacString(getMacBytes(ni));
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] getMacBytes(NetworkInterface ni) {
        byte[] mac = null;
        try {
            Enumeration<InetAddress> address = ni.getInetAddresses();
            while (address.hasMoreElements()) {
                InetAddress ip = address.nextElement();
                if (ip.isAnyLocalAddress() || !(ip instanceof Inet4Address) || ip.isLoopbackAddress())
                    continue;
                if (ip.isSiteLocalAddress())
                    mac = ni.getHardwareAddress();
                else if (!ip.isLinkLocalAddress()) {
                    mac = ni.getHardwareAddress();
                    break;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return mac;
    }

    private static String getMacString(byte[] mac) {
        if (mac != null) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < mac.length; i++) {
                sb.append(parseByte(mac[i]));
            }
            return sb.substring(0, sb.length() - 1);
        }
        return null;
    }

    private static String parseByte(byte b) {
        String s = "00" + Integer.toHexString(b) + "_";
        return s.substring(s.length() - 3);
    }
}

二、Demo

1、activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_mac"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />

    <TextView
        android:id="@+id/tv_wifi_mac"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />

    <TextView
        android:id="@+id/tv_ethernet_mac"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />

</LinearLayout>

2、MainActivity.java

public class MainActivity extends AppCompatActivity {

    private TextView mTvMac;
    private TextView mTvWifiMac;
    private TextView mTvEthernetMac;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTvMac = findViewById(R.id.tv_mac);
        mTvWifiMac = findViewById(R.id.tv_wifi_mac);
        mTvEthernetMac = findViewById(R.id.tv_ethernet_mac);

        mTvMac.setText("当前上网网卡Mac:" + MacUtil.getMac());
        mTvWifiMac.setText("wifi网卡Mac:" + MacUtil.getWifiMac());
        mTvEthernetMac.setText("ethernet网卡Mac:" + MacUtil.getEthernetMac());
    }
}

3、效果

欢迎关注微信公众号:全栈行动