我这边直接贴代码吧,里面有一些注释:
具体的我就不解释了,但是这种方式我本地测试过,是准确的,包括有线和无线的连接方式,具体里面的一些之类和文件的含义,可以自己百度下。
/**
* 获取路由器MAC地址
* @return
*/
public String getGatewayMac() {
String str ="";
try {
str = getMacFromFile( getGateway());
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
*
* @param str 根据ip获取到对应mac地址信息
* @return
*/
public String getMacFromFile(String str) {
if (TextUtils.isEmpty(str)) {
return "";
}
List a = readFile("/proc/net/arp");
if (a != null && a.size() > 1) {
for (int i = 1; i < a.size(); i++) {
List arrayList = new ArrayList();
String[] split = ((String) a.get(i)).split(" ");
int i2 = 0;
while (i2 < split.length) {
if (split[i2] != null && split[i2].length() > 0) {
arrayList.add(split[i2]);
}
i2++;
}
if (arrayList.size() > 4 && ((String) arrayList.get(0)).equalsIgnoreCase(str)) {
return ((String) arrayList.get(3)).toUpperCase();
}
}
}
return "";
}
private static List<String> readFile(String str) {
IOException e;
Throwable th;
File file = new File(str);
List<String> arrayList = new ArrayList();
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader(file));
while (true) {
try {
String readLine = bufferedReader.readLine();
if (readLine == null) {
break;
}
arrayList.add(readLine);
} catch (IOException e2) {
e = e2;
}
}
bufferedReader.close();
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e3)