IP linux route manipulation

From Teknologisk videncenter
Jump to: navigation, search

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

Showing the Route table

Example show below has nothing to do with example above.

heth@mars2:~$ ip route show table main
192.168.139.0/24 dev eth0  proto kernel  scope link  src 192.168.139.50
default via 192.168.139.1 dev eth0  metric 100
heth@mars2:~$ ip route show table 4
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.140.0   0.0.0.0         255.255.255.0   U     0      0        0 eth1
0.0.0.0         192.168.140.1   0.0.0.0             UG   100   0        0 eth1