Multiple IP Addresses in Ubuntu

This is a copy of a post in my old blog that seems to be getting quite a few hits, so I’ve decided to duplicate it here for all the people who still want to read it:


This is a reply to Stefano Rivers’a blog post Multiple IP addresses on Debian.

His post is about using “post-up” and “pre-down” in /etc/network/interfaces to add additional IP addreses to an interface, I propose a slightly prettier way of doing it.

The trick here is that Ubuntu (and probably Debian, they are very closely related) scans for and executes executable scripts in sub-directories of the /etc/network directory:

if-pre-up.d – Before brining an interface up

if-up.d – After bringing and interface up

if-down.d – Just before taking and interface down

if-post-down.d – Just after taking an interface down

Keeping that in mind, my method of adding IP addresses and special routes is to create a script called /etc/network/if-up.d/00routes that looks a bit like this:

#!/bin/bash

# Add IP 192.168.1.2 to eth0
# Add a route to network 192.168.2.0/24 via gateway 192.168.1.254
if [ "$IFACE" = "eth0" ]; then
  ip addr add 192.168.1.2/24 dev eth0
  ip add route 192.168.2.0/24 via 192.168.1.254 dev eth0
fi

I usually also have a script called /etc/network/if-up.d/01firewall to turn my firewall rules on:

#!/bin/bash

# Load firewall rules
if [ "$IFACE" = "eth0" ]; then
  # /etc/iptables is where my firewall rules are stored
  /sbin/iptables-restore < /etc/iptables
fi

And /etc/if-down.d/01firewall to turn them off again (note that there’s no need for a script to take additional IP addresses and routes down, they will be cleared when the interface goes down):

#!/bin/bash

# Save firewall rules and clear them
if [ "$IFACE" = "eth0" ]; then
  # /etc/iptables is where my firewall rules are stored
  /sbin/iptables-save > /etc/iptables
  # /etc/iptables-clear is a blank firewall ruleset
  /sbin/iptables-restore < /etc/iptables-clear
fi

Comments are closed.