Check whether network cable is plugged in without bringing interface up
Solution 1
ip link show
, by default shows all the interfaces, use ip link show up
to show only the running interfaces. You could use filters to get the difference.
Solution 2
Here is my script to update default routes based on the state of the connection in realtime. (runs in background)
works with multiple interfaces, I define priorities
in the /tmp/${iface}.metric
files, the 'best' connected interface will be used to route default traffic.
#!/bin/sh
/sbin/ip monitor link | while read -r line
do
iface=$(echo $line | sed -ne 's/[^ ]* \([^ ]*\): .* state \([^ ]*\).*/\1/p')
state=$(echo $line | sed -ne 's/[^ ]* \([^ ]*\): .* state \([^ ]*\).*/\2/p')
if [ "$iface" != "" ] ; then
echo "$iface is $state"
if [ -f /tmp/${iface}.metric ] ; then
echo "updating default route for ${iface}"
if [ "$state" = "DOWN" ] ; then
ip route del default dev "${iface}"
else
ip route add default dev "${iface}" metric `cat /tmp/${iface}.metric`
fi
fi
fi
done
Solution 3
ip link show displays the flag "LOWER_UP" to indicate the cable in plugged. You can also check for /sys/class/net/eth*/operstate or carrier. However, all of these only work for an interface with an IP address bound on it.
Related videos on Youtube
minaev
Updated on September 18, 2022Comments
-
minaev over 1 year
I am trying to identify NICs on ~20 remote servers (2-6 NICs on every server). To begin with, I want to identify those ready for use and free ones. How can I check the state of the physical media? I know some ways, including
ifconfig|grep RUNNING
,ethtool
,cat /sys/class/net/eth0/carrier
, but all they require that the interface is up. I don't want to bring ALL interfaces up. Not sure why, but I don't like to have enabled, but not configured interfaces in the network. Is there a way I can avoid this?Or am I just wrong and there's nothing bad about all interfaces being up (and not configured)? Even if they are plugged in?
-
minaev over 12 yearsBingo. Thanks. And
ip addr show
even adds IP addresses to the output. -
Gilles 'SO- stop being evil' over 12 yearsThat doesn't work on my machine (Debian squeeze, skge driver):
ip link show
shows nothing more than “DOWN”.ip
reports the same information asifconfig
and/sys/class/net/
in any case, doesn't it? Do you get link status information fromip
that's different from what you get under/sys/class/net
or fromifconfig
on your machine? Or do you get link status about interfaces that are down in/sys/class/net
(I get/sys/class/net/eth0/carrier: Invalid argument
)? -
X Tian about 10 yearsInteresting information, but doesn't really answer Original Post.
-
kangear about 9 yearseven if I haven't plugin eth, it will say "up" also.
-
Vladimir Kunschikov over 8 yearsit doesn't work if interface is down.
-
Joe over 7 years@Nikhil Mulley What do you mean by filters?