Tuesday, June 2, 2009

Set a static IP address in Ubuntu

Even though relying on DHCP to assign IP addresses is usually easier, sometimes setting a static address at a local machine is the right thing to do. In Ubuntu, this is accomplished by editing a few system config files. Different Linux distributions handle network configurations differently. This should work for Debian, Ubuntu, and other Debian based systems. RHEL/CentOS use a different networking configuration so this will not work on those systems.

If you are going from using DHCP to setting a static address, make sure you know the existing network configuration. Determine your existing IP address with:
ifconfig
Also you will need to know your default gateway:
route -n
For more details how to interpret the results of this command, check this post. When the system boots, the networking daemon reads /etc/network/interfaces to determine whether to start DHCP or not. You need to edit this file and input your desired networking information. This assumes you are using a machine with only a single network adapter. If you have more than one in your computer this may be different.

Make a copy of the original file for backup purposes:
sudo cp /etc/network/interfaces /etc/network/interfaces.original
Now open /etc/network/interfaces with a text editor. It should look something like this:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto eth0
iface eth0 inet dhcp
If yours doesn't have the section at the bottom for eth0, that's ok, you can add it in. My Ubuntu server had that section but my Ubuntu desktop did not. You need to change the section dealing with eth0 so it looks like this:
auto eth0
iface eth0 inet static
address 192.168.1.10
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1

This assumes that you want an IP address of 192.168.1.10 and the default gateway is 192.168.1.1. Your configuration will likely be different. If you need to adjust your DNS servers, that is located at /etc/resolve.conf. First, make a copy of that file:
sudo cp /etc/resolve.conf resolve.conf.original
The servers the system will use for DNS are specified with their address preceeded by the word "nameserver." To add your default gateway as a nameserver, as it likely may be for you, make sure the file contains this line:
nameserver 192.168.1.1
Now all of these changes you have made will not take effect instantly. They will certainly take effect after you reboot. However, you can put them into effect now by restarting the networking daemon by typing:
sudo /etc/init.d/networking restart

No comments:

Post a Comment