树莓派4B搭建无线路由器

树莓派4B系统信息
root@raspi4b:~# uname -a
Linux raspi4b 4.19.75-v7l+ #1270 SMP Tue Sep 24 18:51:41 BST 2019 armv7l GNU/Linux
root@raspi4b:~#
root@raspi4b:~# lsb_release -a
No LSB modules are available.
Distributor ID:    Raspbian
Description:    Raspbian GNU/Linux 10 (buster)
Release:    10
Codename:    buster
root@raspi4b:~#
root@raspi4b:~#


先拆卸和清除软件和配置信息,如果不放心(之前的错误配置会导致后续配置错误),dhcpcd和dhcpcd5都可以删除(注意:删除前请先备份配置文件),只是树莓派失去了dhcp的功能而已,可以尝试配置静态IP给树莓派,修改这个文件即可:/etc/network/interface
apt-get autoremove --purge udhcpd
apt-get autoremove --purge hostapd
apt-get autoremove --purge dnsmasq
注意:-purge 选项是删除软件的同时把配置文件也清除干净。

安装 dnsmasq 和 hostapd
sudo apt-get update
sudo apt-get install dnsmasq hostapd udhcpd
修改/etc/network/interfaces设置eth0为DHCP并自动连接以太网(做NAT出口),wlan0为固定IP(做内网接口)

# 表示使用localhost
auto lo
iface lo inet loopback

# eth0自动获取IP
auto eth0
iface eth0 inet dhcp
# pre-up wpa_supplicant -Dwext -i wlan1 -c /etc/wpa_supplicant/wpa_supplicant.conf -B
 
# wlan0 为静态IP
auto wlan0
allow-hotplug wlan0
iface wlan0 inet static
address 192.168.150.1
netmask 255.255.255.0
重启树莓派4B
sudo service dhcpcd restart
sudo reboot
配置UDHCP
编辑配置文件/etc/udhcpd.conf
start 192.168.150.20 #配置网段
end 192.168.150. 50
interface wlan0       # The device uDHCP listens on.
remaining yes
opt dns 8.8.8.8 8.8.4.4
opt subnet 255.255.255.0
opt router 192.168.150.1   # 无线lan网段
opt lease 864000       # 租期10天
配置 HOSTAPD
创建hostapd.conf
sudo vi /etc/hostapd/hostapd.conf
添加如下配置
interface=wlan0
driver=nl80211
ssid=raspi4b
hw_mode=g
channel=6
wmm_enabled=1
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=88888888
wpa_key_mgmt=WPA-PSK
rsn_pairwise=CCMP
修改 /etc/default/hostapd ,让系统每次启动都自动加载AP模式下的配置。
DAEMON_CONF="/etc/hostapd/hostapd.conf"
设置开机启动
sudo update-rc.d hostapd enable
备份默认配置文件
sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.bak
添加以下内容
interface=wlan0
bind-interfaces
server=218.2.2.2
server=114.114.114.114
server=8.8.8.8
domain-needed
bogus-priv
dhcp-range=192.168.150.2,192.168.150.254,12h
设置 IPV4 转发
打开系统配置文件sysctl.conf,去掉IPV4转发那一行的#注释
sudo vi /etc/sysctl.conf
# Uncomment the next line toenable packet forwarding for IPv4
net.ipv4.ip_forward=1
外置无线接口共享给wlan0上网,需要配置NAT:
sudo iptables -F
sudo iptables -X
sudo iptables -t nat -APOSTROUTING -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
保存以上防火墙规则
sudo sh -c "iptables-save> /etc/iptables.ipv4.nat"
在/etc/network/interfaces 末尾增加一行,设置为开机启动
up iptables-restore < /etc/iptables.ipv4.nat
保存退出,然后修改 iptables 权限:
sudo chmod 755 /etc/network/if-pre-up.d/iptables
重启树莓派
sudo reboot

 

你可能感兴趣的:(树莓派,树莓派4B)