由于在網(wǎng)上沒有找到正確獲取到Mac地址的方式,我原來的代碼在Windows上可以獲取到,但是蘋果電腦上卻不行,所以找了一下原因,發(fā)現(xiàn)是需要獲取本機所有的ip然后找到一個有mac地址信息的數(shù)據(jù),代碼不復(fù)雜,但用得少,記錄一下以便日后使用。
/**
* 獲取計算機MAC地址
* @return mac
*/
public static String getLocalMac(){
// 這里可以放一個隨機數(shù)或者唯一id做一個兜底
String mac = "";
try {
// 獲取本機主機名
String hostName = InetAddress.getLocalHost().getHostName();
// 獲取本機所有的IP地址
InetAddress[] inetAddresses = InetAddress.getAllByName(hostName);
// 遍歷IP地址
for (InetAddress inetAddress : inetAddresses) {
NetworkInterface net = NetworkInterface.getByInetAddress(inetAddress);
byte[] macBytes = net.getHardwareAddress();
if (macBytes != null){
return transBytesToStr(macBytes);
}
}
} catch (UnknownHostException | SocketException e) {
e.printStackTrace();
}
return mac;
}
blog: java獲取計算機MAC地址