树莓派共享以太网口上网

诉求

步骤

1. Enable Forwarding

Edit /etc/sysctl.conf, remove # before this line:

net.ipv4.ip_forward=1

Enable this configuration:

sudo sysctl -p

2. Configure the firewall

Enable NAT, use ip mask in wlan0

sudo iptables -F 
sudo iptables -P INPUT ACCEPT 
sudo iptables -P FORWARD ACCEPT 
sudo iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE

make firewall conf presistent

1. export firewall conf and save in /etc

sudo iptables-save > nat.rule
sudo mv nat.rule /etc

2. make it autostart after powering on

sudo nano /etc/network/if-pre-up.d/iptables:

#!/bin/bash
/sbin/iptables-restore < /etc/nat.rule

This file will be use when the network service starts, restore previously saved configurations via iptables-restore.

don’t forget to add executable permission:

sudo chmod 755 /etc/network/if-pre-up.d/iptables

3. set static ip in the device which connects to rpi

nano /etc/dhcpcd.conf, and add this:

# the interface you use, maybe not eth0 
interface eth0
# infact you can set 192.168.1.x, x in [2, 254]
static ip_address=192.168.1.10/24
# router ip is rpi eth0 ip
static routers=192.168.1.1
# dns is the dns rpi use, change it on your own occations
static domain_name_servers=10.10.10.1

When all is set well, reboot and it will work.

几点改进:

  1. 在debian上,静态ip推荐使用/etc/network/interfaces来配置。不必为了配静态IP而依赖dhclient。ubuntu则是netplan。
  2. 不要做不必要的操作。为什么要flush掉所有已有规则? 使用细化的iptables规则。为什么要修改系统预置的默认规则? 做NAT以及路由无需开启INPUT chain。FORWARD chain最好指明包的传递方向:sudo iptables -A FORWARD -i 来源IF -o 目标IF -j ACCEPT

iptables持久化方法与debian wiki保持一致

1 个赞