TUTORIAL / SCRIPT: How to share Internet connection with WiFi hotspot

Here’s my take, this is a slightly different approach, this hooks into NetworkManager’s dispatcher and will get called every time there is a network interface state change. This means that this script will automatically run any time the WiFi hotspot is enabled or disabled.

This is just a quick and dirty test with very little sanity or error checking. I’ve given it a quick run through and it seems to work in it’s rather crude state. I’m quite limited on testing capability tho as the WiFi performance on my phone is quite poor and suffers from stability issues. The IP regex is quite lose and I haven’t bothered to check/trap if there is actually an IPv4 network to route to among other areas that could be improved.

I called the file “50-shared-masquerade” to install the script you have to set permissions to 755…

chmod 755 50-shared-masquerade

Then set ownership to root…

sudo chown root:root 50-shared-masquerade

And finally move into NetworkManager’s dispatcher directory…

sudo mv 50-shared-masquerade /etc/NetworkManager/dispatcher.d/

Then any time you enable or disable the hotspot the masquarade rules should automatically be set and removed as required.

Maybe some of this will be helpful to you, here’s the script…

EDIT: The script has been updated to handle any type of connection share, hotspot, shared via Ethernet etc., Multiple shared connections can be active simultaneously, enabling/disabling one connection will not interfere or disturb any others.

#!/bin/bash

STATUS=$2
CONNID=${CONNECTION_UUID}

[[ -z $(nmcli -t c s ${CONNID} | grep ipv4.method:shared) ]] && exit 0

NETWORKADDR=$(nmcli -t c s ${CONNID} | grep ipv4.addresses: | \
              awk -F ":" '{print $2}')

: ${NETWORKADDR:=10.42.0.0/24}

case ${STATUS} in
    up)
      iptables-legacy -t nat -A POSTROUTING -s ${NETWORKADDR} \
                           ! -d ${NETWORKADDR} -j MASQUERADE
      ;;

    down)
      for ACTCONN in $(nmcli -t -f STATE,UUID c s | grep ^activ \
                     | awk -F ":" '{print $2}')
      do
        [[ ! -z $(nmcli -t c s ${ACTCONN} \
                | grep ipv4.method:shared) ]] \
               && SHR=1
      done

      [[ -z ${SHR} ]] && sysctl net.ipv4.ip_forward=0

      iptables-legacy -t nat -D POSTROUTING -s ${NETWORKADDR} \
                           ! -d ${NETWORKADDR} -j MASQUERADE
      ;;
esac

exit 0

3 Likes