OpenWrt: route different computers via different upstreams based on their IP

Let's say you have two IPv4 upstreams: and is used as the default route, but you want some computers to be routed via, based on their LAN IP address.

Let's imagine for an example that you have two DHCP clients connected:

# cat /tmp/dhcp.leases 
1629000000 01:02:03:aa:bb:cc MacBook-Pro 01:01:02:03:aa:bb:cc
1629000000 01:02:03:dd:ee:ff MacBook-Air 01:01:02:03:dd:ee:ff

and you want to route MacBook-Air ( via the second upstream

Your main routing table looks like this:

# ip r
default via dev eth2  src dev br-lan scope link  src dev eth2 scope link  src dev eth3 scope link  src

Add new routing table:

# echo "100 mytable" >> /etc/iproute2/rt_tables

Define new IP set:

# ipset create myset hash:net

Fill it with LAN IPs of computers you want to route via the second upstream:

# ipset add myset

Add iptables rules to mark packets coming from those IPs. Add it to /etc/firewall.user, then restart firewall.

iptables -t mangle -A PREROUTING -m set --match-set myset src -j MARK --set-mark 0x64

Add routing rule matching the fwmark:

# ip rule add fwmark 0x64 table mytable

Set default route in table mytable:

# ip route add default via table mytable

You may also want to add route for LAN:

# ip route add via table mytable

Basically that's it, now packets coming from will be routed through

To make these changes persistent, use /etc/rc.local script (executed at boot) and /etc/hotplug.d hooks.

If you have any comments, contact me by email.