我有一个项目可以对 LAN 网络上的所有计算机进行 ping 操作。首先我使用InetAddress.isReachable()
但有时函数返回 IP is not reachable() 即使 IP 是可访问的(尝试在 windows 上使用内置函数并且 IP 是可访问的)。其次,我尝试使用此代码:
Process proc = new ProcessBuilder("ping", host).start();
int exitValue = proc.waitFor();
System.out.println("Exit Value:" + exitValue);
但是输出是错误的。然后我google了一下,找到了这段代码:
import java.io.*;
import java.util.*;
public class JavaPingExampleProgram
{
public static void main(String args[])
throws IOException
{
// create the ping command as a list of strings
JavaPingExampleProgram ping = new JavaPingExampleProgram();
List<String> commands = new ArrayList<String>();
commands.add("ping");
commands.add("-n");
commands.add("1");
commands.add("192.168.1.1");
ping.doCommand(commands);
}
public void doCommand(List<String> command)
throws IOException
{
String s = null;
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null)
{
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null)
{
System.out.println(s);
}
}
}
此代码运行良好,但问题是当 Windows 使用其他语言时,您无法判断地址是否可访问。你们能否与我分享一个如何在 LAN 或 VPN 网络上 ping IP 地址的安全方法。谢谢你。