std::string getMacAddress(JNIEnv* env) {
//通过JNI找到java中的NetworkInterface类
jclass cls_networkInterface = env->FindClass("java/net/NetworkInterface");
if (cls_networkInterface == 0) {
return "";
}
//找到getByName方法
jmethodID jmethodID_getByName =
env->GetStaticMethodID(cls_networkInterface, "getByName",
"(Ljava/lang/String;)Ljava/net/NetworkInterface;");
if (jmethodID_getByName == 0) {
return "";
}
jstring wlan = env->NewStringUTF("wlan0");
//调用getByname方法返回NetworkInterface的实例
jobject jobject_networkInterface = env->CallStaticObjectMethod(
cls_networkInterface, jmethodID_getByName, wlan);
//找到getHardAddress方法
jmethodID jmethodID_getHardwareAddress =
env->GetMethodID(cls_networkInterface, "getHardwareAddress", "()[B");
if (jmethodID_getHardwareAddress == 0) {
return "";
}
//调用getHardAddress方法获取MAC地址的byte[]数组
jbyteArray jbyte_mac = (jbyteArray)env->CallObjectMethod(
jobject_networkInterface, jmethodID_getHardwareAddress);
jsize oldsize = env->GetArrayLength(jbyte_mac);
int len = (int)oldsize;
char* data = (char*)env->GetByteArrayElements(jbyte_mac, 0);
std::string MacAddress;
MacAddress.reserve(len * 2);
char buffer[3] = {0};
for (int i = 0; i < len; i++) {
snprintf(buffer, sizeof(buffer), "%02X", data[i]);
MacAddress.append(buffer);
}
return MacAddress;
}