【发布时间】:2011-11-12 01:45:56
【问题描述】:
我正在使用 Api 级别 8 的 Android,我想获取我的以太网接口 (eth0) 的地址。
在 API 级别 8 上,NetworkInterface 类没有函数 getHardwareAddress()。 WifiManager 也不起作用,因为这不是无线接口。
提前致谢!
【问题讨论】:
标签: java android ethernet mac-address
我正在使用 Api 级别 8 的 Android,我想获取我的以太网接口 (eth0) 的地址。
在 API 级别 8 上,NetworkInterface 类没有函数 getHardwareAddress()。 WifiManager 也不起作用,因为这不是无线接口。
提前致谢!
【问题讨论】:
标签: java android ethernet mac-address
这是我基于 Joel F 答案的解决方案。希望它可以帮助某人!
/*
* Load file content to String
*/
public static String loadFileAsString(String filePath) throws java.io.IOException{
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
/*
* Get the STB MacAddress
*/
public String getMacAddress(){
try {
return loadFileAsString("/sys/class/net/eth0/address")
.toUpperCase().substring(0, 17);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
【讨论】:
假设您的以太网接口是 eth0,请尝试打开并读取文件 /sys/class/net/eth0/address。
【讨论】:
这种方式用java修复吧;也许可以帮助你
NetworkInterface netf = NetworkInterface.getByName("eth0");
byte[] array = netf.getHardwareAddress();
StringBuilder stringBuilder = new StringBuilder("");
String str = "";
for (int i = 0; i < array.length; i++) {
int v = array[i] & 0xFF;
String hv = Integer.toHexString(v).toUpperCase();
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv).append("-");
}
str = stringBuilder.substring(0, stringBuilder.length()- 1);
【讨论】:
至少在 Amlogic 平台上还要检查 /sys/class/efuse/mac。
【讨论】:
现在(2014 年 3 月)Google 没有提供关于 Ethernet 的 API
这是原因,因为我们没有办法像在 wifi 情况下那样获得以太网 mac。
private String getWifiMACAddress(Context ctx) {
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
return info.getMacAddress();
}
另一种方法是读取 eth0 文件。如果有人知道,请告诉我!
【讨论】:
public static String getEthernetMacAddress() {
String macAddress = "Not able to read";
try {
List<NetworkInterface> allNetworkInterfaces = Collections.list(NetworkInterface
.getNetworkInterfaces());
for (NetworkInterface nif : allNetworkInterfaces) {
if (!nif.getName().equalsIgnoreCase("eth0"))
continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return macAddress;
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:", b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
macAddress = res1.toString();
}
} catch (Exception ex) {
log(LogLevel.ERROR, "getEthernetMacAddress e :" + ex.getMessage());
ex.printStackTrace();
}
return macAddress;
}
【讨论】:
AndroidTV 的许多实现可能会将其填充到属性中,您可以使用 getprop 命令检查以找到正确的属性名称广告,然后使用 SystemProperties.get() 读取它
要在 java 中读取程序中的 MAC,您可以使用以下内容
SystemProperties.get("ro.boot.ethernet-mac");
【讨论】: