一.有些安卓设备不仅有无线wifi的mac地址,还有有线网卡的mac地址,下面是几中获取方法。
1.直接上代码,以下几种方法只能获取有线网卡MAC
//得到有线网卡的MAC地址public staticString getWireMac(){String strMacAddress =null;try{byte[] b = NetworkInterface.getByName("eth0").getHardwareAddress();StringBuffer buffer =newStringBuffer();for(inti = 0; i < b.length; i++) {if(i != 0) {buffer.append(':');}System.out.println("b:"+(b[i]&0xFF));String str = Integer.toHexString(b[i] & 0xFF);buffer.append(str.length() == 1 ? 0 + str : str);}strMacAddress = buffer.toString().toUpperCase();Log.d("TAG",strMacAddress);}catch(Exception e) {e.printStackTrace();}returnstrMacAddress;}
2.
public staticString getMacAddress() {String result ="";String Mac ="";result = callCmd("busybox ifconfig","HWaddr");if(result ==null) {return"网络出错,请检查网络";}if(result.length() > 0 && result.contains("HWaddr")) {Mac = result.substring(result.indexOf("HWaddr") + 6, result.length() - 1);if(Mac.length() > 1) {result = Mac.toLowerCase();}}returnresult.trim();}
3.
//根据busybox获取本地Macpublic staticString getLocalMacAddressFromBusybox(){String result ="";String Mac ="";result = callCmd("busybox ifconfig","HWaddr");//如果返回的result == null,则说明网络不可取if(result==null){return"网络出错,请检查网络";}//对该行数据进行解析 //例如:eth0Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67if(result.length()>0 && result.contains("HWaddr")==true){Mac = result.substring(result.indexOf("HWaddr")+6, result.length()-1);Log.i("test","Mac:"+Mac+" Mac.length: "+Mac.length());/*if(Mac.length()>1){ Mac = Mac.replaceAll(" ", ""); result = ""; String[] tmp = Mac.split(":"); for(int i = 0;i<tmp.length;++i){result +=tmp[i]; } }*/result = Mac;Log.i("test",result+" result.length: "+result.length());}returnresult;}private staticString callCmd(String cmd,String filter) {String result ="";String line ="";try{Process proc = Runtime.getRuntime().exec(cmd);InputStreamReader is =newInputStreamReader(proc.getInputStream());BufferedReader br =newBufferedReader (is);//执行命令cmd,只取结果中含有filter的这一行while((line = br.readLine ()) !=null&& line.contains(filter)==false) {//result += line;Log.i("test","line: "+line);}result = line;Log.i("test","result: "+result);}catch(Exception e) {e.printStackTrace();}returnresult;}