问题描述
我列出了ip和mac地址所有lan中的设备(如网络扫描仪)
I am listing ip and mac address all devices in lan (like network scanner)
我想使用java编程语言。
I want use java programming languages.
如果我使用我的IP地址,结果为真,但如果我在局域网中使用另一个IP地址,则网络变量为空。
If i use my ip address,result is true but if i use another ip address in lan,network variable is null.
(例如;我的IP地址:192.168.1.7,另一个IP地址:192.168.1.8)
(for example ; my ip address : 192.168.1.7 , another ip address : 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。
I've been working on a project to do the same thing. I think the best way to go about this is to execute another process at run time and read the results. As already suggested, you could read the system ARP table and parse results, but this is platform dependent. The windows command in command prompt is: arp -a.
我选择远程调用nmap并解析这些结果。它需要在您的机器上安装nmap,但只要安装了适当版本的nmap,解决方案应该是跨平台的:
I chose to make a remote call to nmap and parse those results. It requires installing nmap on your machine, but the solutions "should" be cross-platform as long as the appropriate version of nmap is installed:
此处可用:
这是一个简单的例子。您当然需要进行一些更改以动态选择要扫描的网络并解析结果而不是打印它们。
Here's a quick example. You'd of course need to make some changes to dynamically choose the network to scan and parse the results instead of print them.
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);
}
这篇关于在局域网中获取所有IP和Mac地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!