java 获取linux mac_Linux系统java如何获取硬件唯一信息
时间: 2024-01-28 08:05:26 浏览: 76
java实现获取用户的MAC地址
5星 · 资源好评率100%
可以使用Java的相关API来获取Linux/Mac系统的硬件唯一信息,包括MAC地址和CPU。
获取MAC地址:
可以使用Java的NetworkInterface类来获取MAC地址,示例代码如下:
```
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class MacAddressUtil {
public static void main(String[] args) {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
byte[] mac = ni.getHardwareAddress();
if (mac != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
System.out.println(sb.toString());
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
```
获取CPU信息:
可以使用Java的Runtime类和Process类来执行Linux/Mac系统的命令,获取CPU信息,示例代码如下:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CpuInfoUtil {
public static void main(String[] args) {
String os = System.getProperty("os.name").toLowerCase();
String[] cmd = {"/bin/sh", "-c", ""};
if (os.contains("linux")) {
cmd[2] = "cat /proc/cpuinfo | grep 'model name' | uniq";
} else if (os.contains("mac")) {
cmd[2] = "sysctl -n machdep.cpu.brand_string";
}
try {
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
```
以上代码仅供参考,具体实现需要根据实际情况进行调整。
阅读全文