How to configure `eth0` to retry `dhclient` when unplugged and replugged?
I'm working on a linux gadget.
I want it to get DHCP if I plug in the network cable after it has booted up already or if the network cable unplugged and replugged.
One solution is to run a script such as this (which works, btw):
#!/bin/bash
NET_STATUS='different'
while true
do
NEW_NET_STATUS=`ifconfig | grep RUNNING | grep -v LOOPBACK`
if [ "${NEW_NET_STATUS}" = "${NET_STATUS}" ]
then
echo "no change"
sleep 1
continue
fi
NET_STATUS=${NEW_NET_STATUS}
if [ "${NET_STATUS}" ]
then
echo "cable plugged in"
else
echo "cable unplugged"
fi
sleep 1
done
However, I've got a feeling deep down in my little toe that tells me that there's a better way to deal with hotplug events for the ethernet cable.
netplug
netplug
is the solution that I went with. ifplugd
may work just as well.
Installation
sudo apt-get install netplug
Interface Configuration
cat /etc/netplug/netplugd.conf
eth*
Event Configuration
cat /etc/netplug/netplug
#!/bin/sh
PATH=/usr/bin:/bin:/usr/sbin:/sbin
export PATH
dev="$1"
action="$2"
case "$action" in
in)
echo "$dev : $action : plugged in" >> /tmp/netplug.log
;;
out)
echo "$dev : $action : unplugged" >> /tmp/netplug.log
;;
probe)
echo "$dev : $action : probed" >> /tmp/netplug.log
;;
*)
echo "$dev : $action : I feel violated" >> /tmp/netplug.log
exit 1
;;
esac
Testing
/etc/init.d/netplug stop
/etc/init.d/netplug start
cat /tmp/netplug.log
eth0 : probe : probed
eth1 : probe : probed
...
eth15 : probe : probed
eth0 : in : plugged in
ifplugd handles this situation very well:
ifplugd
is a Linux daemon which will automatically configure your ethernet device when a cable is plugged in and automatically unconfigure it if the cable is pulled. This is useful on laptops with onboard network adapters, since it will only configure the interface when a cable is really connected.
ifplugd
interfaces with your distribution's native network configuration utilities.Some features:
- Uses your distribution's native
ifup
/ifdown
programs.- [...]
- Supports the Linux
SIOCETHTOOL
(newer, akaethtool
API),SIOCGMIIREG
(older, akamii-diag
/mii-tool
API) andSIOCDEVPRIVATE
(oldest, akamii-tool
API)ioctl()
s for getting link status. Release 0.24 introduces support for link detection with theIFF_RUNNING
interface flag.- [...]
- Can be configured to ignore short "unplugged" periods (
-d
option) or short "plugged" periods(-u
option)- [...]
- Compatibility mode for network devices which do not support cable detection (
-F
option)