在Java中获取Linux系统的MAC地址
在Java中获取Linux系统的MAC地址有几种方法,以下是几种常见的实现方式:

方法1:使用NetworkInterface类(推荐)
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;
public class MacAddress {
public static void main(String[] args) throws Exception {
List<NetworkInterface> networks = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface network : networks) {
byte[] mac = network.getHardwareAddress();
if (mac != null && mac.length > 0) {
StringBuilder sb = new StringBuilder();
for (byte b : mac) {
sb.append(String.format("%02X:", b));
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1); // 移除最后一个冒号
}
System.out.println("Interface: " + network.getName() +
", Display Name: " + network.getDisplayName() +
", MAC: " + sb.toString());
}
}
}
}
方法2:执行系统命令获取
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MacAddressCommand {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("ifconfig");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("HWaddr") || line.contains("ether")) {
// 对于不同的Linux发行版,MAC地址的位置可能不同
String[] parts = line.split("\\s+");
for (String part : parts) {
if (part.matches("..:..:..:..:..:..")) {
System.out.println("MAC: " + part);
break;
}
}
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
方法3:使用第三方库(如Apache Commons Net)
import org.apache.commons.net.util.SubnetUtils;
public class MacAddressCommons {
public static void main(String[] args) {
// 注意:这个库主要用于网络子网计算,不是直接获取MAC地址
// 这里只是展示如何使用第三方库,实际MAC地址获取仍需上述方法
SubnetUtils utils = new SubnetUtils("192.168.1.0/24");
System.out.println("CIDR: " + utils.getInfo().getCidrSignature());
}
}
注意事项
-
权限问题:在Linux上,获取MAC地址可能需要root权限,特别是当使用
ifconfig命令时。 -
多网卡情况:系统可能有多个网络接口,上述方法会返回所有接口的MAC地址。
-
虚拟接口:某些虚拟接口(如docker0)也会被列出,需要过滤掉。
-
格式差异:不同Linux发行版的
ifconfig输出格式可能不同,方法2中的正则表达式可能需要调整。
(图片来源网络,侵删) -
Java 9+模块系统:如果使用Java 9或更高版本,可能需要添加适当的模块访问权限。
方法中,方法1(使用NetworkInterface)是最推荐的方式,因为它不依赖于系统命令,且跨平台性更好。
