How to tell if the WAN cable is no longer plugged in?

Within an ash script, I want to be able to detect when a WAN cable is unplugged from the router.

I have tried the network_ready_device wan function of /lib/functions/network.sh but it only returns false, no matter whether the wan is active or not. I can not use the wan IP address, because that sticks around for as long as the lease is valid (even though the cable is unplugged).

Is there another way?

# test script
. /lib/functions/network.sh

  while true; do
    network_flush_cache

    ipWAN=""    # router IP address on WAN side
    if network_get_ipaddr ipWAN wan; then
      echo got ip=$ipWAN
    else
      echo got NO ip address
    fi

    if network_ready_device wan ; then
      echo WAN is ready
    else
      echo wan is not ready
    fi

    sleep 5

  done
1 Like

In most all-in-one devices, the interface handles only the protocol-level part of Ethernet and is connected to the switch with an industry-standard bus like GMII. As a result, eth0 is "always" up, even without cables plugged in, as the switch answers "I'm here and running." The "phy", the part that deals with the physical layer, is typically part of the switch and that is what you need to query.

As a hint as to what might work for you, from an Archer C7v2:

jeff@office:~$ swconfig dev switch0 show | fgrep link
	link: port:0 link:up speed:1000baseT full-duplex txflow rxflow 
	link: port:1 link:up speed:1000baseT full-duplex auto
	link: port:2 link:down
	link: port:3 link:down
	link: port:4 link:down
	link: port:5 link:down
	link: port:6 link:up speed:1000baseT full-duplex txflow rxflow 

Interesting. I can see my physical switch is reporting that port 1 changes with unplugging the WAN. In the output of ip addr it is listed as eth0.2

        link: port:1 link:up speed:100baseT full-duplex txflow rxflow auto
-
        link: port:1 link:down

Is there a general purpose way of figuring out which physical switch port is associated with the WAN?

It's all in your switch configuration. Ports on a switch don't have an "IP". The interface that sends packets to the switch has one or more.