MacUtils.java 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package com.ydtech.utils;
  2. import java.net.*;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.stream.Collectors;
  6. public class MacUtils {
  7. /***因为一台机器不一定只有一个网卡呀,所以返回的是数组是很合理的***/
  8. public static List<String> getMacList() throws Exception {
  9. java.util.Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
  10. StringBuilder sb = new StringBuilder();
  11. ArrayList<String> tmpMacList = new ArrayList<>();
  12. while (en.hasMoreElements()) {
  13. NetworkInterface iface = en.nextElement();
  14. List<InterfaceAddress> addrs = iface.getInterfaceAddresses();
  15. for (InterfaceAddress addr : addrs) {
  16. InetAddress ip = addr.getAddress();
  17. NetworkInterface network = NetworkInterface.getByInetAddress(ip);
  18. if (network == null) {
  19. continue;
  20. }
  21. byte[] mac = network.getHardwareAddress();
  22. if (mac == null) {
  23. continue;
  24. }
  25. sb.delete(0, sb.length());
  26. for (int i = 0; i < mac.length; i++) {
  27. sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
  28. }
  29. tmpMacList.add(sb.toString());
  30. }
  31. }
  32. if (tmpMacList.isEmpty()) {
  33. return tmpMacList;
  34. }
  35. /***去重,别忘了同一个网卡的ipv4,ipv6得到的mac都是一样的,肯定有重复,下面这段代码是。。流式处理***/
  36. List<String> unique = tmpMacList.stream().distinct().collect(Collectors.toList());
  37. return unique;
  38. }
  39. public static String getLocalMac() {
  40. StringBuffer sb = new StringBuffer("");
  41. try {
  42. //获取网卡,获取地址
  43. InetAddress ia = InetAddress.getLocalHost();
  44. //System.out.println(ia);
  45. byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
  46. //System.out.println("mac数组长度:"+mac.length);
  47. for (int i = 0; i < mac.length; i++) {
  48. if (i != 0) {
  49. sb.append("-");
  50. }
  51. //字节转换为整数
  52. int temp = mac[i] & 0xff;
  53. String str = Integer.toHexString(temp);
  54. // System.out.println("每8位:" + str);
  55. if (str.length() == 1) {
  56. sb.append("0" + str);
  57. } else {
  58. sb.append(str);
  59. }
  60. }
  61. } catch (Exception e) {
  62. //do nothing
  63. }
  64. System.out.println("本机MAC地址:" + sb.toString().toUpperCase());
  65. return sb.toString().toUpperCase();
  66. }
  67. public static void main(String[] args) throws Exception {
  68. long a = System.currentTimeMillis();
  69. System.out.println("进行 multi net address 测试===》");
  70. List<String> macs = getMacList();
  71. long b = System.currentTimeMillis();
  72. System.out.println("本机的mac网卡的地址有:" + macs);
  73. System.out.println("总耗时----" + (b - a) + "-----ms");
  74. getLocalMac();
  75. }
  76. }