Using this software of mine for network configuration, it's very easy.
http://code.google.com/p/badvpn/wiki/NCD
The following NCD program will do. It also shows how you can extend the configuration, in this case by running something when the network goes up/down.
process eth0 {
# Set device.
var("eth0") dev;
# Wait for device to appear, set it up, and wait for cable to be plugged in.
net.backend.waitdevice(dev);
net.up(dev);
net.backend.waitlink(dev);
# DHCP configuration.
# net.ipv4.dhcp() will block here until it obtaines an IP address.
# It doesn't check the obtained address in any way,
# so as a basic security measure, do not proceed if it is local.
net.ipv4.dhcp(dev) dhcp;
ip_in_network(dhcp.addr, "127.0.0.0", "8") test_local;
ifnot(test_local);
# Assign IP address to interface, as obtained by DHCP.
net.ipv4.addr(dev, dhcp.addr, dhcp.prefix);
# Add default route.
net.ipv4.route("0.0.0.0", "0", dhcp.gateway, "20", dev);
# Add DNS servers.
net.dns(dhcp.dns_servers, "20");
# Run an external program when network comes up or goes down.
list("/some/program/to/run/when/up", "argument") do;
list("/some/program/to/run/when/down", "argument") undo;
run(do, undo);
}
Note that this will not only handle the network cable being plugged in or out, but also the network interface itself appearing and disappearing (useful if it's USB).
The advantage of using NCD compared to other software like ifplugd is that its design alows for great flexibility. It basically allows you to program your own network config, as opposed to being limited to a limited set of hardcoded capabilities.
UPDATE: I've made Ubuntu packages for BadVPN and NCD. I've updated the wiki with installation and usage instructions for Ubuntu too: http://code.google.com/p/badvpn/wiki/NCD#Running_it
ifplugd
andnetplugd
appear unmaintained. However this similar question looks like it has a good (simple) answer using udev rules - no additional package needed. serverfault.com/a/312296/275255auto
toallow-hotplug
ininterfaces
.