📜  如何在指定数量的 ECHO_REQUEST 数据包后告诉 ping 退出 - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:24:38.371000             🧑  作者: Mango

如何在指定数量的 ECHO_REQUEST 数据包后告诉 ping 退出 - Shell-Bash

在Linux系统中,ping命令可以用于测试网络连接情况。默认情况下,ping会一直发送ECHO_REQUEST数据包,直到手动停止或者按Ctrl+C中止。但是有时候我们可能需要在指定数量的数据包之后自动停止ping命令,这就需要用到ping命令的一些选项了。

基本用法

使用ping命令发送一个请求,会不断地发送数据包,直到手动中止:

ping example.com

使用-c选项可以指定发送的数据包数量。例如,以下命令会在发送10个数据包之后停止ping命令:

ping -c 10 example.com

输出结果:

PING example.com (93.184.216.34) 56(84) bytes of data.
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=1 ttl=58 time=12.6 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=2 ttl=58 time=12.4 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=3 ttl=58 time=12.4 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=4 ttl=58 time=12.4 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=5 ttl=58 time=12.5 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=6 ttl=58 time=12.5 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=7 ttl=58 time=12.3 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=8 ttl=58 time=12.5 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=9 ttl=58 time=12.6 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=10 ttl=58 time=12.4 ms

--- example.com ping statistics ---
10 packets transmitted, 10 received, 0% packet loss, time 9008ms
rtt min/avg/max/mdev = 12.309/12.493/12.679/0.171 ms
指定发送时间

使用-w选项可以指定每个数据包的超时时间(单位为毫秒)。例如,以下命令会在每个数据包的超时时间为2秒,总共发送10个数据包后自动停止ping命令:

ping -w 2000 -c 10 example.com

输出结果:

PING example.com (93.184.216.34) 56(84) bytes of data.
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=1 ttl=58 time=12.3 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=2 ttl=58 time=12.4 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=3 ttl=58 time=12.5 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=4 ttl=58 time=12.5 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=5 ttl=58 time=12.4 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=6 ttl=58 time=12.4 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=7 ttl=58 time=12.4 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=8 ttl=58 time=12.6 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=9 ttl=58 time=12.3 ms
64 bytes from 93.184.216.34 (93.184.216.34): icmp_seq=10 ttl=58 time=12.5 ms

--- example.com ping statistics ---
10 packets transmitted, 10 received, 0% packet loss, time 9017ms
rtt min/avg/max/mdev = 12.313/12.458/12.626/0.123 ms
小结

以上介绍了如何在指定数量的ECHO_REQUEST数据包后告诉ping退出。使用ping命令的-c选项可以设置发送数据包的数量,在达到指定数量后自动退出;使用ping命令的-w选项可以指定每个数据包的超时时间,在超过指定时间后自动退出。您可以根据实际情况选择合适的选项来测试网络连接。