Raspberry Pi 3 connecting and setting static IP addresses on multiple networks

So you got Wifi at home and a pocket mobile wifi dongle for remote access when you are traveling. You want Raspbery Pi 3 to know which network it is currently connecting to and assign a static IP accordingly.

Here is how.

  1. Edit /etc/wpa_supplicant/wpa_supplicant.conf, then ctrl+x y:
    $sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
    ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
    update_config=1
    network={
    ssid=”HomeWifi”
    psk=”password_for_home_wifi”
    }network={
    ssid=”PocketMobileWifi”
    psk=”password_for_mobile_wifi”
    }
  2. Create a new file /etc/dhcpcd.exit-hook, then ctrl+x y:
    $sudo nano /etc/dhcpcd.exit-hook

    # This script adds the desired static ip addresses as an alias based on the currently detected network. This compliements /etc/dhcpcd.conf
    aliasip=
    gw=
    if $if_up; then
    # Wireless alias
    case "$ifssid" in
    HomeWifi) aliasip="192.168.1.222/24";gw="192.168.1.1";;
    PocketMobileWifi) aliasip="192.168.0.222/24";gw="192.168.0.1";;
    esac
    if [ -n "$aliasip" ]; then
    echo "Adding alias of $aliasip to $interface"
    ip addr add "$aliasip" dev "$interface"
    ip route add "$aliasip" via "$gw"
    fi
    fi
  3. Save and reboot. We are done! Confused? Leave message below.
(Visited 2,273 times, 1 visits today)

4 thoughts on “Raspberry Pi 3 connecting and setting static IP addresses on multiple networks”

  1. i ch says:

    don’t you need to change the file ‘/etc/network/interfaces’?

  2. Gareth says:

    echoing the previous question re /etc/network/interfaces. I did above but I get no wireless interfaces found.

  3. John Caipa Roldan says:

    It doesn’t work

  4. Pradeep Prakash says:

    What if I keep the ssid also the same (I mean home network and hotspot network ssid are the same) since I know they are mutually exclusively available. Can I still achieve the above??

Comments are closed.