How to use different network interfaces for different processes?

I have two network interfaces on a Linux PC, and I need to manually set the interface that a given process will use.

The program (Twinkle softphone) does not have a similar option, so I believe that it must be set externally.

How can I do it?

Edit: I'm not trying to make a server process bind to a specific interface, but rather to make a client program contact a server using a specific interface.


you can replace code at runtime by the use of LD_PRELOAD (@windows you can use a similar technique called detours, quite fancy). what this does is to inform the dynamic linker to first load all libs into the process you want to run and then add some more ontop of it. you normally use it like this:

% LD_PRELOAD=./mylib.so ls

and by that you change what ls does.

for your problem i would try http://www.ryde.net/code/bind.c.txt, which you can use like:

% BIND_ADDR="ip_of_ethX" LD_PRELOAD=./bind.so twinkle

here is how you build it:

% wget http://www.ryde.net/code/bind.c.txt -O bind.c
% gcc -nostartfiles -fpic -shared bind.c -o bind.so -ldl -D_GNU_SOURCE

a longer howto is http://daniel-lange.com/archives/53-Binding-applications-to-a-specific-IP.html

similar hacks and tools:

  • bindhack
  • liboverride
  • fixsrcip
  • netjail

ip netns can do this.

TL;DR: Create network namespaces, associate interfaces to them and then run "ip netns exec NAME cmd..."

Just check if your distro supports ip netns... (Backtrack 5r3 does not, whereas Kali does ;) )

IN MORE DETAILS:

#create netns
ip netns add myNamespace
#link iface to netns
ip link set eth0 netns myNamespace
#set ip address in namespace
ip netns exec myNamespace ifconfig eth0 192.168.0.10/24 up
#set loopback (may be needed by process run in this namespace)
ip netns exec myNamespace ifconfig lo 127.0.0.1/8 up
#set route in namespace
ip netns exec myNamespace route add default gw 192.168.0.1
#force firefox to run inside namespace (using eth0 as outgoing interface and the route)
ip netns exec myNamespace firefox

Why is this better than binding the ip via LD_PRELOAD? Because LD_PRELOAD does not control the route that the processes uses. It will use the first route.

And since it always uses the same route, it will default to the interface registered to the route.(which is not what we want)


I don't think it is possible to force a process to use a certain interface.

However, I think you might be able to play with ipchain/iptables and force that a certain port your process is listening at will only get packets coming through a particular interface.

Useful HOWTO: http://tldp.org/HOWTO/IPCHAINS-HOWTO.html