最近在写个程序用Runtime.exec来执行操作系统的ping命令以获得目标网络信息。
但是在solaris却遇到了困难,就是无法指定发包数量,需要手工ctrl+c停止命令,才会有统计信息的输出,后来研究了一把,终于得到了解决办法,下面先分享下各个系统上的ping命令是如何指定发包数的。
大家应该对windows下的ping很熟悉了。我们执行ping命令时,默认发送4个数据包,可以通过n参数指定发包数,并且最后还有个统计数据,如:
引用
C:\Documents and Settings\Administrator>ping -n 2 192.168.0.134
Pinging 192.168.0.134 with 32 bytes of data:
Request timed out.
Request timed out.
Ping statistics for 192.168.0.134:
Packets: Sent = 2, Received = 0, Lost = 2 (100% loss),
C:\Documents and Settings\Administrator>
而linux上也可以指定发包数,如:
引用
[root@eomssso1 ~]# ping -c 3 10.243.24.3
PING 10.243.24.3 (10.243.24.3) 56(84) bytes of data.
64 bytes from 10.243.24.3: icmp_seq=1 ttl=255 time=4.36 ms
64 bytes from 10.243.24.3: icmp_seq=2 ttl=255 time=0.266 ms
64 bytes from 10.243.24.3: icmp_seq=3 ttl=255 time=0.258 ms
--- 10.243.24.3 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1998ms
rtt min/avg/max/mdev = 0.258/1.628/4.360/1.931 ms
[root@eomssso1 ~]#
经过研究solaris下的ping参数,发现其实也是可以实现发送指定的数据包,只不过参数的选择上有些特定的规则,先看效果,效果如下:
引用
root@temip # ping -s 10.243.24.3 56 4
PING 10.243.24.3: 56 data bytes
64 bytes from emipserver1 (10.243.24.3): icmp_seq=0. time=0. ms
64 bytes from emipserver1 (10.243.24.3): icmp_seq=1. time=0. ms
64 bytes from emipserver1 (10.243.24.3): icmp_seq=2. time=0. ms
64 bytes from emipserver1 (10.243.24.3): icmp_seq=3. time=0. ms
----10.243.24.3 PING Statistics----
4 packets transmitted, 4 packets received, 0% packet loss
round-trip (ms) min/avg/max = 0/0/0
root@temip #
这里有3个重要的参数,-s、56和4,其中-s可以替换为-I,56为指定数据包大小,4表示发包次数为4次。
这3个参数缺一不可,我们来试试运行ping -s 10.243.24.3 1 4 ,指定数据包大小为1,结果如下:
引用
root@temip # ping -s 10.243.24.3 1 4
PING 10.243.24.3: 1 data bytes
9 bytes from emipserver1 (10.243.24.3): icmp_seq=0.
9 bytes from emipserver1 (10.243.24.3): icmp_seq=1.
9 bytes from emipserver1 (10.243.24.3): icmp_seq=2.
9 bytes from emipserver1 (10.243.24.3): icmp_seq=3.
----10.243.24.3 PING Statistics----
4 packets transmitted, 4 packets received, 0% packet loss
root@temip #
可以发现,如果指定的数据包太小,则没有最大最小及平均耗时的统计(需要>=8),