詳解Java如何跨平臺獲取MAC地址
使用 NetworkInterface 類
首先介紹如何通過Java的NetworkInterface類的API來獲取本機MAC地址的方法,首先展示代碼:
/**
* 獲取 mac 地址工具類 v1 版
*
* @date 2021/5/13
* @author zjw
*/
public class MacUtil {
public static void main(String[] args) {
getMac().forEach(System.out::println);
}
/**
* 獲取本機 mac 地址集合
*
* @return mac 地址集合
*/
public static List<String> getMac() {
List<String> list = new ArrayList<>();
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Optional.ofNullable(networkInterface.getHardwareAddress())
.ifPresent(mac -> list.add(format(mac)));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* 將 mac 字節(jié)數(shù)組格式化為全大寫并且使用 - 作為分隔符的字符串
*
* @param mac 獲取到的 mac 字節(jié)數(shù)組
*
* @return 格式化后的 mac 地址
*/
private static String format(byte[] mac) {
StringBuilder sb = new StringBuilder();
for (byte b : mac) {
sb.append(String.format("%02X", b)).append("-");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
}
通過以上代碼理論上即可獲取本機所有的MAC地址,此外通過format方法可以將獲取到的MAC地址統(tǒng)一處理成XX-XX-XX-XX-XX-XX的格式,這里之所以說是理論上,是因為我曾經(jīng)在別人的蘋果電腦上運行,結(jié)果并沒有得到所有MAC地址(沒有得到執(zhí)行ifconfig -a得到的所有MAC地址,而且還會出現(xiàn)llw0這個網(wǎng)絡的MAC地址一直變動),但是我在本地的虛擬機中運行蘋果時卻也是正常,由于我自己沒有蘋果電腦,所以暫時也不清楚具體的原因,如果有知道的小伙伴,歡迎留言,提前感謝啦~~~
執(zhí)行命令行獲取
正如在上一部分中提到的,在某些情況下使用NetworkInterface類并不能獲取到本機所有的MAC地址,甚至還可能出現(xiàn)動態(tài)變化的情況(暫時不清楚原因)。因此,在這種情況下只能通過Java的Runtime類的exec方法直接執(zhí)行命令了,當然在大多數(shù)情況下還是建議使用NetworkInterface類,不僅方便,而且萬一以后修復了上面的bug(不知道算不算是bug,還是我個人的問題),不對上述代碼做任何變動就可以得到自己執(zhí)行命令的效果了,說了那么多,先看看如果通過自己執(zhí)行命令獲取本機的所有MAC地址吧,先直接展示代碼:
/**
* 獲取 mac 地址工具類 v2 版
*
* @date 2021/5/13
* @author zjw
*/
public class MacUtil {
private static final String WIN_PREFIX = "win";
private static final String OS_NAME_PROPERTY = "os.name";
private static final String WIN_COMMAND = "ipconfig /all";
private static final String UNIX_COMMAND = "/sbin/ifconfig -a";
private static final String MAC_REGEX = "(([a-f0-9]{2}-){5}|([a-f0-9]{2}:){5})[a-f0-9]{2}";
private static final Pattern pattern = Pattern.compile(MAC_REGEX, Pattern.CASE_INSENSITIVE);
public static void main(String[] args) {
getMac().forEach(System.out::println);
}
/**
* 根據(jù)不同操作系統(tǒng)執(zhí)行不同命令
* 獲取本機 mac 地址集合
*
* @return mac 地址集合
*/
private static List<String> getMac() {
try {
String osName = System.getProperty(OS_NAME_PROPERTY).toLowerCase();
if (osName.startsWith(WIN_PREFIX)) {
return getMacByCommand(WIN_COMMAND);
}
return getMacByCommand(UNIX_COMMAND);
} catch (Exception e) {
e.printStackTrace();
}
return Collections.emptyList();
}
/**
* 通過正則表達式提取執(zhí)行命令得到的結(jié)果集中的 mac 地址
* 并調(diào)整得到的 mac 地址的格式
*
* @param command 查看網(wǎng)絡信息的命令
*
* @return mac 地址集合
*/
private static List<String> getMacByCommand(String command) throws IOException {
List<String> macList = new ArrayList<>();
List<String> strList = execCommand(command);
for (String str : strList) {
Matcher matcher = pattern.matcher(str);
if (matcher.find() && matcher.end() == str.length()) {
macList.add(matcher.group().replace(":", "-").toUpperCase());
}
}
return macList;
}
/**
* 執(zhí)行命令并得到結(jié)果的每一行組成的字符串數(shù)組
*
* @param command 查看網(wǎng)絡信息的命令
*
* @return 執(zhí)行命令返回的所有數(shù)據(jù)行
*/
private static List<String> execCommand(String command) throws IOException {
List<String> strList = new ArrayList<>();
Process process = Runtime.getRuntime().exec(command);
try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
return br.lines().collect(Collectors.toList());
} catch (Exception e) {
e.printStackTrace();
}
process.destroy();
return strList;
}
}
到此這篇關于詳解Java如何跨平臺獲取MAC地址的文章就介紹到這了,更多相關Java跨平臺獲取MAC地址內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java 將文件轉(zhuǎn)為字節(jié)數(shù)組知識總結(jié)及實例詳解
這篇文章主要介紹了Java 將文件轉(zhuǎn)為字節(jié)數(shù)組實例詳解的相關資料,需要的朋友可以參考下2016-12-12
使用MyBatis查詢千萬級數(shù)據(jù)量操作實現(xiàn)
這篇文章主要為大家介紹了如何使用MyBatis?查詢千萬數(shù)據(jù)量的操作過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05
Java數(shù)據(jù)結(jié)構(gòu)之鏈表的增刪查改詳解
今天帶大家來學習Java鏈表的增刪改查的相關知識,文中有非常詳細的代碼示例,對正在學習Java的小伙伴們有很好的幫助,需要的朋友可以參考下2021-05-05
Java使用poi-tl1.9.1生成Word文檔的技巧分享
本文將簡單介紹poi-tl的相關知識,通過一個實際的案例實踐,充分介紹如何利用poi-tl進行目標文檔的生成,同時分享幾個不同的office版本如何進行圖表生成的解決方案,需要的朋友可以參考下2023-09-09
Java的線程池ThreadPoolExecutor及多種線程池實現(xiàn)詳解
這篇文章主要介紹了Java的線程池ThreadPoolExecutor及多種線程池實現(xiàn)詳解,ThreadPoolExecutor 使用 int 的高 3 位來表示線程池狀態(tài),低 29 位表示線程數(shù)量,之所以將信息存儲在一個變量中,是為了保證原子性,需要的朋友可以參考下2024-01-01

