Ham Radio

Internet Sharing Script

From George Smart's Wiki

Jump to: navigation, search

I wrote a script for Linux to allow the sharing of internet. This was used in my university flat, where I had internet supplied by wireless (wlan0) and needed to share it over wired ethernet (eth0). The script below does this:

The Script

This script should allow you to bridge internet connections as outlined above. You can download it from here.

#!/bin/bash
# Internet Sharing Script 
# George Smart, M1GEO - Nov 2009
echo "IPv4 Port Forwarding Script"
echo "George Smart, M1GEO"

if [ $# -ne 3 ]; then
	echo "Usage:	$0 <source device> <output device> <output ip address>"
	echo "eg:	$0 wlan0 eth0 10.0.0.1"
	echo "		bridges wireless to wired"
	exit -1
else
	INPUT="$1"
	OUTPUT="$2"
	NETADD="$3"
	echo "Source:	$INPUT"
	echo "Output:	$OUTPUT"
	echo "IP Add:	$NETADD"

	# DO IT!
	sudo ifconfig eth0 $NETADD up
	sudo iptables -A FORWARD -i $INPUT -o $OUTPUT -s $NETADD/24 -m conntrack --ctstate NEW -j ACCEPT
	sudo iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
	sudo iptables -A POSTROUTING -t nat -j MASQUERADE
	sudo sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"
	sudo sysctl net.ipv4.conf.default.forwarding=1 2>&1 > /dev/null
	sudo sysctl net.ipv4.conf.all.forwarding=1 2>&1 > /dev/null

	echo "Done..."
fi

Usage

To use the script, you call it from the command line and give the three command-line arguments:

user@box ~$  ./internet-share.sh wlan0 eth0 10.0.0.1
  • Source Device, e.g. wlan0
  • Destination Device, e.g. eth0
  • Output IP Address, e.g. 10.0.0.1


The source device needs to be the device where the internet is accessible. In the above example, it is the wireless adapter wlan0. This then bridges wlan0 to the ethernet card at eth0, and opens eth0 with the IP-address entered, 10.0.0.1. Devices connecting via the ethernet port should be able to set the default gateway to 10.0.0.1. You will need to manually configure the client device, as this script does not setup DHCP. I suggest using a client IP of 10.0.0.2 and using the DNS server 8.8.8.8 [1].