fi
done
+# generate list of available default gateways
+gwsline=$(/sbin/ip route | awk '/default/ { print $3 }')
+gateways=($gwsline)
+
+# select a gateway on the same subnet
+selectgw() {
+ for gw in "${gateways[@]}"; do
+ if [[ "$(netcalc "${1}" "${2}")" == "$(netcalc "${gw}" "${2}")" ]]; then
+ echo $gw
+ return
+ fi
+ done
+ echo "0.0.0.0"
+}
+
# add the routing entries and rules
for i in "${interfaces[@]}"
do
cidrmask=($(/sbin/ip -o -4 addr list $i 2>&- | awk '{print $4}' | cut -d/ -f2))
# convert cidr mask to mask in dot format
dotmask=$(cidr2mask ${cidrmask[0]})
- # apply mask to ip addr
- net=$(netcalc ${addr[0]} $dotmask)
+ # find a gateway on the same subnet
+ gw=$(selectgw ${addr[0]} $dotmask)
# build and execute route commands
- routecmd=(/sbin/ip route add ${net}/${cidrmask[0]} dev ${i} proto kernel scope link src ${addr[0]} table ${i})
+ if [[ $gw == "0.0.0.0" ]]; then
+ # gateway not found, assume local destinations
+ net=$(netcalc ${addr[0]} $dotmask)
+ routecmd=(/sbin/ip route add ${net}/${cidrmask[0]} dev ${i} proto kernel scope link src ${addr[0]} table ${i})
+ else
+ routecmd=(/sbin/ip route add default via ${gw} dev ${i} table ${i})
+ fi
ruledelcmd=(/sbin/ip rule del from ${addr[0]} table ${i} '&>/dev/null')
ruleaddcmd=(/sbin/ip rule add from ${addr[0]} table ${i})
eval ${routecmd[@]}