Let's make comprehension easy ...
Ever wondered if you could setup a sub network on one side of Raspberry Pi and other side get connected to your home network ? Why would you do that ? (1) This will help you understand basics of routing and the minimum services required for a device to connect and communicate successfully. This article describes how to setup Raspberry Pi as router allowing to create a subnet.
Prerequisuites before we jump into details. We will need a Raspberry Pi with a Wifi and a LAN port, and we also assume that you have Raspberry Pi OS installed, and you can login to the Pi terminal.
Lets start by defining the networks on the Pi interfaces:
Create file /etc/systemd/network/10-wlan0.network with following contents:
Create file /etc/systemd/network/10-lan0.network
And then, enable and restart network-manager service
sudo systemctl enable systemd-networkd sudo systemctl start systemd-networkd
Verify the IPs are assigned with command:
ip a
Next, Configuring bidirectional routing on the PI by installing IP tables
sudo apt install -y iptables
and run the commands
sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT sudo iptables -A FORWARD -i eth0 -o wlan0 -j ACCEPT
and save the rules:
sudo sh -c "iptables-save > /etc/iptables.rules"
Since we want to restore the rules everytime the system is rebooted, we have to setup a service to load these rules, create file /etc/systemd/system/iptables-restore.service
And enable and restart the service
sudo systemctl daemon-reload sudo systemctl enable iptables-restore.service sudo systemctl start iptables-restore.service sudo reboot # Check the rules are restored after reboot sudo iptables -L -v -n
Enable the IP forwarding by editing the file /etc/sysctl.conf
apply the setting by executing the below command:
sudo sysctl -p
On your home router, login and define the route to state any traffic belonging to 192.168.2.0/24 network should be routed to 192.168.0.30
Destination: 192.168.2.0/24
Gateway: 192.168.0.30 (Raspberry Pi’s wlan0 IP)
Metric: 2
We also want the new device that connects to Pi to get IP address assigned and route the traffic via PI, hence we need to install and enable DHCP on PI, run the below commands:
sudo apt update
sudo apt install isc-dhcp-server -y
Edit the file: /etc/default/isc-dhcp-server and update the line
INTERFACESv4="eth0"
so that DHCP is enabled only for eth0
and then edit /etc/dhcpd.conf
Restart DHCP service and enable it:
sudo systemctl restart isc-dhcp-server sudo systemctl status isc-dhcp-server
reboot ip route # Output 192.168.0.0/24 dev wlan0 proto kernel scope link src 192.168.0.30 metric 600 192.168.2.0/24 dev eth0 proto kernel scope link src 192.168.2.1
sudo systemctl status systemd-networkd # Should be running
sudo systemctl status isc-dhcp-server # Should be running
A device connected to home network should be able to ping 192.168.2.1
Comments: