Setting up a Raspberry Pi 3 as an Access Point

Pages
Contributors: Shawn Hymel
Favorited Favorite 10

Enable Packet Forwarding

We can use the Raspberry Pi as a router by being able to connect it to another network over Ethernet and have WiFi-connected devices be able to talk to that network. By doing this, we can share an Internet connection from the Pi.

Configure NAT

Make sure you are logged into your Pi. Edit the /etc/sysctl.conf file:

language:bash
sudo nano /etc/sysctl.conf

Look for the line #net.ipv4.ip_forward=1, and uncomment it by deleting the #.

language:bash
net.ipv4.ip_forward=1

Your terminal window should look similar to the image below.

Enable IPv4 packet forwarding

Save and exit by pressing ctrl + x and y when prompted.

Finally, we need to configure Network Address Translation (NAT) between the Ethernet and WiFi interfaces to allow devices on both networks to communicate with each other. In the terminal, enter the following:

language:bash
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE  
sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT

This will work for now, but on reboot, the Pi will revert back to its previous state. To fix this, we need these NAT rules to be applied each time it starts up. Save the current rules to a file with this command:

language:bash
sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"

Linux provides us with a number of ways to run commands on boot. Usually, the easiest is to put those commands into the /etc/rc.local script. To have our NAT rules restored on boot, we edit the rc.local file:

language:bash
sudo nano /etc/rc.local

Just above the exit 0 line (which ends the script), add the following:

language:bash
iptables-restore < /etc/iptables.ipv4.nat 

Your terminal window should look similar to the image below.

Restore NAT rules during boot with rc.local

Save and exit by pressing ctrl + x and y when prompted.

Test It Out

Restart your Pi:

language:bash
sudo reboot

Give your Pi a couple minutes to restart (once again, no need to log in). Connect an Ethernet cable from your Internet router (or switch, etc.) to your Pi. Once the Pi has started, connect to the MyPiAP network from your computer. Open a web browser, and navigate to the website of your choice.

Example of a good website

You can also open a terminal on your computer and ping a known Internet address (e.g. 8.8.8.8 is one of Google's Public DNS servers).

Ping 8.8.8.8 over the Raspberry Pi WiFi network