Raspberry pi做成無線熱點

Raspberry pi作爲卡片式微型電腦,本身沒有自帶顯示器、鼠標、鍵盤等外設,如果想對Raspberry PI進行設定需要連接顯示器,或者通過路由器ssh登陸纔可以。心想Raspberry pi是可以運行Linux系統的卡片型電腦,爲何不嘗試把Raspberry Pi做成一個無線AP,想登陸Raspbery pi的時候就比較方便了。後續也可以加上USB存儲外設之類的做個多媒體網關等等。


主要的實現思路是wlan0設定成固定IP,eth0動態獲取IP。Raspberry Pi運行hostapd和udhcpd分別作爲無線AP熱點和DHCP服務器給終端分配IP地址。

目前我手上的wifi網卡是Realtek的8818芯片。如果直接按照網上的教程安裝hostapd的話會出現錯誤。經過一番查找,Realtek公司專門有針對8818芯片的hostapd版本,網上牛人已經把相關代碼放到github上,我們直接安裝就可以了。

爲了能正常爲8818芯片的wifi網卡安裝上hostapd,首先要卸載掉原先的hostapd

sudo apt-get autoremove hostapd

然後安裝8818芯片版本的hostapd

wget https://github.com/jenssegers/RTL8188-hostapd/archive/v2.0.tar.gztar -zxvf v2.0.tar.gz

然後編譯安裝

cd RTL8188-hostapd-2.0/hostapd sudo make

sudo make install


$ sudo service hostapd restart

[ ok ] Stopping advanced IEEE 802.11 management: hostapd.

[ ok ] Starting advanced IEEE 802.11 management: hostapd.

hostapd安裝完畢。

接下來安裝udhcpd

sudo apt-get install udhcpd

安裝完成後配置/etc/udhcpd.conf


start 192.168.20.20 # This is the range of IPs that the hostspot will give to client devices.
end 192.168.20.200
interface wlan0 # The device uDHCP listens on.
remaining yes
opt dns 8.8.8.8 4.2.2.2 # The DNS servers client devices will use.
opt subnet 255.255.255.0
opt router 192.168.20.1 # The Pi's IP address on wlan0 which we will set up shortly.
opt lease 864000 # 10 day DHCP lease time in seconds

接下來編輯/etc/default/udhcpd並且將下面這行註釋掉,以使DHCP Server正常工作:

#DHCPD_ENABLED="no"

爲了下次啓動仍然有效,我們需要配置/etc/network/interfaces文件:

sudo nano /etc/network/interfaces

註釋掉所有的關於無線網卡的部分,最後應該變成下面所示:

#wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
#iface default inet dhcp

注意保留allow-hotplug wlan0,英文原文是不保留的,但是我操作下來發現如果不保留這段的話,無線網卡有時無法正常配置IP,最後無線網卡IP的配置信息如下:

allow-hotplug wlan0
iface wlan0 inet static
  address 192.168.20.1
  netmask 255.255.255.0

編輯hostapd配置

sudo nano /etc/hostapd/hostapd.conf


啓動IP轉向功能以便於開通NAT

sudo sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"

net.ipv4.ip_forward=1

配置iptables防火牆

我們可以做個腳本名爲nat.sh,以便啓動的時候自動運行nat相關配置

#!/bin/sh
sudo iptables -t nat -A POSTROUTING -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 chmod +x nat.sh

編輯/etc/rc.local文件,使之開機時運行nat相關iptabls配置和啓動hostapd

sudo nano /etc/rc.local

在exit 0上面加上以下兩行後保存退出

sudo service hostapd start

sh /home/pi/nat.sh


再讓udhcpd也啓動時一起運行。

sudo update-rc.d udhcpd enable

所有的步驟結束後重啓Raspberry pi.

大功告成!


PS:這裏碰到了幾個小問題。

  1. 不知是問麼原因,原本打算用sudo update-rc.d hostapd enable使hostapd開機啓動的。但是會報錯無法開機啓動,後來決定在/etc/rc.local上加上sudo service hostapd start的方式解決。

  2. 關於iptables,原本打算用sudo sh -c "iptables-save > /etc/network/iptables",然後在/etc/network/interface上加上 up iptables-restore < /etc/network/iptables方式使nat相關配置生效的。但是不知什麼原因重啓Raspberry pi後一直不生效。也只能通過萬能的rc.local上加上sh /home/pi/nat.sh的方式解決。

後期打算加上自動加載USB存儲設備,通過媒體共享的方式給我的IPAD,iphone等共享文件,播放視頻等等。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章