用CubieBoard玩转网络共享

将CubieBoard或Raspberry Pi架成Wireless Access Point的办法网上已有很多,但和我的需求正好相反,我是打算让连在CubieBoard的ethernet上的内部子网络可以共享CubieBoard的无线网络端的internet联接,即AP Client方式。

AP client的实现并不复杂,通过dhcpd及NAT即可做到。

第一步:设置有线网口(eth0)为固定ip

~# cat /etc/network/interfaces
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address 192.168.0.1
netmask 255.255.255.0

第二步:安装并配置dhcpd服务

~# apt-get install isc-dhcp-server

添加dhcp网段地址:

~# cat /etc/dhcp.dhcpd.conf
……
subnet 192.168.0.0 netmask 255.255.255.0
{
    range 192.168.0.50 192.168.0.250;
    option routers 192.168.0.1;
    option domain-name-servers 8.8.8.8,4.2.2.2;
}

限定dhcp服务运行于连接在eth0上的子网:

~# vi /etc/default/isc-dhcp-server
……
INTERFACES="eth0"

启动dhcpd服务:

~# service isc-dhcp-server restart
isc-dhcp-server stop/waiting
isc-dhcp-server start/running, process 23686

~# ps -efa | grep dhcpd
root     23686     1  0 15:45 ?        00:00:00 dhcpd -user dhcpd -group dhcpd -f -q -4 -pf /run/dhcp-server/dhcpd.pid -cf /etc/dhcp/dhcpd.conf eth0

此时dhcpd服务架设成功,连在网口eth0子网上的电脑客户端可以自动获取到ip了。

第三步:设置无线上线

用实际的ssid及password替换下面的命令:

~# wpa_passphrase ssid password >> wpa.conf
~# cat wpa.conf
network={
        ssid="ssid"
        #psk="password"
        psk=44116ea881531996d8a23af58b376d70f196057429c258f529577a26e727ec1b
}

连接无线网络:

~# wpa_supplicant -iwlan0 -B -Dwext -c ./wpa.conf
~# dhclient wlan0
~# ifconfig wlan0

wlan0     Link encap:Ethernet  HWaddr 14:xx:xx:xx:xx:xx
          inet addr:10.0.3.93  Bcast:10.0.3.255  Mask:255.255.255.0
          inet6 addr: fe80::16cf:92ff:fe1b:34ef/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:240 errors:0 dropped:0 overruns:0 frame:0
          TX packets:497 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2299089 (2.2 MB)  TX bytes:1124901 (1.1 MB)
~# ping www.google.com
PING www.google.com (74.125.128.99) 56(84) bytes of data.
64 bytes from hg-in-f99.1e100.net (74.125.128.99): icmp_req=1 ttl=46 time=69.2 ms
64 bytes from hg-in-f99.1e100.net (74.125.128.99): icmp_req=2 ttl=46 time=59.4 ms
^C

第四步:设置网络转发及NAT

编辑/etc/sysctl.conf启用ip forward:

~# cat /etc/sysctl.conf

net.ipv4.ip_forward=1

使ip forward更改生效:

~# sysctl –p

设置NAT转发:

~# iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE

设置好NAT后,子网客户端就可以上网了。

注1:dhcpd server可以用udhcpd来替代
注2:无线网络的设置也可以通过/etc/network/interfaces来做
注3:ip forward的设置(/etc/sysctl.conf方式)重启仍然有效
注4:有关iptables的设置及防火墙配置请参阅相关资料