Skip to content

Instantly share code, notes, and snippets.

@sfan5
Created April 8, 2016 17:24
Show Gist options
  • Save sfan5/e5506d9ece03dcc77cc95ffc5fb0642e to your computer and use it in GitHub Desktop.
Save sfan5/e5506d9ece03dcc77cc95ffc5fb0642e to your computer and use it in GitHub Desktop.
Support multiple gateways on one machine
#!/bin/bash -e
IFACE=wlp0s18f2u1
TBLN=10
# TBLN needs to be different for each interface
IPADDR=`ip addr show dev $IFACE | grep "inet " | awk '{print $2}' | cut -d '/' -f1`
IPSUBNET=`ip route show | grep "dev $IFACE" | grep "src $IPADDR" | awk '{print $1}'`
IPGATEWAY=`ip route | grep "default via" | grep "dev $IFACE" | awk '{print $3}'`
if [ "x$IPGATEWAY" = "x" ]; then
echo "Nothing to do."
exit 0
fi
# Create seperate route table with default route via $IPGATEWAY
if [ `ip route show table $TBLN | wc -l` -eq 0 ]; then
ip route add default via $IPGATEWAY dev $IFACE table $TBLN
ip route add $IPSUBNET dev $IFACE src $IPADDR table $TBLN
fi
# Use said route table for traffic to/from $IPADDR
if [ `ip rule list | grep "lookup $TBLN" | wc -l` -eq 0 ]; then
ip rule add from $IPADDR table $TBLN
ip rule add to $IPADDR table $TBLN
fi
# Delete unused default route via $IPGATEWAY
if [ `ip route show | grep "default via $IPGATEWAY" | wc -l` -gt 0 ]; then
ip route del default via $IPGATEWAY dev $IFACE
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment