您的位置:首页 > 移动开发 > Android开发

android如何获取以太网mac地址

2015-08-05 19:40 405 查看
android系统已经应用到了机顶盒及其他设备中,不像手机只能通过wifi连接网络,还可以通过有线的方式。在机顶盒应用开发中,有时候需要用到mac地址,这就牵涉到mac地址和ip地址的获取。
本文讲述无线网和以太网mac地址获取的方法:1.以太网获取mac地址
因为机顶盒系统是linux内核的,假设ethernet是eth0,那么可以从以下文件中读取相关信息:/sys/class/net/eth0/address
方法1:
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;}}方法2:
NetworkInterface NIC = NetworkInterface.getByName("eth0");byte[] buf = NIC.getHardwareAddress();for (int i = 0; i < buf.length; i++) {mac = mac + byteHEX(buf);}if (mac != null && !"".equals(mac)) {ethernetMac = mac.toUpperCase();}
2.wifi获取mac和ip首先要在manifest.xml文件中添加权限:
<uses-permission
android:name=
"android.permission.ACCESS_WIFI_STATE"
></uses-permission>
获取mac的代码如下
WifiManager
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo
info = wifi.getConnectionInfo();
return
info.getMacAddress();
获取Ip的代码
public
String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); if (intf.getName().toLowerCase().equals("eth0")) { for (Enumeration<InetAddress>
enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { String ipaddress = inetAddress.getHostAddress().toString(); if(!ipaddress.contains("::")){//ipV6的地址
return ipaddress; } } } } else { continue; } } } catch (Exception ex) { Log.e("WifiPreference IpAddress", ex.toString()); } return null; }


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: