How to test an Internet connection with bash?

后端 未结 19 1210
青春惊慌失措
青春惊慌失措 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:09

    Ping was designed to do exactly what you're looking to do. However, if the site blocks ICMP echo, then you can always do the telnet to port 80 of some site, wget, or curl.

    0 讨论(0)
  • 2020-11-27 10:11

    shortest way: fping 4.2.2.1 => "4.2.2.1 is alive"

    i prefer this as it's faster and less verbose output than ping, downside is you will have to install it.

    you can use any public dns rather than a specific website.

    fping -q google.com && echo "do something because you're connected!"

    -q returns an exit code, so i'm just showing an example of running something you're online.

    to install on mac: brew install fping; on ubuntu: sudo apt-get install fping

    0 讨论(0)
  • 2020-11-27 10:14

    The top answer misses the fact that you can have a perfectly stable connection to your default gateway but that does not automatically mean you can actually reach something on the internet. The OP asks how he/she can test a connection with the world. So I suggest to alter the top answer by changing the gateway IP to a known IP (x.y.z.w) that is outside your LAN.

    So the answer would become:

    ping -q -w 1 -c 1 x.y.z.w > /dev/null && echo ok || echo error
    

    Also removing the unfavored backticks for command substitution[1].

    If you just want to make sure you are connected to the world before executing some code you can also use:

    if ping -q -w 1 -c 1 x.y.z.w > /dev/null; then
        # more code
    fi
    
    0 讨论(0)
  • 2020-11-27 10:17

    Without ping

    #!/bin/bash
    
    wget -q --spider http://google.com
    
    if [ $? -eq 0 ]; then
        echo "Online"
    else
        echo "Offline"
    fi
    

    -q : Silence mode

    --spider : don't get, just check page availability

    $? : shell return code

    0 : shell "All OK" code

    Without wget

    #!/bin/bash
    
    echo -e "GET http://google.com HTTP/1.0\n\n" | nc google.com 80 > /dev/null 2>&1
    
    if [ $? -eq 0 ]; then
        echo "Online"
    else
        echo "Offline"
    fi
    
    0 讨论(0)
  • 2020-11-27 10:17

    make sure your network allow TCP traffic in and out, then you could get back your public facing IP with the following command

    curl ifconfig.co
    
    0 讨论(0)
  • 2020-11-27 10:19

    Pong doesn't mean web service on the server is running; it merely means that server is replying to ICMP echo. I would recommend using curl and check its return value.

    0 讨论(0)
提交回复
热议问题