Android系统中iptables的应用(三)NatController

个人邮箱:[email protected]  欢迎大家直接发邮件给我共同交流学习

      NatController这个模块支持android系统中网络共享功能,也可以勉强代称为网络地址转换(NAT:Network Address Translation),即在不同的网络接口设备之间搭建数据通路,互为上载出口,通过网络地址转换来实现数据包内部代理转发。例如,手机做无线热点hotspot,数据流量给其他通过wifi链接到本机的设备。从framework下发的可用Netdcmd只有一个:

 nat

 enable/disable

(1)Netd.CommanderListener初始化后:
createChildChains(V4V6, "filter", "FORWARD", FILTER_FORWARD);                                                                   
createChildChains(V4, "mangle", "FORWARD", MANGLE_FORWARD);
createChildChains(V4, "nat", "POSTROUTING", NAT_POSTROUTING);
sNatCtrl->setupIptablesHooks(); 
nat表新增规则:
  -N natctrl_nat_POSTROUTING
  -A POSTROUTING -j natctrl_nat_POSTROUTING

filter表:
  -N natctrl_FORWARD
  -N natctrl_tether_counters
  -A FORWARD -j natctrl_FORWARD
  -A natctrl_FORWARD -j DROP


mangle表:
  -N natctrl_mangle_FORWARD
  -A FORWARD -j natctrl_mangle_FORWARD
  -A natctrl_mangle_FORWARD -p tcp -m tcp --tcp-flags SYN SYN -j TCPMSS –clamp-mss-to-pmtu

    重要的是最后一条规则,这条规则的意义是,使TCP的SYN包中的MSS字段,根据upstream的MTU自动调整,相互兼容,避免downstream的数据包因超过通路upstream的MTU而无法通过。关于MSS的计算,通常ipv4协议MSS=MTU减40(IP数据包包头20字节和TCP数据包头20字节)。

(2)开启设备的某一种数据共享后:本例中开启mtk的hotspot共享,iniface=ap0,extiface=ccmni1
    sNatCtrl->enableNat( [intiface] , [extiface] );
nat表新增规则:
  -A natctrl_nat_POSTROUTING -o ccmni1 -j MASQUERADE
使出口为ccmni1的数据包,按照ccmni1网络接口设备的当前ip进行自动进行dst address的nat

filter表新增规则:
  -A natctrl_FORWARD -i ccmni1 -o ap0 -m state --state RELATED,ESTABLISHED -g natctrl_tether_counters
  -A natctrl_FORWARD -i ap0 -o ccmni1 -m state --state INVALID -j DROP
  -A natctrl_FORWARD -i ap0 -o ccmni1 -g natctrl_tether_counters
  -A natctrl_tether_counters -i ap0 -o ccmni1 -j RETURN
  -A natctrl_tether_counters -i ccmni1 -o ap0 -j RETURN
在ap0与ccmni1之间建立一条nat通道,保证有效数据能够成功通过iface转发。

(3)关于jump target MASQUERADE的man手册
MASQUERADE
       This target is only valid in the nat table, in the POSTROUTING chain.  It should only be used with dynamically  assigned  IP (dialup) connections: if you have a static IP address, you should use the SNAT target.
       Masquerading is equivalent to specifying a mapping to the IP address of the interface the packet is  going out,  but  also  has  the effect that connections are forgotten when the interface goes down.  This is the correct behavior when the next dialup is unlikely to have the same interface address (and hence any established connections are lost anyway).

       --to-ports port[-port]

              This  specifies  a  range of source ports to use, overriding the default SNAT source port-selection heuristics (see above).  This is only valid if the rule also specifies -p tcp or -p udp.

       --random

              Randomize source port mapping If option --random is used then port mapping will be randomized (ker‐nel >= 2.6.21).

你可能感兴趣的:(Android网络,Android,Netd,Android,Netd,network,Android,Netd)