Skip to content

Instantly share code, notes, and snippets.

@harish2704
Created December 1, 2017 15:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harish2704/6f42ba1059a31435cff461f6499a884f to your computer and use it in GitHub Desktop.
Save harish2704/6f42ba1059a31435cff461f6499a884f to your computer and use it in GitHub Desktop.
Routing network traffic of specific process through specific interface in linux

Consider we have two working ether net connections. One will be set as default by system.

What if we want to route all the network traffic for a specific process through a specific network interface ? In Linux, we can do this easily

My current configuration is this.

enp0s26u1u2 Link encap:Ethernet  HWaddr 02:45:4a:37:5a:28  
          inet addr:192.168.42.244  Bcast:192.168.42.255  Mask:255.255.255.0
          inet6 addr: fe80::80dd:1547:fe5d:986f/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:5188 errors:0 dropped:0 overruns:0 frame:0
          TX packets:4354 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:3915768 (3.9 MB)  TX bytes:845144 (845.1 KB)

wlp2s0    Link encap:Ethernet  HWaddr a4:db:30:e2:b5:35  
          inet addr:192.168.0.19  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::65d6:dbac:56e3:3e6f/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2507663 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1776662 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:2839280384 (2.8 GB)  TX bytes:239215030 (239.2 MB)

ip route command output

default via 192.168.42.129 dev enp0s26u1u2  proto static  metric 100 
default via 192.168.0.1 dev wlp2s0  proto static  metric 600 

So, By default, all the traffic will pass through enp0s26u1u2 interface.

Now, I want to run a wget command using wlp2s0 interface.

For that, first we will create a routing rule saying "All the trafic comming from 192.168.0.19 should be classified under table "3"

ip rule add from 192.168.0.19 table 3

Then we will add a route saying that, "All the traffic comes under table 3 should use 192.168.0.1 dev wlp2s0 as default route"

ip route add table 3 default via 192.168.0.1 dev wlp2s0

Now, we will run wget command with --bind-address 192.168.0.19 option. Thats all. Done.

Note: not all the applications will have an option to specify bind address. In that case, we can use LD_PRELOAD hack to do the same. For this, compile this as specified in that file. then run any application wtih like

env BIND_ADDR=192.168.0.19 LD_PRELOAD='<path to bind.so>/bind.so' firefox

Thats it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment