Running Openelec on a Raspberry Pi is a great use of the small & cheap computer. This was my media center and file server on a first gen Raspberry Pi and now I run this media center optimised Linux distribution on a Raspberry Pi 2.

However, something goes funky with the wired networking. I haven’t worked out why, but for some reason the networking stack will die after some random amount of time. Easily fixed by removing and reseating the network cable in the router.

The situation had become untenable though, so I set out to make sure the Pi’s networking fixed itself.

This is the Bash script I used. It is a mashup of a few scripts that do a similar job that I found on the Web (thank you other people with blogs). It runs via a cron job every 5 minutes.

#!/bin/bash

# cron script for checking lan connectivity

# Ping count is set aggressively to 1, increase depending what you want.
PING_COUNT=1
PING="/bin/ping"


# Find the gateway IP address
GATEWAY_IP=`ip route | grep default | cut -d " " -f 3`
# ping test
$PING -n -c "$PING_COUNT" "$GATEWAY_IP" &>/dev/null

if [ "$?" -ge 1 ]
then
    # Try restart the eth0 interface
    ethtool --negotiate eth0
fi

What I like about this script is that it doesn’t leave the local network to perform its job. It discovers the gateway’s IP and pings it. Any problems doing that and it calls the Openelec way of restarting the network interface. If you’re using wifi or a usb ethernet adapter, then use the respective device in place of the eth0 device.