我可以使用下面的代码获取本地 MAC 地址
package com.eiw.server;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
class FindMACAddress {
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();
}
}
}
但我需要找到远程系统的 Mac 地址... 是否可能?我已经浏览了一些帖子...但不清楚...
最佳答案
可以调用函数getMacAddrHost("192.168.1.xx")获取远程主机的mac addr。这可能不是最好的解决方案,但效果很好。请注意,这仅适用于 LAN 内部。
public static String getMacAddrHost(String host) throws IOException, InterruptedException {
//
boolean ok = ping3(host);
//
if (ok) {
InetAddress address = InetAddress.getByName(host);
String ip = address.getHostAddress();
return run_program_with_catching_output("arp -a " + ip);
}
//
return null;
//
}
public static boolean ping3(String host) throws IOException, InterruptedException {
boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");
ProcessBuilder processBuilder = new ProcessBuilder("ping", isWindows ? "-n" : "-c", "1", host);
Process proc = processBuilder.start();
int returnVal = proc.waitFor();
return returnVal == 0;
}
public static String run_program_with_catching_output(String param) throws IOException {
Process p = Runtime.getRuntime().exec(param);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
if (!line.trim().equals("")) {
// keep only the process name
line = line.substring(1);
String mac = extractMacAddr(line);
if (mac.isEmpty() == false) {
return mac;
}
}
}
return null;
}
public static String extractMacAddr(String str) {
String arr[] = str.split(" ");
for (String string : arr) {
if (string.trim().length() == 17) {
return string.trim().toUpperCase();
}
}
return "";
}
关于java - 如何查找远程系统 MAC 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20117248/