我正在使用 NetworkInterface 类来获取 MAC 地址,但我在代码中得到 null NetworkInterface ni = NetworkInterface.getByInetAddress(inetAddr); .我在ni对象中得到null,请建议我获取局域网上设备的MAC地址的方法。
提前致谢。
最佳答案
试试这个代码,
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.regex.*;
public class GetMac
{
public static void main(String[] args)
throws IOException
{
String address = new GetMac().getMacAddress();
System.out.println(address);
}
public String getMacAddress() throws IOException
{
String macAddress = null;
String command = "ipconfig /all";
Process pid = Runtime.getRuntime().exec(command);
BufferedReader in =
new BufferedReader(
new InputStreamReader(pid.getInputStream()));
while (true) {
String line = in.readLine();
if (line == null)
break;
Pattern p = Pattern.compile(".*Physical Address.*: (.*)");
Matcher m = p.matcher(line);
if (m.matches()) {
macAddress = m.group(1);
break;
}
}
in.close();
return macAddress;
}
}
关于java - java中如何获取本地网络机器的MAC地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10025965/