📜  在Java中 Ping 一个 IP 地址 | Set 2(通过创建子流程)

📅  最后修改于: 2022-05-13 01:54:56.926000             🧑  作者: Mango

在Java中 Ping 一个 IP 地址 | Set 2(通过创建子流程)

在文章 Ping an IP address in Java中,我们讨论了如何使用Java.net.InetAddress.isReachable()方法 ping IP 地址。在这篇文章中,我们将讨论如何通过创建子进程来执行 ping 命令。

先决条件: ProcessBuilder类,Process类
下面的Java程序创建了一个方法commands() ,它以 command(ping) 列表作为参数。我们知道 ProcessBuilder 类用于创建操作系统进程, ProcessBuilder.start()启动将执行 ping 命令的子进程。

Java
// Java program for ping using sub-process
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
 
public class PingWebsite
{
    // method for finding the ping statics of website
    static void commands(ArrayList commandList)
                                           throws Exception
    {
        // creating the sub process, execute system command
        ProcessBuilder build = new ProcessBuilder(commandList);
        Process process = build.start();
         
        // to read the output
        BufferedReader input = new BufferedReader(new InputStreamReader
                                   (process.getInputStream()));
        BufferedReader Error = new BufferedReader(new InputStreamReader
                                   (process.getErrorStream()));
        String s = null;
         
        System.out.println("Standard output: ");
        while((s = input.readLine()) != null)
        {
            System.out.println(s);
        }
        System.out.println("error (if any): ");
        while((s = Error.readLine()) != null)
        {
            System.out.println(s);
        }
    }
     
    // Driver method
    public static void main(String args[]) throws Exception
    {
        // creating list for commands
        ArrayList commandList = new ArrayList();
         
        commandList.add("ping");
        // can be replaced by IP
        commandList.add("www.google.com");
         
        PingWebsite.commands(commandList);
    }
}


输出:

Standard output: 
PING www.google.com (216.58.220.164): 56 data bytes
64 bytes from 216.58.220.164: icmp_seq=0 ttl=53 time=98.803 ms
64 bytes from 216.58.220.164: icmp_seq=1 ttl=53 time=87.856 ms
64 bytes from 216.58.220.164: icmp_seq=2 ttl=53 time=110.600 ms
64 bytes from 216.58.220.164: icmp_seq=3 ttl=53 time=92.897 ms
64 bytes from 216.58.220.164: icmp_seq=4 ttl=53 time=90.142 ms

--- www.google.com ping statistics ---
5 packets transmitted, 5 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 87.856/96.060/110.600/8.140 ms
error (if any): 

阅读和理解输出:到目的地的每一行代表一个数据包传输,最后以毫秒为单位指定的时间与测试互联网连接最相关,因为那里的数字越大,表示延迟或连接问题越高。如果根本没有响应,要么服务器宕机,要么连接有问题,要么没有响应 ping 请求,要么响应很慢。
没有网络连接时的输出:当我们的系统没有连接网络时,上面程序的输出变得非常有趣
输出:

Standard output: 
error (if any): 
ping: cannot resolve www.google.com: Unknown host