0

Im writing a bash script that detects when connection to the internet has dropped and attempts to reconnect as well as displaying status on leds.

Im using the netcat command to connect to google on port 80 to determine if network connection is live

This all works fine when internet is connected, however, when powering off my router (simulating dropout) the netcast command takes aroud 30 seconds to timeout!

Application is for a WiFi radio,

#!/bin/bash

sig_state=0

echo "Network Watchdog ON"

echo "0" > /sys/class/gpio/export
echo "out" > /sys/class/gpio/gpio0/direction

function sig_led_high
{

        echo "0" > /sys/class/gpio/gpio0/value
        sig_state=1
}

function sig_led_low
{

        echo "1" > /sys/class/gpio/gpio0/value
        sig_state=0
}

sig_led_low

while true ; do
        echo "Testing nwrk..."

        if      nc -z -w 1 www.google.co.uk 80  > /dev/null 2>&1; then
                echo "Network OK. (nwd)"
                if ((sig_state)); then
                        sig_led_low
                fi

        else
                if !((sig_state)); then
                        sig_led_high
                fi
                echo "Network connection down! Attempting reconnection."
                ifup --force wlan0  > /dev/null 2>&1

                if      nc -zw1 www.google.co.uk 80  > /dev/null 2>&1; then
                mpc play
                fi
        fi

        sleep  1

done
andowt
  • 274
  • 1
  • 4
  • 15
  • did you look at `man nc` to see if the program offers an options to change the timeout value? Otherwise, you're looking at rather clunky and fragile solution/work-around involving running `nc` in the back ground, and testing with `kill -X $!` in a loop that counts to your timeout value. `X` is an option for `kill` that that reports if the process ID exists. `X` isn't the real option to `kill`, it is a place holder. Check you `man kill` for the correct arg (I can't think of it right now). Good luck. – shellter Apr 12 '18 at 12:46
  • 1
    can you test without resolveur: `nc -z -w1 8.8.8.8 53 2>/dev/null && echo ok || KO` – kyodev Apr 12 '18 at 13:09

0 Answers0