There's no way to do this with 192.168.1.1 and 192.168.1.2 on the gateway's same network interface, thus resolving to the same MAC address. It's not a feature not implemented in iptables that could be implemented, it's a feature that cannot be implemented because of how IP networking works.
A client using 192.168.1.1 or 192.168.1.2 as gateway will never send a single IPv4 packet with 192.168.1.1 or 192.168.1.2 in it when emitting packets to Internet. It will:
- consult its routing table for a given destination
- find that there is a gateway for this destination
- Use ARP or a cached entry to resolve the L2 address (Ethernet MAC address) needed to reach the gateway.
The last step will have only one Ethernet destination: the gateway's NIC unique MAC address: the same for a client with gateway 192.168.1.1 or an other client with gateway 192.168.1.2.
So each client will now send a packet to the gateway with their IPv4 source address, the intended IPv4 destination in an Ethernet frame having the same destination Ethernet MAC address in both cases. 192.168.1.1/192.168.1.2 is out of the loop.
The gateway now sees two packets to route. In no case these packets hint anymore if they were using 192.168.1.1
or 192.168.1.2
as gateway: the information doesn't appear on the wire so can't be known anywhere by the gateway. If the system has no information to distinguish the cases, then iptables can't have this non-existing information either.
Suggestion of workaround:
One can use a MACVLAN interface to have a second NIC with its own separate MAC address and assign 192.168.1.2/24 to it instead, which will make packets from clients using 192.168.1.2 as gateway arrive on this NIC instead. This case is easy to distinguish with iptables: a different -i NIC
filter.
But this creates the routing problem of having multiple NICs in the same LAN and requires either:
advanced policy-routing rules to address this case properly
so replies aren't sent through the wrong NIC possibly affecting routing behavior or firewall rules.
- and in addition, any UDP service queried on 192.168.1.2 (if 192.168.1.1 is the default), must know how to answer with the correct source address 192.168.1.2 (instead of default 192.168.1.1): it must be multi-homed aware. TCP doesn't require special care.
or else an additional network namespace to separate the added interface. But with a REDIRECT rule, that means the service on port 9992 must run in the additional network namespace instead. And this network namespace still probably has to communicate to Internet using the initial network namespace: also more configuration to plan in various places.