java代码实现ping ip命令和 ping ip -t命令

1.java代码实现ping命令
<1> 使用InetAddress类的getByName(ip)方法

        int timeOut = 3000;
        boolean status = true;
        try {
                status = InetAddress.getByName(main_router_ip).isReachable(timeOut);
                if (status) {
//                    ping成功
                }
        } catch (Exception e) {
            e.printStackTrace();
        }

<2>调用cmd执行命令(ping ip 和 ping ip -t都可使用,其他cmd可执行的命令也可以使用并且可以打印输出的文字)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Test3 {
    public static void main(String[] args) throws Exception {
        Runtime runtime = Runtime.getRuntime(); // 获取当前程序的运行进对象
        Process process = null; //声明处理类对象
        String line = null; //返回行信息
        InputStream is = null; //输入流
        InputStreamReader isr = null;// 字节流
        BufferedReader br = null;
        String ip = "127.0.0.1";
        int requestNum = 0;
        int a= 0;
        boolean res = false;// 结果
        try {
            process = runtime.exec("ping " + ip + " -t"); // PING ip -t(会一直发)
            //process = runtime.exec("ping " + ip); // PING ip (注意ping只发四个请求)
            is = process.getInputStream(); // 实例化输入流
            isr = new InputStreamReader(is);// 把输入流转换成字节流
            br = new BufferedReader(isr);// 从字节中读取文本
            while ((line = br.readLine()) != null) {
                System.out.println(br.readLine());
                System.out.println(a++);
                if (line.contains("TTL")) {
                    requestNum++;
                    if (requestNum == 30) {
                        res = true;
                        break;
                    }

                }
            }
            is.close();
            isr.close();
            br.close();
            System.out.println(res);
            if (res) {
                System.out.println("ping通  ...");

            } else {
                System.out.println("ping不通...");
            }
        } catch (IOException e) {
            System.out.println(e);
            runtime.exit(1);
        }
    }
}

代码实现的结果:

在这里插入图片描述
cmd中执行的结果:
在这里插入图片描述


版权声明:本文为mingxu_W原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。