使用 hostapd、udhcpd 搭建无线路由器 (树莓派、香橙派折腾系列)

4,158 阅读1分钟

简介

通过配置 hostapdudhcpdsysctliptablesinterfaces, 开启热点通过转发实现无线路由器(wifi)功能。

1.安装 hostapd、udhcpd

更新资源命令: apt-get update

安装命令: apt-get install udhcpd

注:一般情况下系统会自带 hostapd,没有的可以安装一下 apt-get install hostapd

如果更新资源失败需要:

更换国内apt-get源:

备份:cp /etc/apt/sources.list /etc/apt/sources.list.bak

替换:sed -i 's/:\/\/\(.*\)\//:\/\/<源地址>/g' /etc/apt/sources.list

更新:apt-get update

<源地址>

清华:mirrors.tuna.tsinghua.edu.cn/ubuntu-ports

阿里:mirrors.aliyun.com/ubuntu

2.编辑配置文件

udhcpd(动态IP分配服务):

vi /etc/udhcpd.conf

start		192.168.30.20	#default: 192.168.0.20
end		192.168.30.254	#default: 192.168.0.254
interface	wlan0		#default: eth0
remaining	yes		#default: yes
opt	dns	8.8.8.8 114.114.114.114
option	subnet	255.255.255.0
opt	router	192.168.30.1

vi /etc/default/udhcpd

注释掉

# DHCPD_ENABLED="no"

hostapd(热点服务):

vi /etc/hostapd.conf

interface=wlan0
   driver=nl80211
  ssid=WIFINAME  #要显示的wifi名
  hw_mode=g
  channel=6
  macaddr_acl=0
  auth_algs=1
  ignore_broadcast_ssid=0
  wpa=2
  wpa_passphrase=12345678  #wifi密码,不少于8位
  wpa_key_mgmt=WPA-PSK
  wpa_pairwise=TKIP
  rsn_pairwise=CCMP

vi /etc/default/hostapd

取消注释

DAEMON_CONF="/etc/hostapd.conf"

sysctl(开启转发):

vi /etc/sysctl.conf

取消注释

net.ipv4.ip_forward=1 #1开启、0关闭

注:sysctl 可以修改内核参数,临时开启数据转发命令:sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"

iptables(配置防火墙规则):

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

iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT

iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT

sh -c "iptables-save > /etc/iptables.ipv4.nat"(保存到/etc/iptables.ipv4.nat)

interfaces(为wlan0配置为静态IP):

vi /etc/network/interfaces

末尾追加以下内容

allow-hotplug eth0  #lan口配置热更新  
iface wlan0 inet static  #为端口wlan0配置静态IP 
    address 192.168.30.1 
    netmask 255.255.255.0\
up iptables-restore < /etc/iptables.ipv4.nat  #启用配置文件/etc/iptables.ipv4.nat里的防火墙规则

注:临时设置IP地址命令: ifconfig wlan0 192.168.30.1

3.启动命令

service hostapd start

service udhcpd start