Setting up NAT and MASQUERADE for sharing USB Tether connection over LAN

· Read in about 2 min · (342 words) ·

I the only source of Internet connection I have currently is my phone. I wanted to share this network with other systems, via a lan/wireless router. So here is a basic setup:

  • Android Phone with USB Tethering
  • Laptop ( Fedora 18 )
  • Wireless Router with Lan
  • A desktop machine ( Fedora 17 )

Setting up Internet gateway: Laptop + Android Phone

I connected Android Phone via USB cable to the laptop and enabled USB thether, so I have a usb device /dev/usb0. This was automatically detected by Network Manager. Also I connected Laptop to the router via a LAN.

I setup the NAT on my Laptop using this script as follows:

# cat nat.sh
IFOUT=usb0
IFLAN=em1
echo 1 > /proc/sys/net/ipv4/ip_forward &&
sudo iptables -t nat -A POSTROUTING -o $IFOUT -j MASQUERADE &&
sudo iptables -A FORWARD -i $IFOUT -o $IFLAN -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT &&
sudo iptables -A FORWARD -i $IFLAN -o $IFOUT -j ACCEPT

So all I had to do to setup is do this:

# sh nat.sh

And IPTABLES take care of masquerading the IP addresses to-and-fro from local network to the internet. I received IP address 192.168.1.2 for the Laptop, which becomes a default gateway for rest of the machines connected to the router.

Setting up Internet user: Desktop machine

Now on the desktop machine ( with IP address 192.168.1.3 ), I only had to setup the routes and DNS server:

# route add default gw 192.168.1.2
# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.1.2     0.0.0.0         UG    0      0        0 em1
0.0.0.0         192.168.1.1     0.0.0.0         UG    0      0        0 em1
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 em1

# cat /etc/resolv.conf 
# Generated by NetworkManager
#nameserver 192.168.1.3
nameserver 208.67.222.222
nameserver 208.67.220.220
nameserver 192.168.42.129

Thats all, that was needed. I had done the NAT + MASQUERADE setup earlier, however it was on Fedora Core 2 and some commands didn’t match up, esp. how to use conntrack module.

References: