java使用ping命令查看ip状态

其实java调用ping方法有很多 我只使用了其中一个 这个大佬是另一种 很详细

大佬写的另一种办法

这是我写的 比较烂 大佬轻喷

主要用到io流和Scanner 用的调用ping 是这个方法 Runtime 可以循环输入

/**
 * ClassName: Ping
 * Description:
 * date: 2022/1/22 10:21
 *
 * @author robotname a
 * @author dev whz
 * @since JDK 1.8
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class javaPing {

    public static void main(String[] args) throws IOException {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
        while (true) {
            System.out.println("请输入ip地址:");
            String str1 = scan.next();
            int  timeOut =  3000;
            Process p = Runtime.getRuntime().exec("ping " + str1);
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), "GB2312"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                if (line.length() != 0)
                    sb.append(line + "\r\n");
            }
            System.out.println("本次指令返回的消息是:");
            System.out.println(sb.toString());
            String string = sb.toString();
            if (string.contains("无法访问目标主机")) {
                System.err.println("这个人不在,或者没开机");
            }
            if (string.contains("字节=")) {
                System.err.println("这个人正在工作");
            }

        }
        // next方式接收字符串
        // 判断是否还有输入
//        if (scan.hasNext()) {
//             str1 = scan.next();
//            System.out.println("输入的数据为:" + str1);
//        }

    }

}

看看效果

next方式接收:
192.168.0.10
本次指令返回的消息是:
正在 Ping 192.168.0.10 具有 32 字节的数据:
来自 192.168.0.10 的回复: 字节=32 时间<1ms TTL=128
来自 192.168.0.10 的回复: 字节=32 时间<1ms TTL=128
来自 192.168.0.10 的回复: 字节=32 时间<1ms TTL=128
来自 192.168.0.10 的回复: 字节=32 时间<1ms TTL=128
192.168.0.10Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 0ms,最长 = 0ms,平均 = 0ms

这个人正在工作
next方式接收:

可以循环输入

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值