我是互联网的搬运工
第一种方法:通过InetAddress对象获取
package com.chunni.mac;
import org.junit.jupiter.api.Test;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class MACTest {
@Test
public void test01 () throws UnknownHostException, SocketException {
// 获取特定的mac地址
InetAddress address = InetAddress.getByName("xxx");
byte[] mac = NetworkInterface.getByInetAddress(address).getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
// 转为16进制
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
System.out.println(sb.toString());
}
@Test
public void test02 () throws UnknownHostException, SocketException {
InetAddress[] addresses = InetAddress.getAllByName("xxx");
StringBuilder sb = new StringBuilder();
for (InetAddress address : addresses) {
byte[] mac = NetworkInterface.getByInetAddress(address).getHardwareAddress();
for (int i = 0; i < mac.length; i++) {
// 转为16进制
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "\n"));
}
}
System.out.println(sb.toString());
}
}
第二种方法:
通过NetworkInterface对象获取
package com.chunni.mac;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class MACTest01 {
public static void main(String[] args) throws SocketException {
StringBuilder sb = new StringBuilder();
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
byte[] mac = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || netInterface.isPointToPoint() || !netInterface.isUp()) {
continue;
} else {
mac = netInterface.getHardwareAddress();
if (mac != null) {
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "\n"));
}
}
}
}
System.out.println(sb.toString());
}
}
注意:第一种方式查询所有mac地址时会有重复的,因为ipv4和ipv6都会查询一份mac地址