Make an arbitrary Linux application use a specific IP address for outbound connections

Solution 1:

You could take advantage of the LD_PRELOAD environment variable and "function interposition" to modify the behavior of your network programs. See this article for an example, and Google function interposition for more information.

You could, for example, override the "socket" system call so that every socket() call was followed by an appropriate bind() operation.

NB: This technique can be lots of fun to play with (for example, I once wrote something that would let me "open" URLs for editing with arbitrary text editors), but can be tricky to get right.

Solution 2:

My only suggestion would be to utilize iptables to redirect the traffic from one interface to another.

Here's a link to someone else who did something similar: http://straylink.wordpress.com/2006/08/16/using-iptables-to-redirect-packets/

Essentially, the command was this:

iptables -t nat -A PREROUTING -p tcp -d 198.168.1.254 --dport 80 -j REDIRECT --to-ports 8080

To completely steal the content (in case it disappears),

The above rule adds a PREROUTING command to your nat table, stating any TCP packets destined for 192.168.1.254 on port 80 should be redirected to localhost port 8080. So breaking down the above example into template format, you have

 iptables -t nat -A PREROUTING -p PROTO -d DEST_IP --dport DEST_PORT -j REDIRECT --to-ports LOCAL_PORTS