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 :
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 :
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 :
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.
# interfaces(5) file used by ifup(8) and ifdown(8)
# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'
# Include files from /etc/network/interfaces.d:
iface lo inet loopback
iface eth0 inet static
iface wlan0 inet static
- 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.
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.