Static IP with Ubuntu Server

My home router’s DHCP server has the bad habit of ignoring MAC addresses when handing out IPs, which means that every time it is reset for some reason, or a machine’s lease ends, it can get an entirely different IP . Since I have two machines with a wired connection in my network, one of which is my home server (it is actually the machine that is serving you this blog) I need it to have always the same IP.

Setting that up is in fact not that hard. I found the solution here. Basically, you edit /etc/network/interfaces.


iface eth0 inet dhcp

and replace it with:

iface eth0 inet static

where is the desired address and is my router. If yours differ, change them accordingly. Then I did

# sudo /etc/init.d/networking restart

Like most DHCP servers, the one my router will hand the a specific IP when one is requested and available, so it worked perfectly.

Until the next morning, that is. The machine didn’t respond to ping, much less to ssh, http or whatever. So I plugged in a monitor and a keyboard, logged in and restarted the networking daemon again. It got the right IP. Then I looked through the config of my router, to find out that it has a maximum DHCP lease of one day. Ubuntu’s networkmanager program requests an IP always immediately after the connection has been lost, so this only became a problem after changing /etc/network/interfaces. I needed something that would make the machine reconnect whenever the connection is lost.

I found the solution here. The text over there claims it is for wireless connections only, but it works equally well for any other kind of connection. What you do is create a file called networktest, and put these contents in it:

# FILENAME: /usr/bin/networktest
# note the backticks in the next line
if ! `ping -c3 >/dev/null 2>&1` ; then
    /etc/init.d/networking restart
exit 0

This script tests the connection and restarts the networking daemon when it is down. The script must be put in a suitable place and made executable:

# sudo chmod 744 networktest
# sudo chown root:root networktest
# sudo mv networktest /usr/bin/

The last step was to add it to root’s cron tab, so that it will be executed on a regular basis:

# sudo crontab -e

I added the line:

* 3 * * 0 /usr/bin/networktest

This made sure the network connection is tested every minute, and restored whenever it is available again. I tested it by taking down the network connection (I was working from another machine, so that in fact made me lose the ssh connection):

# sudo /etc/init.d/networking stop

and a minute later the connection was there again.

Categorised as: howto, linux

One Comment

  1. Just landed on this place via Google search. I love it. This post switch my perceptual experience and I am getting the RSS feeds. Cheers.