I have a machine hosted in datacenter with 3 network interfaces.

Interface  network         ip address

My default gateway is set to, where I can access some services provided by datacenter (repositories, ntp and so on).

Network has a gateway at through which I can access outside world, where dragons live. When I need to go out of my server I simply add a static route. I kind of like this setting as I know where my server is connecting.

Now, I have a mail client (exim4) which needs to send mails... to anyone. So ideally it needs to have a default gw set to Is there a way to route only traffic for this particular service or should I simply change my network configuration on the server?

I'm on debian 8 if that makes any difference.

1 Answer 1


You can set the firewall (iptables) to route to a specific gateway depending on one of 3 characteristics: destination port, source port or owner (may not work, see below)

First you will add a custom routing table for your special application (gateway, create a rule that redirect all packages with the mask 1 to this table, and create a iptables rule that masque the source address in case the package was redirected:

ip route add dev eth0 table 1
ip route add 0/0 via table 1
ip rule add fwmark 1 table 1
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source

For the package marking you have 3 options:

Redirect by destination port, charging PORT with the server port used by exim:

iptables -t mangle -A OUTPUT -p tcp --dport PORT -j MARK --set-mark 4

Redirect by source port, charging PORT with the port used locally by exim, if it does use only one source port:

iptables -t mangle -A OUTPUT -p tcp --sport PORT -j MARK --set-mark 4

Redirect by Owner, changing OWNER with the PID from the Exim process (see iptables -m owner --help for other options):

iptables -t mangle -A OUTPUT -m owner --pid-owner OWNER -j MARK --set-mark 4

Redirecting by Owner considerations www.frozentux.net:

The pid, sid and command matching is broken in SMP kernels since they use different process lists for each processor. It might be fixed in the future however

So depending on your kernel this feature is unavailable or broken (will not work properly)

  • The owner method is totally new for me. And i would use that if I had another kernel. I will see if I can use source port but I doubt it.
    – Kalavan
    Oct 18, 2016 at 12:44
  • I guess you can use the destination ports right? smtp will use just 25, 465, and 587 I think.
    – Segfault
    Apr 19, 2017 at 17:39
  • 1
    The number used in iptables --set-mark should be the same from ip rule fwmark, just a typo.
    – lgaggini
    Sep 10, 2019 at 9:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.