java - java中如何获取本地网络机器的MAC地址

标签 java android macos sockets network-programming

我正在使用 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/

相关文章:

java - 设置背景颜色 Java JButton

Java反编译->重新编译的过程,安全吗?

android 将列表适配器项拖放到 bin 中

c++ - 从终端运行 C++ 程序。在同一终端窗口中获​​取输出

macos - 环境变量 Visual Studio Code for Mac 与 Python Jupyter

android - 整合推特 : why can’t I post status without having to authenticate?

java - 方法链警告

java - 我们可以不使用 final 关键字来避免继承吗?

java - Java 运算符总是从左到右阅读吗?

java - Android - 在数组中创建 JSON 数组