在局域网中获取所有IP和Mac地址

我在局域网中列出ip和mac地址所有设备(如网络扫描仪)

我想用java编程语言。

如果我使用我的IP地址,结果为真,但如果我在局域网中使用另一个IP地址,则网络变量为空。

(例如;我的IP地址:192.168.1.7,另一个IP地址:192.168.1.8)

这是我的代码;

public static void checkHosts(String subnet) throws UnknownHostException, IOException{ int timeout=3000; for (int i=1;i<255;i++){ String host=subnet + "." + i; if (InetAddress.getByName(host).isReachable(timeout)){ System.out.println(host + " is reachable" + InetAddress.getByName(host)); NetworkInterface network = NetworkInterface.getByInetAddress(InetAddress.getByName(host)); if(network!=null){ System.out.println(network.isUp()); byte[] mac = network.getHardwareAddress(); System.out.println(network.getDisplayName()); System.out.println(network.getName()); System.out.println(InetAddress.getByName(host).getHostName()); System.out.print("Current MAC address : "); StringBuilder sb = new StringBuilder(); for (int j = 0; j < mac.length; j++) { sb.append(String.format("%02X%s", mac[j], (j < mac.length - 1) ? "-" : "")); } System.out.println(sb.toString()); } } } } 

我一直在做一个项目来做同样的事情。 我认为最好的方法是在运行时执行另一个进程并读取结果。 如前所述,您可以读取系统ARP表并解析结果,但这取决于平台。 命令提示符下的windows命令是:arp -a。

我选择远程调用nmap并解析这些结果。 它需要在您的机器上安装nmap,但只要安装了适当版本的nmap,解决方案“应该”是跨平台的:

可在此处获取: https : //nmap.org/download.html

这是一个简单的例子。 您当然需要进行一些更改以动态选择要扫描的网络并解析结果而不是打印它们。

 try { Process proc = Runtime.getRuntime().exec("nmap -PR -sn 192.168.1.0/24"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); // read the output from the command String s = null; while ((s = stdInput.readLine()) != null) { System.out.println(s); // read any errors from the attempted command while ((s = stdError.readLine()) != null) { System.err.println(s); } } catch (IOException ex) { System.err.println(ex); } 

基本上,您要做的是在本地网络上实施ping扫描。 您提供的代码可能正在执行所需的ping扫描(取决于实现),但它只显示本地接口的MAC地址。 要确定网络上计算机的MAC地址,您必须查看机器的ARP缓存,该缓存不是独立于平台的,因此在Java中不易实现。

注释(和javadoc)中所述的NetworkInterface类用于本地接口。 它不能用于识别远程NIC。

 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RealMacAddress { public static void main(String args[]){ try { Process proc = Runtime.getRuntime().exec("arp -a "); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); // read the output from the command String s = null; while ((s = stdInput.readLine()) != null) { System.out.println(s); // read any errors from the attempted command while ((s = stdError.readLine()) != null) { System.err.println(s); } }}catch (IOException ex) { System.err.println(ex); } } }