java獲取本機mac物理地址


package com.simonjia.util.other;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class MacTools {
/***因為一台機器不一定只有一個網卡呀,所以返回的是數組是很合理的***/
public static List<String> getMacList() throws Exception {
java.util.Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
StringBuilder sb = new StringBuilder();
ArrayList<String> tmpMacList = new ArrayList<>();
while (en.hasMoreElements()) {
NetworkInterface iface = en.nextElement();
List<InterfaceAddress> addrs = iface.getInterfaceAddresses();
for (InterfaceAddress addr : addrs) {
InetAddress ip = addr.getAddress();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
continue;
}
byte[] mac = network.getHardwareAddress();
if (mac == null) {
continue;
}
sb.delete(0, sb.length());
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
tmpMacList.add(sb.toString());
}
}
if (tmpMacList.size() <= 0) {
return tmpMacList;
}
/***去重,別忘了同一個網卡的ipv4,ipv6得到的mac都是一樣的,肯定有重復,下面這段代碼是。。流式處理***/
List<String> unique = tmpMacList.stream().distinct().collect(Collectors.toList());
return unique;
}

public static void main(String[] args) throws Exception {
long a = System.currentTimeMillis();
System.out.println("進行 multi net address 測試===》");
List<String> macs = getMacList();
long b = System.currentTimeMillis();
System.out.println("本機的mac網卡的地址有:" + macs);
System.out.println("總耗時----" + (b - a) + "-----ms");
}
}

 

這個只能拿到服務本機的mac地址,對於遠程請求獲取請求者的mac信息並不適用……

獲取來訪者ip信息----:https://www.cnblogs.com/SimonHu1993/p/11015069.html

博主原文太長,只取精華-0-  詳細可見:https://blog.csdn.net/cdnight/article/details/86741265


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM