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信息並不適用……html
獲取來訪者ip信息----:http://www.javashuo.com/article/p-kqtcxnxw-m.htmljava
博主原文太長,只取精華-0- 詳細可見:https://blog.csdn.net/cdnight/article/details/86741265數組