树莓派配置 AP,变身无线路由器
首先介绍一下系统环境,笔者用的是树莓派2B (Raspberry Pi 2 Model B)系统是 Arch Linux。另外购得了一个无线网卡,Tenda W311M,RT5370 芯片,支持 Soft-AP。无线网卡是否支持 AP,这点大家购买前一定要确认一下。
大家知道,配置无线 AP 有很多种方法,本文使用 hostapd + dnsmasq 进行配置,如果你不太习惯这两个工具,也可以使用其他方案。
确认无线网卡支持 AP 模式
执行
lsusb
查看接入的 USB 信息。1
2
3
4Bus 001 Device 004: ID 148f:5370 Ralink Technology, Corp. RT5370 Wireless Adapter
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp. SMC9514 Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub可以看到第一行便是笔者的无线网卡。
执行
iw list
查看无线网卡支持的模式。(如果没有请使用 pacman 安装)请注意
supported interface modes
这一项:1
2
3
4
5
6software interface modes (can always be added):
* IBSS
* managed
* AP
* AP/VLAN
* monitor如果包含
AP
则说明是网卡是支持的,可以继续下一步,否则说明网卡硬件不支持或者驱动不支持。
配置无线热点
安装 hostapd
修改(新建)
hostapd.conf
vim /etc/hostapd/hostapd.conf
,检查以下配置项:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22# 无线网卡名称,这里应该与无线网卡对应
interface=wlan0
driver=nl80211
# WIFI 名称
ssid=YourWiFiName
# 模式:a/b/g
hw_mode=g
# 信道
channel=6
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
# WIFI 密码
wpa_passphrase=Somepassphrase
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
# 最大支持的 station 数量
max_num_sta=5
logger_stdout=-1
logger_stdout_level=2启动
1
systemctl start hostapd
配置 DNS 和 DHCP 服务器
为无线网卡配置 IP 地址
1
ifconfig wlan 192.168.0.1/24
也可以使用
1
2ip link set up dev wlan0
ip addr add 192.168.0.1/24 dev wlan0修改
dnsmasq.conf
vim /etc/dnsmasq.conf
,检查以下几项:1
2
3
4
5
6
7
8
9
10
11
12# dnsmasq 的 dns 配置
resolv-file=/etc/resolv.dnsmasq.conf
# 无线网卡设备名
interface=wlan0
# ipconfig 配置的无线网卡地址
listen-address=192.168.0.1
bind-interfaces
dhcp-range=192.168.0.100,192.168.0.150,12h
# Google DNS
server=8.8.8.8
server=8.8.4.4
修改(新建)
resolv.dnsmasq.conf
3vim /etc/resolv.dnsmasq.conf
,增加:1
nameserver 127.0.0.1
启动
1
systemctl start dnsmasq
启用包转发和 NAT
检查当前转发设置
1
sysctl -a | grep forward
临时启用包转发
1
sysctl net.ipv4.ip_forward=1
编辑 /etc/sysctl.d/30-ipforward.conf 使每次启动时生效
1
2
3net.ipv4.ip_forward=1
net.ipv6.conf.default.forwarding=1
net.ipv6.conf.all.forwarding=1启用 NAT
1
2
3iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT导出 NAT 规则至文件
1
iptables-save > /etc/iptables/ap.rules
其他
如果网速不稳定,请确认是否安装了 haveged
上面配置完成后,每次重启后运行以下脚本即可
1
2
3
4
5ifconfig wlan0 192.168.0.1/24
systemctl start dnsmasq
iptables-restore < /etc/iptables/ap.rules
sysctl net.ipv4.ip_forward=1
systemctl start hostapd
树莓派配置 AP,变身无线路由器