Android获取Ethernet、WIFI的ip和mac地址
2014-11-05 18:46
525 查看
通过IP获取MAC地址还有一种更简单的方式获取Ethernet的mac/** * 通过本地ip获取mac地址 * @return */ @SuppressWarnings("finally") private String getLocalMacAddressFromIp() { String mac_s = ""; try { byte[] mac; String ip = getLocalIpAddress(); if (!InetAddressUtils.isIPv4Address(ip)) { return mac_s; } InetAddress ipAddress = InetAddress.getByName(ip); if (ipAddress == null) { return mac_s; } NetworkInterface ne = NetworkInterface.getByInetAddress(ipAddress); mac = ne.getHardwareAddress(); if (mac.length > 0) { mac_s = byte2mac(mac); } } catch (Exception e) { e.printStackTrace(); }finally{ return mac_s; } } private String byte2mac(byte[] b) { StringBuffer hs = new StringBuffer(b.length); String stmp = ""; int len = b.length; for (int n = 0; n < len; n++) { stmp = Integer.toHexString(b & 0xFF); if (stmp.length() == 1) { hs = hs.append("0").append(stmp); } else { hs = hs.append(stmp); } } StringBuffer str = new StringBuffer(hs); for (int i = 0; i < str.length(); i++) { if (i % 3 == 0) { str.insert(i, ':'); } } return str.toString().substring(1); }因为是通过ip获取的mac地址,所以当是wifi连接时的ip获取到的则是WIFI的mac,如果是Ethernet连接时则获取的是Ethernet的mac地址
下面的方法则是直接获取Ethernet的mac
/**
* 获取Ethernet的MAC地址
* @return
*/
private String getMacAddress() {
try {
return loadFileAsString("/sys/class/net/eth0/address").toUpperCase(Locale.ENGLISH).substring(0, 17);
} catch (IOException e) {
return null;
}
}
private 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();
}
/** * 获取Ethernet的MAC地址 * @return */ private String getMacAddress() { EthernetManager ethManager = (EthernetManager) MainActivity.this.getSystemService("ethernet"); return ethManager.getMacAddr()==null?"":ethManager.getMacAddr(); }
获取wifi的mac地址
/** * 获取wifi mac * @return */ private String getWifiMac(){ WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo(); return info.getMacAddress()==null?"":info.getMacAddress(); }
相关文章推荐
- Android中Wifi未开启情况下获取Mac地址和IP
- Android中Wifi未开启情况下获取Mac地址和IP
- Android中Wifi未开启情况下获取Mac地址和IP
- Android 在wifi下获取IP和MAC地址
- Android中Wifi未开启情况下获取Mac地址和IP
- Android获取Ethernet、WIFI的ip和mac地址
- Android获取Ethernet、WIFI的ip和mac地址
- Android 获取Mac地址和IP
- android获取wifi外网ip的方法
- Android 获取WIFI MAC地址的方法
- Android 获取WIFI MAC地址的方法
- android获取wifi的IP,子网掩码,网关,dns等信息
- Android开发--获取本地ip(wifi 3g)
- android获取wifi的IP,子网掩码,网关,dns等信息
- Android 获取本机WIFI及3G网络IP
- Android_获取手机IP和MAC地址
- Android系统下获取本地IP和mac地址的方法
- android ethernet dhcp概率性获取不到ip的解决方法
- Android 获取本机WIFI及3G网络IP
- android获取Mac地址和IP 地址