我知道这是一个非常古老的问题,但还有另一种方法可以做到这一点。下面的代码可以编译,但我还没有尝试过。
您可以编写一些 C 代码并使用 JNI(Java Native Interface)来获取 MAC 地址。
这是示例主要活动代码:
package com.example.getmymac;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class GetMyMacActivity extends AppCompatActivity {
static { // here we are importing native library.
// name of the library is libnet-utils.so, in cmake and java code
// we just use name "net-utils".
System.loadLibrary("net-utils");
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
// some debug text and a TextView.
Log.d(NetUtilsActivity.class.getSimpleName(), "Starting app...");
TextView text = findViewById(R.id.sample_text);
// the get_mac_addr native function, implemented in C code.
byte[] macArr = get_mac_addr(null);
// since it is a byte array, we format it and convert to string.
String val = String.format("%02x:%02x:%02x:%02x:%02x:%02x",
macArr[0], macArr[1], macArr[2],
macArr[3], macArr[4], macArr[5]);
// print it to log and TextView.
Log.d(NetUtilsActivity.class.getSimpleName(), val);
text.setText(val);
}
// here is the prototype of the native function.
// use native keyword to indicate it is a native function,
// implemented in C code.
private native byte[] get_mac_addr(String interface_name);
}
还有布局文件,main_screen.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/sample_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
清单文件,我不知道要添加什么权限,所以我添加了一些。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.getmymac">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".GetMyMacActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
get_mac_addr 函数的 C 实现。
/* length of array that MAC address is stored. */
#define MAC_ARR_LEN 6
#define BUF_SIZE 256
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <unistd.h>
#define ERROR_IOCTL 1
#define ERROR_SOCKT 2
static jboolean
cstr_eq_jstr(JNIEnv *env, const char *cstr, jstring jstr) {
/* see [this](https://stackoverflow.com/a/38204842) */
jstring cstr_as_jstr = (*env)->NewStringUTF(env, cstr);
jclass cls = (*env)->GetObjectClass(env, jstr);
jmethodID method_id = (*env)->GetMethodID(env, cls, "equals", "(Ljava/lang/Object;)Z");
jboolean equal = (*env)->CallBooleanMethod(env, jstr, method_id, cstr_as_jstr);
return equal;
}
static void
get_mac_by_ifname(jchar *ifname, JNIEnv *env, jbyteArray arr, int *error) {
/* see [this](https://stackoverflow.com/a/1779758) */
struct ifreq ir;
struct ifconf ic;
char buf[BUF_SIZE];
int ret = 0, sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock == -1) {
*error = ERROR_SOCKT;
return;
}
ic.ifc_len = BUF_SIZE;
ic.ifc_buf = buf;
ret = ioctl(sock, SIOCGIFCONF, &ic);
if (ret) {
*error = ERROR_IOCTL;
goto err_cleanup;
}
struct ifreq *it = ic.ifc_req; /* iterator */
struct ifreq *end = it + (ic.ifc_len / sizeof(struct ifreq));
int found = 0; /* found interface named `ifname' */
/* while we find an interface named `ifname' or arrive end */
while (it < end && found == 0) {
strcpy(ir.ifr_name, it->ifr_name);
ret = ioctl(sock, SIOCGIFFLAGS, &ir);
if (ret == 0) {
if (!(ir.ifr_flags & IFF_LOOPBACK)) {
ret = ioctl(sock, SIOCGIFHWADDR, &ir);
if (ret) {
*error = ERROR_IOCTL;
goto err_cleanup;
}
if (ifname != NULL) {
if (cstr_eq_jstr(env, ir.ifr_name, ifname)) {
found = 1;
}
}
}
} else {
*error = ERROR_IOCTL;
goto err_cleanup;
}
++it;
}
/* copy the MAC address to byte array */
(*env)->SetByteArrayRegion(env, arr, 0, 6, ir.ifr_hwaddr.sa_data);
/* cleanup, close the socket connection */
err_cleanup: close(sock);
}
JNIEXPORT jbyteArray JNICALL
Java_com_example_getmymac_GetMyMacActivity_get_1mac_1addr(JNIEnv *env, jobject thiz,
jstring interface_name) {
/* first, allocate space for the MAC address. */
jbyteArray mac_addr = (*env)->NewByteArray(env, MAC_ARR_LEN);
int error = 0;
/* then just call `get_mac_by_ifname' function */
get_mac_by_ifname(interface_name, env, mac_addr, &error);
return mac_addr;
}
最后是 CMakeLists.txt 文件
cmake_minimum_required(VERSION 3.4.1)
add_library(net-utils SHARED src/main/cpp/net-utils.c)
target_link_libraries(net-utils android log)