2011/05/02

Android Reverse USB Tethering with NAT

Environment: Android:CyanogenMod 6.1.1, PC:Ubuntu 10.10

It might be inconvenient when using reverse usb tethering with bridged network.

I must be execute the script that deletes a bridge interface when I stop tethering.
Without doing that, the network transfer in PC stops.

So I tried tethering with NAT that doesn't stop the network transfer in PC.
I came to be able to disconnect USB cable anytime without iconvenient effect in PC.

Firstly, enable IP forwarding in my PC.

/etc/sysctl.conf:

net.ipv4.ip_forward=1



To apply, execute 'sysctl -p'.
If you want to change the perameter temporarlily without editing sysctl.conf,
execute 'sysctl -w net.ipv4.ip_forward=1'.

Next, configure iptables.

iptables -A INPUT -j ACCEPT
iptables -A OUTPUT -j ACCEPT
iptables -A FORWARD -i usb0 -j ACCEPT
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE



To enable auto setting of iptables in Ubuntu, you must write a script to apply your settings.
I use following script in /etc/rc.local.

/etc/rc.local:

#!/bin/sh -e
/sbin/iptables-restore < /etc/iptables-rusbnat.rules



iptables-rusbnat.rules are created by 'iptables-save > iptables-rusbnat.rules'.


You have to do the work above only once.

You have to do following works whenever enabling reverse tethering.
Enable 'USB Tethering' in android. Execute rusbtether-nat in PC.

rusbtether-nat:

#!/bin/sh 
set -e
export LANG=C
ROUTE=/system/bin/route
GWA=`LANG=C ifconfig usb0 | grep "inet addr:" | \
    sed 's/ *inet addr:\([0-9\.]\+\).*$/\1/'`

ping -I usb0 -c 1 $GWA > /dev/null
# add route
adb shell su -c "$ROUTE add default gw $GWA dev usb0"

DNS=`grep nameserver /etc/resolv.conf | head -n1 | awk '{print$2}'`

# clear dns
for p in net.dns1 net.dns2 net.dns3 net.rmnet0.dns1 \
    net.rmnet0.dns2 dhcp.eth0.dns1 dhcp.eth0.dns2 \
    dhcp.eth0.dns3 dhcp.eth0.dns4 net.eth0.dns1 \
    net.eth0.dns2 net.usb0.dns1 net.usb0.dns2; do
    adb shell su -c "setprop $p ''"
done

# set dns
adb shell su -c "setprop net.dns1 $DNS"

echo Completed



To stop reverse tethering, just disconnect USB cable or disable 'USB Tethering' in android.
You have nothing to do in PC.

You should not to enable WiFi/3G while using reverse tethering.
Because dns settings in android are changed when enabling WiFi/3G and dns client will be not able to resolve names.
If you enable WiFi/3G while reverse tethering, execute rusbtether-nat again to fix dns settings.

0 件のコメント:

コメントを投稿