配置进程以使用特定的 NIC

Nit*_*hin 3 linux networking process network-interface

我有两个 NIC(一个以太网和一个来自移动设备的网络共享)。我的以太网互联网连接是端口过滤的,所以我不能在上面使用一些应用程序。所有应用程序都可以在我的移动网络共享上运行,但由于我只有有限的数据,我只希望某些选定的应用程序使用该 NIC。

所以问题是:如何仅强制某些进程使用特定的 NIC?

小智 6

基本上你想“监禁”你的进程并强制它绑定到特定的网卡。很多人使用 LD_PRELOAD 但 LD_PRELOAD 不控制进程使用的路由。它将使用第一条路线。一种可能的解决方案是超级用户https://superuser.com/questions/241178/how-to-use-different-network-interfaces-for-different-processes/241215#241215

ip netns 可以做到这一点。

TL;DR:创建网络命名空间,将接口关联到它们,然后运行“ip netns exec NAME cmd...”

只需检查您的发行版是否支持 ip netns...(Backtrack 5r3 不支持,而 Kali 支持;))

更多细节:

#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
Run Code Online (Sandbox Code Playgroud)