获取设备的mac地址和IP地址(android6.0以上专用)
Posted 紫檀未灭,我亦未去
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取设备的mac地址和IP地址(android6.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以上专用)的主要内容,如果未能解决你的问题,请参考以下文章