1. 简介
本文将介绍如何使用 Java 获取本地机器的 MAC 地址。
✅ MAC 地址是网卡(Network Interface Card)的唯一物理标识符,常用于网络通信、设备识别等场景。
我们聚焦于 MAC 地址的获取,不展开网络接口的全面介绍。若需了解更广泛的网络接口操作,可参考《Java 网络接口使用指南》。
⚠️ 注意:获取 MAC 地址依赖底层操作系统支持,某些虚拟化环境或安全策略可能返回
null
或异常。
2. 实际示例
我们将使用 java.net.NetworkInterface
和 java.net.InetAddress
两个核心类来完成操作。以下是几种常见场景的实现方式。
2.1. 获取本机 localhost 的 MAC 地址
最常见的方式是通过本地回环地址(localhost)反查对应网卡的 MAC 地址:
InetAddress localHost = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(localHost);
byte[] hardwareAddress = ni.getHardwareAddress();
📌 NetworkInterface.getHardwareAddress()
返回的是 byte[]
类型,需要格式化为常见的十六进制字符串形式(如 00-1A-2B-3C-4D-5E
)。
下面是一个简单粗暴的格式化方法:
String[] hexadecimal = new String[hardwareAddress.length];
for (int i = 0; i < hardwareAddress.length; i++) {
hexadecimal[i] = String.format("%02X", hardwareAddress[i]);
}
String macAddress = String.join("-", hexadecimal);
✅ 解释:
%02X
:将每个字节转为两位大写十六进制数,不足补零String.join("-", ...)
:用连字符连接各段,符合标准 MAC 显示格式
⚠️ 踩坑提示:getLocalHost()
可能受 hosts 配置影响,不一定返回你期望的网卡地址。建议结合具体 IP 使用更精准的方式。
2.2. 根据指定本地 IP 获取 MAC 地址
如果你知道目标网卡的 IP 地址(比如 192.168.1.108
),可以直接通过该 IP 查询:
InetAddress localIP = InetAddress.getByName("192.168.1.108");
NetworkInterface ni = NetworkInterface.getByInetAddress(localIP);
byte[] macAddress = ni.getHardwareAddress();
📌 这种方式比 getLocalHost()
更可靠,避免了 DNS 或 hosts 配置带来的不确定性。
✅ 获取到的 macAddress
依然是 byte[]
,后续格式化逻辑同上。
📌 示例中 IP 地址为示例值,实际应替换为当前局域网内本机真实 IP,例如 192.168.0.105
或 10.0.0.5
。
2.3. 遍历所有网络接口获取全部 MAC 地址
有时我们需要列出所有活动网卡的 MAC 地址,比如做设备指纹采集或网络诊断工具。
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = networkInterfaces.nextElement();
byte[] hardwareAddress = ni.getHardwareAddress();
if (hardwareAddress != null) {
String[] hexadecimalFormat = new String[hardwareAddress.length];
for (int i = 0; i < hardwareAddress.length; i++) {
hexadecimalFormat[i] = String.format("%02X", hardwareAddress[i]);
}
System.out.println(String.join("-", hexadecimalFormat));
}
}
✅ 关键点说明:
NetworkInterface.getNetworkInterfaces()
返回所有物理 + 虚拟接口(包括 Docker、VMware、Loopback 等)- ✅ 通过
hardwareAddress != null
过滤掉虚拟接口:物理网卡才有硬件地址,虚拟接口通常返回null
- 输出结果为所有有效网卡的 MAC 地址,每行一条
📌 常见输出示例:
00-1A-2B-3C-4D-5E
A0-B1-C2-D3-E4-F5
⚠️ 注意事项:
- 某些系统(如 Windows)可能需要管理员权限才能访问全部接口
- 在容器化环境中(如 Docker),看到的可能是虚拟网桥的 MAC 地址
3. 总结
本文演示了三种在 Java 中获取 MAC 地址的典型方式:
方法 | 适用场景 | 是否推荐 |
---|---|---|
getLocalHost() |
快速尝试获取本机地址 | ⚠️ 有风险,受配置影响 |
getByName(ip) |
已知具体 IP 时精准定位 | ✅ 推荐 |
遍历所有接口 | 全面扫描设备网卡 | ✅ 推荐 + 配合 null 判断 |
📌 核心要点:
- 所有方法最终都依赖
NetworkInterface.getHardwareAddress()
- 返回值为
byte[]
,需手动格式化为可读字符串 - 虚拟接口无 MAC 地址,务必做
null
判断
所有示例代码已上传至 GitHub:https://github.com/baeldung/core-java-modules/tree/master/core-java-networking-2