其实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.10 的 Ping 统计信息:
数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
最短 = 0ms,最长 = 0ms,平均 = 0ms
这个人正在工作
next方式接收:
可以循环输入