IP linux route manipulation
From Teknologisk videncenter
Example
#!/bin/sh
#
#Enable Routing
echo "1" > /proc/sys/net/ipv4/ip_forward
#Flush Route table 4 and remove mark 4
ip route flush table 4
ip rule del fwmark 4 table 4
#Flush iptables Rules
iptables -F -t nat
iptables -F -t mangle
#Add static routes to route table 4
ip route add table 4 204.0.0.32/28 dev eth1 scope link
ip route add table 4 172.21.0.0/16 dev eth2 scope link
ip route add table 4 default via 204.0.0.33
ip route add table 4 172.22.0.0/16 dev eth2 via 172.21.0.2
#Mark packets coming from 172.21/16 and 172.22/16 with 4
iptables -t mangle -A PREROUTING -s 172.21.0.0/16 -d 0/0 -j MARK --set-mark 4
iptables -t mangle -A PREROUTING -s 172.22.0.0/16 -d 0/0 -j MARK --set-mark 4
#Add mark 4 to route table 4
ip rule add fwmark 4 table 4
#Source Nat trafix from 172.21/16 and 172.22/16 to 204.0.0.34 (Source address changed in packets)
iptables -t nat -A POSTROUTING -s 172.21.0.0/16 -d 0/0 -j SNAT --to 204.0.0.34
iptables -t nat -A POSTROUTING -s 172.22.0.0/16 -d 0/0 -j SNAT --to 204.0.0.34