目标

在树莓派4B上创建一个频率为5Ghz的WiFi热点。

以下内容应该同样适用于树莓派3B+。

准备工作

给树梅派4B刷写系统,具体过程不赘述,我用的是目前最新的官方系统,镜像名称为2019-09-26-raspbian-buster.img。第一次进系统时请正确选择语言、国家、时区等等

用eth0连网

给树莓派连上网线,根据实际网络环境使用dhcp自动获取IP或者设置eth0的静态IP

固定wlan0的IP

编辑文件/etc/dhcpcd.conf, 添加如下配置

interface wlan0
static ip_address=192.168.4.1/24
nohook wpa_supplicant

现在重启dhcpcd守护进程:

sudo systemctl restart dhcpcd

安装dnsmasq,设置DHCP服务

先来说明一下我的网段设置,有线网络使用192.168.3.*这个网段,而无线AP端,使用192.168.4.*网段

使用命令sudo apt-get install dnsmasq安装dnsmasq,编辑/etc/dnsmasq.conf,添加如下配置:

 listen-address=127.0.0.1,192.168.4.1
 interface=wlan0
 dhcp-range=192.168.4.50,192.168.4.150,12h

运行命令sudo systemctl reload dnsmasq来启用

开启包转发、NAT

Linux系统默认关闭了IP包转发,因此不能做路由器。所以需要先打开包转发

编辑/etc/sysctl.conf,去掉以下属性前的注释:

net.ipv4.ip_forward=1

运行sudo sysctl -p来启用

之后运行

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

来启用eth0端口的NAT

配置防火墙

上一步中,我们启用了一条防火墙规则,但是防火墙规则重启后就丢失了,为了能够规则开机自动加载,我们可以使用iptables-persistent。用命令sudo apt-get install iptables-persistent来安装该组件,根据其提示进行初次设置(一路确认)。该组件默认会将防火墙规则保存到/etc/iptables/rules.v4中。你可以使用如下命令保存和读入规则:

#保存现有规则
 sudo service netfilter-persistent save
 #读取并应用先有规则
 sudo service netfilter-persistent reload

配置hostapd

启用WIFI热点,本文使用的是hostapd。首先,用命令sudo apt-get install hostapd安装它(安装时如果出现无法下载软件包的情况,请尝试更换为国内软件源,如阿里、中科大的源),然后增加配置文件/etc/hostapd/hostapd.conf如下:

interface=wlan0
driver=nl80211

hw_mode=a
ieee80211n=1
ieee80211ac=1
ieee80211d=1
ieee80211h=1
require_ht=1
require_vht=1
wmm_enabled=1
country_code=US

vht_oper_chwidth=1
channel=149
vht_oper_centr_freq_seg0_idx=155
ht_capab=[HT40-][HT40+][SHORT-GI-40][DSSS_CCK-40]

wpa=2
wpa_key_mgmt=WPA-PSK
rsn_pairwise=CCMP

ssid=wifiname
wpa_passphrase=1234567890

请更改其中的ssid和wpa_passphrase属性,分别为无线AP的名称和密码。注意country_code=US这行必须有,更换为其他国家代码似乎都不行。

之后运行命令sudo hostapd -d /etc/hostapd/hostapd.conf来观察测试,没有错误可以连接,就OK了。 CTRL+C后,编辑/etc/default/hostapd,改变DAEMON_CONF的配置如下

DAEMON_CONF="/etc/hostapd/hostapd.conf"

正式启动AP

sudo systemctl unmask hostapd

sudo systemctl enable hostapd

sudo systemctl start hostapd

关机重启一下,看看AP是否能够启动起来。如果正常就OK了。

附注:更换默认源为阿里云更新源

编辑 /etc/apt/sources.list 文件,删除原有内容,添加如下内容:

deb http://mirrors.aliyun.com/raspbian/raspbian/ buster main contrib non-free rpi
deb-src http://mirrors.aliyun.com/raspbian/raspbian/ buster main contrib non-free rpi

然后执行一下命令sudo apt-get update

7 个评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注