I have several gateways and would like to route some traffic out of different gateways based on its destination. I'm guessing I'd need to use a combination of iproute2 and iptables rules, but am not sure where to start.
Can someone provide an example?
You can probably do what you want with ip route
:
ip route add 8.8.8.8 via 10.0.0.1 dev enp3s8
ip route add 10.0.0.0/24 dev eth0
The first ip route add
shows a single IP address, sent out a given ethernet interface (ep3s8) to the next hop router, 10.0.0.1
The second route is for a whole network, 10.x.y.z, sent out a given ethernet card, eth0. That's the "local network", which doesn't have a next hop router, it's all on the same logical wire.
You want to read man ip-route
before doing anything, though. Also, be prepared to have to reboot, and do not do this remotely. You can very easily create incorrect routes that terminate your remote access. I am the voice of experience in this last recommendation.
What you are asking about is policy-based routing
or source-based routing
. There is an excellent introduction by David Schwartz on this very same site.
I would like to point out that there is also a neat little program, which you cn find here, that allows you to bind specific applications to a given interface. This is of course easy with apps like openssh which have options to bind to the desired listening address. But this library allows you to bind even applications without such options (like Firefox) to a given IP address.
In this way, you can choose whether you wish to provide separate routing tables for all applications, or override those same specifications on a per-application basis.
-
You don't need policy routing if you want to route by destination. – Diego Woitasen Nov 18 '13 at 12:02
-
Hi, that is also a good point, hmm, that will allow greater flexibility which is probably more advanced than I want to be at this point. Definitely something to learn though. – Walter Nov 21 '13 at 1:47
good place to read about source base routing is Linux Advanced Routing & Traffic Control
you also can read manuals
man ip rule
man ip route
In general, you should add the rule (I added interface eth1 just for demonstration purposes, it can be omited)
#ip rule add dev eth1 to 170.10.0.10 table 2 priority 20000
here are:
dev eth1 - device which will be used to send packets
to 170.10.0.10 - the destination
table 2 - table where you should ass your routes
priority 20000 - priority of rule
you can see your rule by
#ip ru sh
0: from all lookup local
20000: from all to 170.10.0.10 iif eth1 lookup 2
32766: from all lookup main
32767: from all lookup default
Next, you should add the routes in usual way, but you should specify the table (table 2), where you would put the route
#ip route add table 2 via 170.10.0.1 default
to see your routes, you should run
#ip route show ta 2