| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package com.ydtech.utils;
- import java.net.*;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.stream.Collectors;
- public class MacUtils {
- /***因为一台机器不一定只有一个网卡呀,所以返回的是数组是很合理的***/
- 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.isEmpty()) {
- return tmpMacList;
- }
- /***去重,别忘了同一个网卡的ipv4,ipv6得到的mac都是一样的,肯定有重复,下面这段代码是。。流式处理***/
- List<String> unique = tmpMacList.stream().distinct().collect(Collectors.toList());
- return unique;
- }
- public static String getLocalMac() {
- StringBuffer sb = new StringBuffer("");
- try {
- //获取网卡,获取地址
- InetAddress ia = InetAddress.getLocalHost();
- //System.out.println(ia);
- byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
- //System.out.println("mac数组长度:"+mac.length);
- for (int i = 0; i < mac.length; i++) {
- if (i != 0) {
- sb.append("-");
- }
- //字节转换为整数
- int temp = mac[i] & 0xff;
- String str = Integer.toHexString(temp);
- // System.out.println("每8位:" + str);
- if (str.length() == 1) {
- sb.append("0" + str);
- } else {
- sb.append(str);
- }
- }
- } catch (Exception e) {
- //do nothing
- }
- System.out.println("本机MAC地址:" + sb.toString().toUpperCase());
- return sb.toString().toUpperCase();
- }
- 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");
- getLocalMac();
- }
- }
|