Wednesday, 11 September 2013

How to set a static IP address on a Raspberry Pi

Note: This is only for wired (eth0) connections. Wifi instructions to follow.

Introduction:
When you first set up your Raspberry Pi, it will have been configured to automatically get an IP address (DHCP). This is fine. But, the address will probably be different each time you switch it on, so to do anything useful with it, like making it a webserver, it will need a static, or fixed known, IP address. That way you will always be able to access it remotely without having to first see what IP address it is using. It also means you'll be able to make your Pi accessible to the internet via port forwarding on your router.

Let's go.

First, make a backup of the current configuration.

SSH to your Pi, or login via the desktop and run Terminal.

$ sudo cp /etc/network/interfaces /etc/network/interfaces.orig

Let's now see what IP address it  has already got.

$ ifconfig -a

eth0      Link encap:Ethernet
          inet addr:192.168.1.74  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

The bits in bold above are the ones we need to know. In this case, our IP address is 192.168.1.74 The rest doesn't matter. We might as well use the same address, but make sure it's permanent (static IP) and doesn't change each time we switch the Pi on.

Next, let's find the IP address of our router (gateway):

$ route -n

Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.1.254   0.0.0.0         UG    0      0        0 eth0

Here, it's 192.168.1.254

Note that, in this example, your IP address, and that of the gateway (router) both start with 192.168.1

We'll go ahead and make the IP address static, why not stick with the address we've been given this time, to make things simple. In this case, it's 192.168.1.74 and the gateway is 192.168.1.254

So, edit the file:

$ sudo vi /etc/network/interfaces

Change the line that says:
iface eth0 inet dhcp

To
iface eth0 inet static

And add the following lines after it:

address 192.168.1.74
netmask 255.255.255.0
gateway 192.168.1.254

Save the file. Restart networking:
$ sudo service networking restart

Once you have your command prompt back, let's check the IP address has been set ok.
$ sudo ifconfig -a
We're looking for, in this example, eth0 to be 192.168.1.74

$ route -n
We're looking for, in this example, gateway 192.168.1.254

If you're cynical like me, reboot the Pi and check the above 2 commands again to make sure it's been set. 
$ ifconfig -a
and
$ route -n

You have now given your Pi a static (fixed) IP address of (in this example) 192.168.1.74 and a gateway of 192.168.1.254

Netmask, or subnet mask, or why all the IP addresses above begin with 192.168.1 is another tutorial. Shout me if you want it,