Android 장치의 MAC를 프로그래밍 방식으로 가져오기
자바를 사용하여 안드로이드 기기의 MAC 주소를 취득해야 합니다.인터넷을 검색해 봤지만, 쓸 만한 것을 찾지 못했어요.
이미 댓글에 지적된 바와 같이 MAC 주소는 WiFi Manager를 통해 수신할 수 있습니다.
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String address = info.getMacAddress();
, 을 「」에 말아 .AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
사용자에게 더 나은 데이터 보호를 제공하기 위해 이 릴리스부터 Android는 Wi-Fi 및 Bluetooth API를 사용하는 앱에 대한 장치의 로컬 하드웨어 식별자에 대한 프로그램 액세스를 제거합니다.WiFiInfo.getMacAddress() 메서드와 BluetoothAdapter.getAddress() 메서드가 02:00:00:00:00:00의 상수값을 반환합니다.
Bluetooth 및 Wi-Fi 스캔을 통해 인근 외부 장치의 하드웨어 식별자에 액세스하려면 앱에 ACCESS_FINE_LOCATION 또는 ACCESS_COARS_LOCATION 권한이 있어야 합니다.
MAC 주소를 통과시키는 것은 마시멜로 이상에서는 동작하지 않습니다.이러한 주소는 비활성화되어 있으며,의 상수 값을 반환합니다.
public static String getMacAddr() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:",b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
}
return "02:00:00:00:00:00";
}
저는 http://robinhenniges.com/en/android6-get-mac-address-programmatically에서 이 솔루션을 개발했고, 이 솔루션은 저에게 효과가 있습니다.희망은 도움이 된다!
public static String getMacAddr() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1)
hex = "0".concat(hex);
res1.append(hex.concat(":"));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
}
return "";
}
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
public String getMacAddress(Context context) {
WifiManager wimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wimanager.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Device don't have mac address or wi-fi is disabled";
}
return macAddress;
}
다른 방법이 있다
마시멜로와의 연계
package com.keshav.fetchmacaddress;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("keshav","getMacAddr -> " +getMacAddr());
}
public static String getMacAddr() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(Integer.toHexString(b & 0xFF) + ":");
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
//handle exception
}
return "";
}
}
안드로이드 디바이스의 하드웨어 MAC 주소를 더 이상 얻을 수 없습니다.WifiInfo.getMacAddress() 및 BluetoothAdapter.getAddress() 메서드는 02:00:00:00:00:00:00를 반환합니다.이 제한은 Android 6.0에서 도입되었습니다.
그러나 Rob Anderson은 < 마시멜로: https://stackoverflow.com/a/35830358>에 유효한 솔루션을 발견했습니다.
MAC 주소를 얻을 수 있습니다.
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String mac = wInfo.getMacAddress();
Menifest.xml에서 권한 설정
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
이 간단한 방법 사용
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
String WLANMAC = wm.getConnectionInfo().getMacAddress();
여기 Android 소스에서 가져온 것입니다.시스템 설정 앱에 MAC 주소가 표시되는 실제 코드입니다.
private void refreshWifiInfo() {
WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
Preference wifiMacAddressPref = findPreference(KEY_MAC_ADDRESS);
String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress();
wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress
: getActivity().getString(R.string.status_unavailable));
Preference wifiIpAddressPref = findPreference(KEY_CURRENT_IP_ADDRESS);
String ipAddress = Utils.getWifiIpAddresses(getActivity());
wifiIpAddressPref.setSummary(ipAddress == null ?
getActivity().getString(R.string.status_unavailable) : ipAddress);
}
매우 오래된 질문인 것은 알지만, 이것을 할 수 있는 방법이 하나 더 있습니다.아래 코드는 오류 없이 컴파일되지만 저는 시도해보지 않았습니다.일부 C 코드를 작성하고 Java Native Interface(JNI; Java 네이티브인터페이스)를 사용하여 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 함수의 구현.
/* 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;
}
마지막으로 CMake Lists입니다.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)
이것.ip link | grep -A1 wlan0명령어는 Termux에서 wifi 하드웨어 주소를 확인하는 방법에서 Android 9에서 작동합니다.
LOCATION 허가 없이 MAC 주소를 읽는 방법을 찾은 것 같습니다.달려.ip link그 출력을 해석합니다.(아마도 이 바이너리의 소스 코드를 보면 비슷한 작업을 할 수 있을 것입니다.)
언급URL : https://stackoverflow.com/questions/11705906/programmatically-getting-the-mac-of-an-android-device
'programing' 카테고리의 다른 글
| 날짜/시간 또는 타임스탬프를 사용할 때 (0) | 2022.11.04 |
|---|---|
| 현재 날짜를 Java 문자열로 변환하려면 어떻게 해야 합니까? (0) | 2022.11.04 |
| 선택 쿼리를 사용하여 테이블 업데이트 (0) | 2022.11.04 |
| store/index.js의 내보내기 외부 상태에 액세스하는 방법 (0) | 2022.11.04 |
| JavaScript 어레이를 쉼표로 구분된 목록으로 쉽게 변환할 수 있습니까? (0) | 2022.11.04 |