WIFI AP模式通过LAN网线上网

一、配置内核,支持iptables、forward和nat

 

 

 

 

 二、交叉编译iptables

a.源码下载:

ftp://ftp.netfilter.org/pub/iptables/

b.交叉编译iptables

tar -xvf iptables-1.8.4.tar.bz2
cd iptables-1.8.4
mkdir build
./configure --prefix=$PWD/build --host=arm-linux

这时报如下错误:

checking for libmnl... no
*** Error: No suitable libmnl found. ***
    Please install the 'libmnl' package
    Or consider --disable-nftables to skip
    iptables-compat over nftables support.

加上--disable-nftables重新配置:

./configure --prefix=$PWD/build --host=arm-linux --disable-nftables

配置成功,执行make进行编译,编译完成后执行make install进行安装,会安装在build目录下。

root@machine:~/wifi/iptables-1.8.4# ls build
bin  include  lib  sbin  share

把build/lib build/sbin build/bin目录里的内容全部拷贝到开发板的/usr/lib /usr/sbin/ /usr/bin目录下,这里需要注意的是拷贝的时候使用“cp -rf”,连同软链接也一起拷贝。

三、测试

a. 启用内核转发

echo "net.ipv4.ip_forward = 1" > /etc/sysctl.conf  #如果开发板文件系统本身不存在/etc/sysctl.conf文件,使用'>',否则使用'>>'(添加到文件尾)。
sysctl -p

或者

echo "1" > /proc/sys/net/ipv4/ip_forward 

 

b.开发板上执行配置 iptables

iptables -F
iptables -t nat -F
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE

这时报如下错误:

/root # iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables v1.8.4 (legacy): Couldn't load target `MASQUERADE':No such file or directory

Try `iptables -h' or 'iptables --help' for more information.

解决办法:

export XTABLES_LIBDIR=/usr/lib/xtables:$XTABLES_LIBDIR

然后就可以成功执行“iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE”了,这时连接到热点的设备即可通过eth0去访问互联网了。

eth0可以设置静态IP地址也可以使用dhclient动态获取IP地址,建议使用dhclient动态获取,dhclient会自动配置好网关和DNS。

手动设置静态IP的话需要自己去配置网关和DNS,方法如下:

ifconfig eth0 192.168.0.102 #路由器的LAN口IP为192.168.0.1这里需要和路由器LAN口在同一个网段
route add default gw 192.168.0.1 dev eth0 #设置eth0网关

修改/etc/resolv.conf添加DNS:

nameserver 192.168.0.1  #192.168.0.1是路由器的LAN口IP地址
nameserver 8.8.8.8 #google域名服务器 
nameserver 8.8.4.4 #google域名服务器

设置完成后可以查看一下网关是否设置正确:

route -n

或者

netstat -r

 四、写一个脚本开机自动执行

#! /bin/sh
export XTABLES_LIBDIR=/usr/lib/xtables:$XTABLES_LIBDIR
hostapd -B /etc/myhostapd.conf
ifconfig wlan0 192.168.3.1
dhcpd -cf /etc/dhcpd.conf wlan0
echo "1" > /proc/sys/net/ipv4/ip_forward
#echo "net.ipv4.ip_forward = 1" > /etc/sysctl.conf
#sysctl -p
iptables -F
iptables -t nat -F
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

 

posted @ 2020-05-17 23:46  闹闹爸爸  阅读(1194)  评论(0编辑  收藏  举报