Assign a static IP address to the wireless network interface on Raspberry Pi

Introduction

To easily access our wireless Raspberry Pi projects (like the Pi Rover) over SSH, FTP, HTTP or whatever, we want to assign a static IP to the WLAN interface. In this example the network address is 192.168.2.0/24 and the Pi should be at 192.168.2.12 (which falls outside the DHCP pool starting at 192.168.2.100). The router is at 192.168.2.1.

Configure WiFi

Once the WiFi dongle is plugged in, the easiest way to configure it is to run WiFi Config from the graphical desktop in Raspbian. Simply let it scan for the available network and connect to it. This will save some network specific settings to /etc/wpa_supplicant/wpa_supplicant.conf.

/etc/wpa_supplicant/wpa_supplicant.conf example:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
	ssid="....."
	psk="....."
	proto=RSN
	key_mgmt=WPA-PSK
	pairwise=CCMP
	auth_alg=OPEN
}

Configure a static IP address

Now you can edit /etc/network/interfaces to define a static configuration for wlan0. Change ‘iface wlan0’ from ‘dhcp’ to ‘static’ and add the IP definition of your LAN and the wlan0 interface as follows:

/etc/network/interfaces

auto lo
auto wlan0

iface lo inet loopback
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet static
address 192.168.2.12
netmask 255.255.255.0
network 192.168.2.0
broadcast 192.168.2.255
gateway 192.168.2.1
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

Make sure to include the ‘auto lo’ as well. Without the loopback you’ll end up in a world of misty symptoms, whereof an extremely slow SSH login is just an example.

EDIT: On Jessie the proper way to assign a static IP would be to configure the interface in /etc/dhcpcd.conf (and reboot to get rid of the ‘secondary’ assignment, see ‘ip addr’):

/etc/dhcpcd.conf

static interface wlan0
static ip_address=192.168.2.12/24
static routers=192.168.2.1
static domain_name_servers=192.168.2.1 8.8.8.8

Guarding the connection

You may not need this, but in my setup the WiFi connection sometimes completely freezes. This might be caused by the adapter driver, but it seems more likely to be caused by a bug in the router. The remedy is to restart the interface, which, of course, can be quite a challenge if there is no connection at all. So I created a simple script:

check_connection.sh

#!/bin/bash
 
wget -q --tries=10 --timeout=20 --spider http://google.com > /dev/null 2>&1
if [[ $? -ne 0 ]]; then
    sudo ifdown wlan0
    sleep 3
    sudo ifup wlan0
fi

This is called every five minutes from the crontab of a sudoer:

*/5 * * * * /home/pi/check_connection.sh

One thought on “Assign a static IP address to the wireless network interface on Raspberry Pi

Leave a Reply