在Windows下很简单直接运行脚本命令就可以了
public static String getMac() {
try {
Process process = Runtime.getRuntime().exec("cmd.exe /c ipconfig /all");
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(),Charset.forName("GBK")));
StringBuffer sb = new StringBuffer();
String line;
List<String> list = new ArrayList<>();
while ((line = br.readLine()) != null) {
if (line.indexOf("Physical Address") > 0) {
int index = line.indexOf(":");
index += 2;
String address = line.substring(index);
break;
} else if (line.indexOf("物理地址") > 0){
int index = line.indexOf(":");
index += 2;
String address = line.substring(index);
list.add(address);
}
sb.append(line);
}
br.close();
String string = sb.toString();
String hostAddress = InetAddress.getLocalHost().getHostAddress();
int index = 0;
int indexOf = string.indexOf(list.get(0));
int indexOf2 = string.indexOf(hostAddress);
for(int i = 1; i < list.size(); i ++) {
if(Math.abs(string.indexOf(list.get(i)) - indexOf2) < Math.abs(indexOf - indexOf2)) {
index = i;
}
}
String mac = list.get(index);
System.out.println("检测到你的MAC地址为 ---> : " + mac);
在linux下方法也和上面的差不多,但如果你要是在Linux下就比较麻烦,原因是linux的网卡配置信息中会由于各种问题导致没有我们想要的MAC信息
public void getMAC() {
String address = "";
String command = "/bin/sh -c ifconfig -a";
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("HWaddr") > 0) {
int index = line.indexOf("HWaddr") + "HWaddr".length();
address = line.substring(index);
break;
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("您的MAC地址为-->" + address);
}
那么怎么办呢?这里给大家提供另外一个方法,我们可以查看系统网络信息的配置文件
public static void main(String[] args) {
String address = "";
String command = "cat /sys/class/net/ens33/address";
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
address = br.readLine();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(address);
}
总之linux比较麻烦,这也是为什么家用电脑都是Windows,linux这个系统操作起来对普通的用户太不友好了
因篇幅问题不能全部显示,请点此查看更多更全内容