How to route only specific subnet (source ip) to a particular interface?
OS: Linux
I know I can do easily by destination IP by using something like
route add 1.2.3.4/24 dev eth4
but I do not see how can route based on source IP.
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Sign up to join this communityYou need to use policy based routing. Something kind of like
ip rule add from <source>/<mask> table <name>
ip route add 1.2.3.4/24 via <router> dev eth4 table <name>
<name>
is either table name specified in /etc/iproute2/rt_tables
or you can use numeric id ...
This pretty much says, that all traffic from 1.2.3.4/24
will be routed using routing table <name>
. IIRC it doesen't use the default table after going through this, so if you need other routes (ie. default gateway), you need to add them to the table as well.
ip route add default dev eth4 table <name>
(table
directive should go at the end I think, just like in the first command... also default
can be replaced by a subnet, just like in your example)
sudo ip route add default via <router-addr> dev <device-name> table <table-id>
, 2nd sudo ip rule add from <source-addr>/<mask> lookup <table-id>
. I think the 1st one creates the table and the 2nd adds a line to it, so the reverse order shouldn't work.
http://wiki.wlug.org.nz/SourceBasedRouting
This site has a nice example of source based routing.
Another great description how it works: