java 程序中如何获取 MAC 地址?
在Java程序中,可以通过Java标准库的 java.net
包中的 NetworkInterface
类来获取本机的MAC地址。
以下是示例代码:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class MacAddress {
public static void main(String[] args) {
try {
// 获取本地主机信息
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println("本机的IP地址是:" + inetAddress.getHostAddress());
// 获取所有网络接口
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
// 遍历所有网络接口
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
// 获取MAC地址
byte[] macBytes = networkInterface.getHardwareAddress();
if (macBytes != null) {
StringBuilder macBuilder = new StringBuilder();
for (int i = 0; i < macBytes.length; i++) {
macBuilder.append(String.format("%02X%s", macBytes[i], (i < macBytes.length - 1) ? "-" : ""));
}
System.out.println("MAC地址:" + macBuilder.toString());
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
}
}
该程序首先获取本机的IP地址,然后通过 NetworkInterface.getNetworkInterfaces()
方法获取所有的网络接口。接着遍历所有的网络接口,通过 NetworkInterface.getHardwareAddress()
方法获取每个网络接口的MAC地址,并将其格式化输出。
需要注意的是,该方法只能获取本机的MAC地址,无法获取其他设备的MAC地址。另外,在一些操作系统中,可能需要管理员权限才能获取MAC地址。