我正在开发一个获取设备MAC地址的应用,但是因为Android 6.0我的代码不起作用,所以给了我一个不正确的值。
这是我的代码......
public String ObtenMAC()
{
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
return(info.getMacAddress().toUpperCase());
}
它不是真正的MAC地址,而是返回一个奇怪的代码:“02:00:00:00:00:00”。
有人可以帮我解决吗?。
答案 0 :(得分:33)
为了向用户提供更好的数据保护,从此版本开始,Android会删除使用Wi-Fi和蓝牙API的应用程序对设备的本地硬件标识符的编程访问。 WifiInfo.getMacAddress()和BluetoothAdapter.getAddress()方法现在返回一个常量值02:00:00:00:00:00。
要通过蓝牙和Wi-Fi扫描访问附近外部设备的硬件标识符,您的应用现在必须具有ACCESS_FINE_LOCATION或ACCESS_COARSE_LOCATION权限。
答案 1 :(得分:26)
使用以下代码在Android 6.0中获取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(Integer.toHexString(b & 0xFF) + ":");
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
//handle exception
}
return "";
}
答案 2 :(得分:13)
我没有得到上述答案,但偶然发现了另一个答案。
这是获取IPv6地址然后从中获取mac地址的完整而简单的方法。
How to get Wi-Fi Mac address in Android Marshmallow
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";
}
已经测试过它并且有效。非常感谢Rob Anderson!
答案 3 :(得分:9)
这是在Marshmallow成功获得它的完整2种方式代码,只需复制过去就可以了!
//Android 6.0 : Access to mac address from WifiManager forbidden
private static final String marshmallowMacAddress = "02:00:00:00:00:00";
private static final String fileAddressMac = "/sys/class/net/wlan0/address";
public static String recupAdresseMAC(WifiManager wifiMan) {
WifiInfo wifiInf = wifiMan.getConnectionInfo();
if(wifiInf.getMacAddress().equals(marshmallowMacAddress)){
String ret = null;
try {
ret= getAdressMacByInterface();
if (ret != null){
return ret;
} else {
ret = getAddressMacByFile(wifiMan);
return ret;
}
} catch (IOException e) {
Log.e("MobileAccess", "Erreur lecture propriete Adresse MAC");
} catch (Exception e) {
Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC ");
}
} else{
return wifiInf.getMacAddress();
}
return marshmallowMacAddress;
}
private static String getAdressMacByInterface(){
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (nif.getName().equalsIgnoreCase("wlan0")) {
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 e) {
Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC ");
}
return null;
}
private static String getAddressMacByFile(WifiManager wifiMan) throws Exception {
String ret;
int wifiState = wifiMan.getWifiState();
wifiMan.setWifiEnabled(true);
File fl = new File(fileAddressMac);
FileInputStream fin = new FileInputStream(fl);
StringBuilder builder = new StringBuilder();
int ch;
while((ch = fin.read()) != -1){
builder.append((char)ch);
}
ret = builder.toString();
fin.close();
boolean enabled = WifiManager.WIFI_STATE_ENABLED == wifiState;
wifiMan.setWifiEnabled(enabled);
return ret;
}
清单:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
摘要:此代码将首先尝试通过接口获取MAC地址,如果失败则由文件系统获取。
注意:对于文件系统方式,您需要启用WIFI才能访问该文件。
thnx对Sam的回答https://stackoverflow.com/a/39288868/3818437
答案 4 :(得分:6)
您可以从IPv6本地地址获取MAC地址。例如,IPv6地址&#34; fe80 :: 1034:56ff:fe78:9abc&#34;对应于MAC地址&#34; 12-34-56-78-9a-bc&#34;。请参阅下面的代码。获取WiFi IPv6地址只需要android.permission.INTERNET。
请参阅维基百科页面IPv6 address,特别是关于&#34;本地地址&#34;的说明。 fe80 :: / 64和关于&#34;修改EUI-64&#34;。
的部分/**
* Gets an EUI-48 MAC address from an IPv6 link-local address.
* E.g., the IPv6 address "fe80::1034:56ff:fe78:9abc"
* corresponds to the MAC address "12-34-56-78-9a-bc".
* <p/>
* See the note about "local addresses" fe80::/64 and the section about "Modified EUI-64" in
* the Wikipedia article "IPv6 address" at https://en.wikipedia.org/wiki/IPv6_address
*
* @param ipv6 An Inet6Address object.
* @return The EUI-48 MAC address as a byte array, null on error.
*/
private static byte[] getMacAddressFromIpv6(final Inet6Address ipv6)
{
byte[] eui48mac = null;
if (ipv6 != null) {
/*
* Make sure that this is an fe80::/64 link-local address.
*/
final byte[] ipv6Bytes = ipv6.getAddress();
if ((ipv6Bytes != null) &&
(ipv6Bytes.length == 16) &&
(ipv6Bytes[0] == (byte) 0xfe) &&
(ipv6Bytes[1] == (byte) 0x80) &&
(ipv6Bytes[11] == (byte) 0xff) &&
(ipv6Bytes[12] == (byte) 0xfe)) {
/*
* Allocate a byte array for storing the EUI-48 MAC address, then fill it
* from the appropriate bytes of the IPv6 address. Invert the 7th bit
* of the first byte and discard the "ff:fe" portion of the modified
* EUI-64 MAC address.
*/
eui48mac = new byte[6];
eui48mac[0] = (byte) (ipv6Bytes[8] ^ 0x2);
eui48mac[1] = ipv6Bytes[9];
eui48mac[2] = ipv6Bytes[10];
eui48mac[3] = ipv6Bytes[13];
eui48mac[4] = ipv6Bytes[14];
eui48mac[5] = ipv6Bytes[15];
}
}
return eui48mac;
}
答案 5 :(得分:4)
我尝试使用2种方法获取mac地址,首先是接口,如果失败,我可以通过文件系统获取,但是你需要启用wifi才能访问该文件。
<div class="row">
@using (Ajax.BeginForm("CreateWiz", "QuanLyDaiLy", null, new AjaxOptions
{
UpdateTargetId = "div-form-daily",
HttpMethod = "POST",
OnBegin = "QuanLyDaiLy.BeforeSend",
OnFailure = "QuanLyDaiLy.Error",
OnComplete = "QuanLyDaiLy.Success",
InsertionMode = InsertionMode.Replace
}, new { @class = "form-update", @role = "form", @id = "search-form" }))
{
<div class="col-xs-12 col-sm-12 col-md-12">
@Html.ValidationSummary(true)
<div id="div-form-daily">
@Html.Partial("_CreateOrEdit", Model)
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button class="btn bg-maroon btn-cons btn-sm" type="submit"><i class="fa fa-floppy-o fa-lg"></i> Lưu</button>
<button class="btn btn-default btn-sm" type="button" data-dismiss="modal"><i class="fa fa-refresh" aria-hidden="true"></i> Quay về</button>
</div>
}
</div>
将此行添加到您的清单。
//Android 6.0 : Access to mac address from WifiManager forbidden
private static final String marshmallowMacAddress = "02:00:00:00:00:00";
private static final String fileAddressMac = "/sys/class/net/wlan0/address";
public static String recupAdresseMAC(WifiManager wifiMan) {
WifiInfo wifiInf = wifiMan.getConnectionInfo();
if(wifiInf.getMacAddress().equals(marshmallowMacAddress)){
String ret = null;
try {
ret= getAdressMacByInterface();
if (ret != null){
return ret;
} else {
ret = getAddressMacByFile(wifiMan);
return ret;
}
} catch (IOException e) {
Log.e("MobileAccess", "Erreur lecture propriete Adresse MAC");
} catch (Exception e) {
Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC ");
}
} else{
return wifiInf.getMacAddress();
}
return marshmallowMacAddress;
}
private static String getAdressMacByInterface(){
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (nif.getName().equalsIgnoreCase("wlan0")) {
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 e) {
Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC ");
}
return null;
}
private static String getAddressMacByFile(WifiManager wifiMan) throws Exception {
String ret;
int wifiState = wifiMan.getWifiState();
wifiMan.setWifiEnabled(true);
File fl = new File(fileAddressMac);
FileInputStream fin = new FileInputStream(fl);
ret = convertStreamToString(fin);
fin.close();
boolean enabled = WifiManager.WIFI_STATE_ENABLED == wifiState;
wifiMan.setWifiEnabled(enabled);
return ret;
}
我建议您在您的偏好设置中保留您的Mac地址,例如
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
答案 6 :(得分:1)
首先,您需要添加Internet用户权限。
<uses-permission android:name="android.permission.INTERNET" />
然后你可以通过NetworkInterfaces API找到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";
}
答案 7 :(得分:1)
答案大多是正确的,但要注意,android 7中有一个变化。你需要使用
DevicePolicyManager 和方法 getWifiMacAddress 。官方文档有拼写错误,这意味着你不应该从那里复制/粘贴它。
DevicePolicyManager.getWifiMacAddress()
参考文献: https://developer.android.com/about/versions/nougat/android-7.0-changes.html
Get Device mac adress in Android Nougat and O programmatically
答案 8 :(得分:1)
非常好
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 "";
}
}
答案 9 :(得分:1)
使用 wifiInfo.getBSSID()来获取AccessPoint的Mac地址,而不是 getMacAddress 方法。
答案 10 :(得分:0)
这是一种更 kotlin 的获取 Mac 地址的方式
fun getMacAddress(): String =
NetworkInterface.getNetworkInterfaces().toList()
.firstOrNull { it.name.equals("wlan0", ignoreCase = true) }?.let {
it.hardwareAddress?.let { macBytes ->
StringBuilder().apply {
for (b in macBytes) {
append(String.format("%02X:", b))
}
if (isNotEmpty()) {
deleteCharAt(lastIndex)
}
}
}.toString()
} ?: "02:00:00:00:00:00"