Tethering技术在移动平台上已经运用的越来越广泛了,它可以把移动设备当做一个接入点,其它的设备可以通过Wi-Fi,USB或是Bluetooth等方式连接到此移动设备。
最近在Telechips的TCC8900开发板上调试网络设备,需要在Linux下实现简单的Tethering,通过Wi-Fi的Ad-hoc 模式,将网络连接共享给其它设备。开发板上一个有线网卡(eth1),一个无线网卡(eth0),eth1连接到外网,eth0作为AP共享给另一台装了无线网卡的PC,使得PC可以通过开发板连接到外网。(内网的ip地址为192.168.0.*)
分析下来需要实现以下几个简单的功能:
1. Wi-Fi的Master或Ad-hoc模式配置
2. NAT
3. DHCP服务器
Wi-Fi模式设置
随开发板提供的是AR6102,一个SDIO接口的Wi-Fi,从硬件说明上看,这个Wi-Fi只支持Ad-hoc的点对点的模式,而无法支持AP,因此使用iwconfig将它设置成Ad-hoc模式
1 | iwconfig eth0 mode ad-hoc |
2 | iwconfig eth0 enc s:12345 |
3 | iwconfig eth0 essid "tcc8900" |
5 | ifconfig eth0 192.168.0.1 |
NAT使用iptables实现
iptables可以实现地址翻译,防火墙,端口过滤等功能,这里只用到了最基本的地址翻译,使得PC可以访问外网
1 | iptables -t nat -A POSTROUTING -o eth1 -s 192.168.0.0/24 -j MASQUERADE |
2 | echo "1" > /proc/sys/net/ipv4/ip_forward |
DHCP服务使用udhcpd搭建
需要新建一个配置文件,默认为/etc/udhcpd.conf,另外需要一个lease(租约)的记录文件,默认为/etc/udhcpd.leases,可以用dumpleases命令来查看已连接的客户端的租约情况。
1 | touch /etc/udhcpd.leases |
2 | udhcpd -S /etc/udhcpd.conf |
提供一个udhcpd.conf的例子。
01 | # Sample udhcpd configuration file (/etc/udhcpd.conf) |
02 | # The start and end of the IP lease block |
06 | # The interface that udhcpd will use |
07 | interface eth0 #default: eth0 |
09 | # The maximim number of leases (includes addressesd reserved |
10 | # by OFFER's, DECLINE's, and ARP conficts |
11 | max_leases 20 #default: 254 |
13 | # If remaining is true (default), udhcpd will store the time |
14 | # remaining for each lease in the udhcpd leases file. This is |
15 | # for embedded systems that cannot keep time between reboots. |
16 | # If you set remaining to no, the absolute time that the lease |
17 | # expires at will be stored in the dhcpd.leases file. |
18 | remaining yes #default: yes |
20 | # The time period at which udhcpd will write out a dhcpd.leases |
21 | # file. If this is 0, udhcpd will never automatically write a |
22 | # lease file. (specified in seconds) |
23 | auto_time 7200 #default: 7200 (2 hours) |
25 | # The amount of time that an IP will be reserved (leased) for if a |
26 | # DHCP decline message is received (seconds). |
27 | decline_time 3600 #default: 3600 (1 hour) |
29 | # The amount of time that an IP will be reserved (leased) for if an |
30 | # ARP conflct occurs. (seconds) |
31 | conflict_time 3600 #default: 3600 (1 hour) |
33 | # How long an offered address is reserved (leased) in seconds |
34 | offer_time 60 #default: 60 (1 minute) |
36 | # If a lease to be given is below this value, the full lease time is |
37 | # instead used (seconds). |
38 | min_lease 60 #defult: 60 |
40 | # The location of the leases file |
41 | lease_file /etc/udhcpd.leases |
43 | # The remainer of options are DHCP options and can be specifed with the |
44 | # keyword 'opt' or 'option'. If an option can take multiple items, such |
45 | # as the dns option, they can be listed on the same line, or multiple |
46 | # lines. The only option with a default is 'lease'. |
49 | opt dns 8.8.8.8 8.8.8.4 |
50 | option subnet 255.255.255.0 |