码迷,mamicode.com
首页 > 移动开发 > 详细

获取设备的mac地址和IP地址(android6.0以上专用)

时间:2016-05-23 19:05:30      阅读:790      评论:0      收藏:0      [点我收藏+]

标签:

/**
* 获取设备HardwareAddress地址
* @return
*/
public static String getMachineHardwareAddress(){
Enumeration<NetworkInterface> interfaces = null;
try {
interfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
String hardWareAddress = null;
NetworkInterface iF = null;
while (interfaces.hasMoreElements()) {
iF = interfaces.nextElement();
try {
hardWareAddress = bytesToString(iF.getHardwareAddress());
if(hardWareAddress == null) continue;
} catch (SocketException e) {
e.printStackTrace();
}
}
if(iF != null && iF.getName().equals("wlan0")){
hardWareAddress = hardWareAddress.replace(":","");
}
return hardWareAddress ;
}

/***
* byte转为String
* @param bytes
* @return
*/
private static String bytesToString(byte[] bytes){
if (bytes == null || bytes.length == 0) {
return null ;
}
StringBuilder buf = new StringBuilder();
for (byte b : bytes) {
buf.append(String.format("%02X:", b));
}
if (buf.length() > 0) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}

/**
* 获取设备IP地址
* @return
*/
public static String getMachineIpAddress(){
Enumeration<NetworkInterface> interfaces = null;
try {
interfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
String ipAddress = null;
NetworkInterface iF = null;
while (interfaces.hasMoreElements()){
iF = interfaces.nextElement();
Enumeration<InetAddress> addressEnumeration = iF.getInetAddresses();
InetAddress address = addressEnumeration.nextElement();
ipAddress = bytesToString(address.getAddress());
if(ipAddress == null) continue;
}
return ipAddress ;
}

获取设备的mac地址和IP地址(android6.0以上专用)

标签:

原文地址:http://www.cnblogs.com/liu-fei/p/5520754.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!