Linux 下用 netcat 测量 tcp 连接建立时间

本文未经验证,仅供参考。

我们希望测量两机之间 tcp 连接的建立时间,以排查网络连接缓慢的问题。
测量连接建立可以用 nc (netcat)。

以下是在 RHEL5 (CentOS 5) 的测试方法,其他发行版的 nc 参数可能会有所不同。

Server端监听 1567 端口:
~~~
# nc -k -l 1567
~~~
使用 -k 参数使之一直保持监听。

Client 端使用脚本建立1000次连接,并用 time 命令进行计时:

/tmp/testcon.sh
~~~
#!/bin/bash

NUM=1000 # How many connection to establish.
IPADDR="192.168.122.136"
PORT="1567"

for((i=0; i<$NUM; i++)) do nc $IPADDR $PORT < /dev/null if [ $? -ne "0" ];then echo "*" fi done ~~~
使用 time 命令计时,获得建立1000次连接的时间。
~~~
# time bash /tmp/testcon.sh

real 0m1.910s
user 0m0.317s
sys 0m0.957s
~~~

另外,nc 测量文件传输时间可用以下方法:

Server side:
~~~
# dd if=/dev/urandom of=/tmp/testfile bs=1M count=500
50+0 records in
50+0 records out
52428800 bytes (52 MB) copied, 5.98404 seconds, 8.8 MB/s

# md5sum /tmp/testfile
de718c820d6dc82bacffa3ef4bc6a457 /tmp/testfile

# nc -l 1567 < /tmp/testfile ~~~ Client side: ~~~ # time nc -n 192.168.122.136 1567 > /tmp/recfile

time nc -n 192.168.122.136 1567 > /tmp/recfile

real 0m2.632s
user 0m0.031s
sys 0m2.416s

# md5sum /tmp/recfile
de718c820d6dc82bacffa3ef4bc6a457 /tmp/recfile
~~~