Give a static IP address to your Raspberry Pi

When working with a Raspberry Pi, it is often convenient to give it a static IP address. For example, if you use it as a DNS server to block ads with Pi-Hole, you don’t want its IP address to change over time. Let’s learn how to give your Raspberry Pi a static IP address!

Why a static address?

By default, the Raspberry, just like any Linux machine, is configured to get its IP address from a DHCP server (Dynamic Host Configuration Protocol). This means that every time your Raspberry connects to your router, it will be given an IP address, which can vary. It’s this change of IP address that we’ll learn how to avoid in this tutorial.

Having a static IP address is particularly helpful if you want to run your Raspberry Pi as a headless server (with no screen or keyboard). It is also needed if you run it as a DNS server, because your other devices need to be given a single IP address that they will hit for DNS requests.

Get your connection settings

We’re first gonna need some information:

  • The IP address of your Raspberry Pi, and its network mask (netmask). To get it, enter the command ifconfig :
Output of the command ifconfig
Output of ifconfig

Here, we see that the IP address of my Pi is 192.168.1.81, and its netmask is 255.255.255.0. Take note of those values in your case, we’ll need them later.

  • The address of your gateway. In a home network, your gateway will most likely be your router. To find its IP address, type ip route :
Output of ip route

My gateway is 192.168.1.254. Take note of yours.

  • The address of your domain name server (DNS). It is, in most cases, the same as your gateway. To find it, type cat /etc/resolv.conf :
Content of resolv.conf file
Content of resolv.conf file

Change your configuration

If you read this tutorial on how to connect your Raspberry Pi to a Wifi network, you’re already familiar with the interfaces file. In this file, you can specify what method is used to get an IP address when a network interface goes up. Let’s modify it to assign a static IP address for both en0 (Ethernet) and wlan0 (Wifi), by modifying the interfaces file: nano /etc/network/interfaces. I’ll use .80 and .81, but feel free to use any address that is not already assigned to another device on your local network.

  • Address is the IP address you want to assign to the interface
  • Netmask is the network mask that we’ve found in the previous step
  • Gateway is the IP address of your local network’s gateway

Exit and save the file by hitting Ctrl+X and then Y.

Test it

Now reboot your Raspberry Pi ( sudo reboot ). After the reboot, your Raspberry should always have the same IP address, the one that you entered in the /etc/network/interfaces  file.

 

 

Be the first to comment

%d bloggers like this: