Linux: Is there handy way to exec a program binding it to IP-address of choice

freebsdipjailslinuxlxc

In FreeBSD 4.9 it was very easy to accomplish with just a single command like

jail [-u username]  path hostname ip-number command

if path was / you had running just the same program as usual but all its network communication was restricted to use only given IP-address as the source. Sometimes it's very handy.

Now in Linux there's LXC, which does look very similar to FreeBSD's jail (or Solaris' zones) — can you think of similar way to execute a program?

Best Answer

Starting the process inside a network namespace that can only see the desired IP address can accomplish something similar. For instance, supposed I only wanted localhost available to a particular program.

First, I create the network namespace:

ip netns add limitednet

Namespaces have a loopback interface by default, so next I just need to bring it up:

sudo ip netns exec limitednet ip link set lo up

Now, I can run a program using ip netns exec limitednet and it will only be able to see the loopback interface:

sudo ip netns exec limitednet ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever

If I wanted to limit it to an address other than localhost, I could add other interfaces into the namespace using:

ip link set DEVICE_NAME netns NAMESPACE

I'd have to experiment a bit more to figure out how to add a single IP address into a namespace in the case where an interface might have more than one IP address

The LWN article on namespaces is also helpful.

Related Question