Anthony J. Martinez

Quick Look @ netns

A quick and dirty approach to creating a network namespace for an application that is otherwise unable to bind a specific interface. An added bonus here specifies a distinct DNS server for the namespace itself.

A few details about the example system:

  1. The default network interface is eth0
  2. We want to jail an application's network to VLAN 42
  3. There is a forwarding DNS server on the router managing VLAN 42
  4. We will call the network namespace the_answer
  5. We will use 172.30.242.16/29 as an IPv4 subnet unlikely to immediately collide with anything else

First make sure DNS works:

# as root (directly or with appropriate sudo usage)
mkdir -p /etc/netns/the_answer
echo -n "nameserver 172.30.242.17\nsearch .\n" > /etc/netns/the_answer/resolv.conf

Now it's time to flex iproute2 for all it's worth

# as root (directly or with appropriate sudo usage)
ip netns add the_answer
ip link add name eth0.42 link eth0 type vlan id 42
ip link set dev eth0.42 netns the_answer
ip netns exec the_answer ip link set dev eth0.42 up
ip netns exec the_answer ip address add 172.30.242.18/29 broadcast 172.30.242.23 dev eth0.42
ip netns exec the_answer ip route add default via 172.30.242.17 dev eth0.42

At this point you have the_answer configured and can launch network applications inside it that will utilize the available interface, route, and DNS without having to know anything about their configuration in advance. Just run:

ip netns exec the_answer [your_application] [args]