How to check internet access using bash script in linux?

前端 未结 10 1198
孤街浪徒
孤街浪徒 2021-02-01 06:43

In my school, the internet is not available(every night after 23:0 the school will kill the internet, to put us in bed >..<), then the ping will never stop, though I have use

10条回答
  •  面向向阳花
    2021-02-01 07:24

    If the school actually turns off their router instead of redirecting all traffic to a "why aren't you in bed" page, then there's no need to download an entire web page or send HTTP headers. All you have to do is just make a connection and check if someone's listening.

    nc -z 8.8.8.8 53
    

    This will output "Connection to 8.8.8.8 port 53 [tcp/domain] succeeded!" and return a value of 0 if someone's listening.

    If you want to use it in a shell script:

    nc -z 8.8.8.8 53  >/dev/null 2>&1
    online=$?
    if [ $online -eq 0 ]; then
        echo "Online"
    else
        echo "Offline"
    fi
    

提交回复
热议问题