How to test an Internet connection with bash?

后端 未结 19 1419
青春惊慌失措
青春惊慌失措 2020-11-27 09:26

How can an internet connection be tested without pinging some website? I mean, what if there is a connection but the site is down? Is there a check for a connection with the

19条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 10:24

    This is notably faster than any solution posted here, and can be used to test a specific host too.

    The trick is solving the IP using a less busy DNS solver than the one employed by ping:

    validateConnection () {
        host="${1}"
        ip=$(getent ahostsv4 "${host}" | awk '{ print $1 }' | head -n1)
        ping -c1 "${ip}" 2>&1 >"/dev/null"
    
        if [ "${?}" -ne 0 ]; then
            echo "No connection to: ${host}" >&2
            exit 1
        fi
    }
    

提交回复
热议问题