1、概述
Java 可以获取服务器的网卡 Mac 地址、CPU 序列号、主板序列号等信息,用来做一些软件授权验证、设备管理等场景。
2、代码实现
package com.study.util;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
/**
* @author CSDN 流放深圳
* @description 获取本机相关地址工具类
* @create 2024-04-13 15:55
* @since 1.0.0
*/
public class MachineAddrUtil {
/**
* 获取网卡物理地址工具类
*
* @return
*/
public static String getMac() {
String result = null;
try {
// 获取所有网络接口
List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface networkInterface : networkInterfaces) {
// 忽略回环接口
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
continue;
}
byte[] macByte = networkInterface.getHardwareAddress();
if (macByte != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < macByte.length; i++) {
sb.append(String.format("%02X%s", macByte[i], (i < macByte.length - 1) ? "-" : ""));
}
result = sb.toString();
break; // 找到有效的MAC地址后退出循环
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 获取 CPU 序列号
*
* @return
*/
public static String getCPUSerial() {
String cpuSerial = System.getenv("PROCESSOR_IDENTIFIER");
return cpuSerial;
}
/**
* 获取主板序列号
*
* @return
*/
public static String getMainBoardSerial() {
String result = null;
try {
Process process = Runtime.getRuntime().exec(new String[]{"wmic", "baseboard", "get", "serialnumber"});
process.getOutputStream().close();
Scanner scanner = new Scanner(process.getInputStream());
while (scanner.hasNext()) {
result = scanner.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
System.out.println("本机的【网卡物理地址】=" + getMac());
System.out.println("本机的【CPU 序列号】=" + getCPUSerial());
System.out.println("本机的【主板序列号】=" + getMainBoardSerial());
}
}
测试结果:
本机的【网卡物理地址】=D8-BB-C1******
本机的【CPU 序列号】=Intel64 Family *******, ******
本机的【主板序列号】=07D4211_LC*******