Bind interface

From Federal Burro of Information
Jump to navigationJump to search

https://unix.stackexchange.com/questions/210982/bind-unix-program-to-specific-network-interface


For Linux, this has already been answered on Superuser - How to use different network interfaces for different processes?.

The most popular answer uses an LD_PRELOAD trick to change the network binding for a program, but modern kernels support a much more flexible feature called 'network namespaces' which is exposed through the ip program. This answer shows how to use this. From my own experiments I have done the following (as root):

# Add a new namespace called test_ns
ip netns add test_ns

# Set test to use eth0, after this point eth0 is not usable by programs
# outside the namespace
ip link set eth0 netns test_ns

# Bring up eth0 inside test_ns
ip netns exec test_ns ip link set eth0 up

# Use dhcp to get an ipv4 address for eth0
ip netns exec test_ns dhclient eth0

# Ping google from inside the namespace
ip netns exec test_ns ping www.google.co.uk

It is also possible to manage network namespaces to some extent with the unshare and nsenter commands. This allows you to also create separate spaces for PIDs, users and mount points. For some more information see:

Reliable way to jail child processes using `nsenter:`

Namespaces in operation