Answering on the same interface where the request came from

Solution 1:

You can set routes in Linux based on the source IP address. While it's possible in Linux to bind to a specific interface, it's very uncommon. Routing based on source IP will allow you to create a default gateway per outgoing interface. Since the socket for the server fielding the requests can be bound to an IP, this will make sure the responses are sent out from the same interface that they came in on. (If the server is listening on the wildcard address (0.0.0.0), and not bound to a specific interface, you won't be able to use this method. It's still should be possible using the conntrack module, and iptables marks, but I won't go into that here).

You can accomplish this by creating another routing table using the ip command. The '10' here is arbitrary.

# 10.0.0.1 = gateway for the secondary interface
# 10.0.0.10 = ip address for the secondary interface eth1

ip route add default via 10.0.0.1 dev eth1 table 10
ip rule add from 10.0.0.10 table 10

If you're binding to multiple addresses, or have dhcp, you can create a rule base on subnet

ip route add default via 10.0.0.1 dev eth1 table 10
ip rule add from 10.0.0.0/8 table 10

If you are certain that the server is binding to a device, another default gateway with a higher metric will suffice.

ip route add default via 10.0.0.1 dev eth1 metric 2

Solution 2:

I'm not sure if this is possible in the general sense you desire. You certainly can control which network interface a program running on your machine uses by binding it to a particular address.

However, in general I don't think there's a way to connect incoming network packets to outgoing packets. The best you can do is provide instructions to the system along the lines of 'if you are trying to connect to this network, always use this interface'. This can be done in various ways via the system routing table (iproute) or with iptables firewall rules.

If this is for security purposes, have you thought about using virtual machines running on your physical server? You could configure one VM to only have access to one interface, and other VM to have access only to the other. Since the VM can't see the other interface at all, there's no way it could ever respond to packets from the incorrect network.

You should probably also look at this serverfault question which covers how to control which interface arp requests go out on. You should also look at the rp_filter sysctl, which can be set to ignore packets which appear on the incorrect interface.