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

时间:2012-04-05 09:22:07

标签: java android macos sockets network-programming

我正在使用NetworkInterface类来获取MAC地址,但我的代码中的空格为NetworkInterface ni = NetworkInterface.getByInetAddress(inetAddr); 。我在ni对象中得到null,请求建议我在lan上获取设备的mac地址的方法。

提前致谢。

2 个答案:

答案 0 :(得分:3)

试试这段代码,

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;
}
}

答案 1 :(得分:2)

使用以下行获取主机

InetAddress address = socket.getInetAddress();
String hostIP = addresss.getHostAddress();

Ashish使用这个java代码,如果发现任何运气,请告诉我。如果有帮助,请检查此链接, How to obtain MAC address of WiFi network interface?