Share an internet connection: A nice little script for quickly getting the task done.

This script uses iptable forwarding and dnsmasq to share an internet connection with full relay of remote DNS servers and a local DHCP server. Before trying the script, here is the over all steps:

  • You connect to the internet in your normal fashion. For instance with a 3G dongle and your network manager applet.

  • Make sure that nothing is running on port 53, run netstat -tlnp to debug

  • READ THE SCRIPT before starting and know which interfaces you are using. EXTERNAL is the one connected to the internet and INTERNAL is the one you are sharing the connection via.

  • Do not let network-manager mange the INTERNAL interface!

  • You might have to adjust the script, especially the iwconfig part, as different interfaces may have different ways of configuring the WEP key

    !/bin/bash

    if [ ! whoami = "root" ]
    then
    echo "Only root"
    exit
    fi

    DHCP='yes'
    EXTERNAL=ppp0
    INTERNAL=wlan0
    INTERNAL_HOST_IP='192.168.10.1'
    SHARE_TO_WLAN='yes'
    WEPKEY=abe1234567
    SSID='mynetwork'
    DNSMASQ_CONFIG='dhcp-range=192.168.10.20,192.168.10.255,12h'
    DNSMASQ_CONFIG_FILE='/etc/dnsmasq.d/shareconnection'

    if [[ $DHCP -eq 'yes' ]]
    then

    DHCP SERVER (enable below lines)

    apt-get install dnsmasq  
    echo $DNSMASQ_CONFIG > $DNSMASQ_CONFIG_FILE  
        echo "listen-address=192.168.10.1" >> $DNSMASQ_CONFIG_FILE  
        echo interface=$INTERNAL >> $DNSMASQ_CONFIG_FILE  
    /etc/init.d/dnsmasq stop
    

    fi

    echo 1 > /proc/sys/net/ipv4/ip_forward
    /sbin/iptables -t nat -A POSTROUTING -o $EXTERNAL -j MASQUERADE
    /sbin/iptables -A FORWARD -i $EXTERNAL -o $INTERNAL -m state --state RELATED,ESTABLISHED -j ACCEPT
    /sbin/iptables -A FORWARD -i $INTERNAL -o $EXTERNAL -j ACCEPT

    ifconfig $INTERNAL down
    ifconfig $INTERNAL $INTERNAL_HOST_IP
    iwconfig wlan0 mode ad-hoc
    iwconfig wlan0 essid $SSID
    iwconfig wlan0 key $WEPKEY
    ifconfig $INTERNAL up

    if [[ $DHCP -eq 'yes' ]]
    then
    /etc/init.d/dnsmasq start
    fi