Enable Network Address Translation (NAT) on Linux

Enabling Network Address Translation on Linux is pretty simple. I use it to enable my local network to use a Mobile Broadband stick connected to an old laptop, but this will work for any interface, not just for Mobile Broadband.

Enabling Network Address Translation on Linux is pretty simple. I use it to enable my local network to use a Mobile Broadband stick connected to an old laptop, but this will work for any interface, not just for Mobile Broadband.

What I have is a simple bash script stored in root’s home directory. Then when I first connect to the net I run this script (as root) which configures NAT and the rest of the network can then access the net.

Note: The script only needs to be run once per reboot, and the net connection needs to be up when it’s run. However if the net connection is restarted, as long as the machine has not been rebooted, the Linux kernel keeps the settings.

Here’s the script:

#!/bin/bash
INT=hso0
NET=192.168.2.0/24

iptables -t nat -A POSTROUTING -s $NET -o $INT -j MASQUERADE
iptables -A FORWARD -s $NET -o $INT -j ACCEPT
iptables -A FORWARD -d $NET -m state --state ESTABLISHED,RELATED -i $INT -j ACCEPT
echo 1 >/proc/sys/net/ipv4/ip_forward

echo "Network $NET is now natted over $INT"

For this to work on your local machine, you simply need to edit the first two lines:

  • INT= the network interface to run Network Address Translation. hso0 here is for the Option modem I’m using on this specific laptop, but it could easily be ppp0 etc.
  • NET= the local network you want to allow access to the NAT.

If you don’t know what to use for INT, simply run ifconfig both before and after you connect to the net using your broadband, and the additional interface is more than likely the port to use.

Author: petermount1

Prolific Open Source developer who also works in the online gaming industry during the day. Develops in Java, Go, Python & any other language as necessary. Still develops on retro machines like BBC Micro & Amiga A1200

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: