gpt4 book ai didi

java - 如何获取机器的mac地址

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:30:19 24 4
gpt4 key购买 nike

我想获取机器的 MAC 地址..但是下面编写的代码仅在 Internet 连接到我的机器时显示 MAC 地址,否则它将返回 null...我使用的是 Windows 7

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

class test
{
public static void main(String[] args)
{
InetAddress ip;
try {
ip = InetAddress.getLocalHost();

System.out.println("The mac Address of this machine is :" + ip.getHostAddress());

NetworkInterface network = NetworkInterface.getByInetAddress(ip);

byte[] mac = network.getHardwareAddress();

System.out.print("The mac address is : ");

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 (UnknownHostException e) {
e.printStackTrace();
}
catch (SocketException e) {
e.printStackTrace();
}
}
}

最佳答案

试试这个它应该在 Linux 和 windows 上都能工作

public static void main(String[] args) {

String command = "/sbin/ifconfig";

String sOsName = System.getProperty("os.name");
if (sOsName.startsWith("Windows")) {
command = "ipconfig";
} else {

if ((sOsName.startsWith("Linux")) || (sOsName.startsWith("Mac"))
|| (sOsName.startsWith("HP-UX"))) {
command = "/sbin/ifconfig";
} else {
System.out.println("The current operating system '" + sOsName
+ "' is not supported.");
}
}

Pattern p = Pattern
.compile("([a-fA-F0-9]{1,2}(-|:)){5}[a-fA-F0-9]{1,2}");
try {
Process pa = Runtime.getRuntime().exec(command);
pa.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(
pa.getInputStream()));

String line;
Matcher m;
while ((line = reader.readLine()) != null) {

m = p.matcher(line);

if (!m.find())
continue;
line = m.group();
break;

}
System.out.println(line);
} catch (Exception e) {
e.printStackTrace();
}

}

关于java - 如何获取机器的mac地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11884696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com