41

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.

Sopalajo de Arrierez
  • 6,603
  • 11
  • 63
  • 97
Alex
  • 1,135
  • 4
  • 12
  • 18

3 Answers3

41

You 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.

sebastian
  • 163
  • 8
Fox
  • 616
  • 6
  • 5
  • 5
    one correction (but not sure if your one will also work. for the second command: `ip route add default dev eth4 table ` (`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) – Alex Jan 12 '12 at 02:23
  • I had to issue these commands in reverse order: 1st `sudo ip route add default via dev table `, 2nd `sudo ip rule add from / lookup `. I think the 1st one creates the table and the 2nd adds a line to it, so the reverse order shouldn't work. – kol Aug 11 '22 at 09:38
11

http://wiki.wlug.org.nz/SourceBasedRouting

This site has a nice example of source based routing.

Marc Tamsky
  • 107
  • 3
daya
  • 2,571
  • 17
  • 19
  • 2
    Please quote the essential parts of the answer from the reference link(s), as the answer can become invalid if the linked page(s) change. – DavidPostill Nov 01 '20 at 08:23
0

Another great description how it works:

https://datahacker.blog/industry/technology-menu/networking/routes-and-rules/iproute-and-routing-tables

sredni
  • 101
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 23 '23 at 20:24