通常情況下,linux系統網絡連通性的檢測有兩種方法:
1、通過“ping指令 + 目標IP” 或者 “ping指令 + 目標IP域名”
注意針對IPv6地址的IP網絡檢測需要試用ping6,同時ping6中不能使用參數hops,因為IP6源碼中已經舍棄了路由,見如下英文解釋:
SYNOPSIS
ping [-aAbBdDfhLnOqrRUvV] [-c count] [-F flowlabel] [-i interval] [-I interface] [-l preload] [-m mark] [-M pmtudisc_option] [-N nodeinfo_option]
[-w deadline] [-W timeout] [-p pattern] [-Q tos] [-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp option] [hop ...] destinationt.
Notes:
ping6 is IPv6 version of ping, and can also send Node Information Queries (RFC4620). Intermediate hops may not be allowed, because IPv6 source
routing was deprecated.
ping指令調用時的常用參數:
# Parameter:
# -c the number of packages to send
# -i internel between two packages
# -W timeout seconds
# Check the connect status of internet function check_ip_status() { ping -c 3 -i 0.2 -W 3 $1 &> /dev/null if [ $? -eq 0 ];then return 0 else return -1 fi }
check_ip_status 10.74.120.104
if [ $? -ne 0 ];then echo "cannot connect guestconf server:10.74.120.104" exit -1 fi
2、使用“curl指令 + IP域名”
#!/usr/bin/bash # #檢測網絡鏈接&&ftp上傳數據 function networkAndFtp() { #超時時間 timeout=5 #目標域名 target=www.baidu.com #獲取響應狀態碼 ret_code=`curl -I -s --connect-timeout $timeout $target -w %{http_code} | tail -n1` if [ "x$ret_code" = "x200" ]; then #網絡暢通 else #網絡不暢通 fi }
在調用shell函數時需要注意一下兩個地方:
1、函數的返回值應采用echo
2、函數的狀態碼應采用return