On Linux, namespaces are a way to partition resources and restrict process abilities to use them.

When testing network equipment, one clever usage of network namespaces is to isolate network interfaces and blocking loopback traffic, so that traffic generated on one interface must go through the physical NIC and return on it.

This is useful, for instance, to check the throughput of a middleware or any generic network equipment.

Namespaces are typically managed through the ip netns utility (man pages).

Let’s see some commands to create and handle a client-server scenario.

Create namespaces

sudo ip netns add client
sudo ip netns add server

Add interfaces to namespaces

sudo ip link set dev eth1 netns server
sudo ip link set dev eth2 netns client

Bring them up

sudo ip netns exec server ip link set dev eth1 up
sudo ip netns exec client ip link set dev eth2 up

Set IPs

The interfaces will loose their IP.

To set them manually:

sudo ip netns exec server ip addr add dev eth1 192.168.99.1/24
sudo ip netns exec client ip addr add dev eth2 192.168.99.2/24

Or, if you have a DHCP server in the network:

sudo ip netns exec server dhclient -i eth1 -v -d 
sudo ip netns exec client dhclient -i eth2 -v -d 

Run commands in your namespaces

For instance, let’s run iPerf:

sudo ip netns exec server iperf -s
sudo ip netns exec client iperf -c 192.168.99.1

Non-sudo privileges

Any process in the namespace by default will run as root. And this is not good (usually).

You should be able to change user by using something like

sudo ip netns exec server sudo --user YOURUSER iperf -s

Delete namespaces

You should first remove the interfaces from the namespaces, then delete them. To remove them from the namespace, we’ll assign them to the same namespace of the init process (with PID 1).

sudo ip netns exec server ip link set eth1 netns 1
sudo ip netns exec client ip link set eth2 netns 1

sudo ip netns delete client
sudo ip netns delete server

Virtual interfaces between namespaces

You can also link namespaces together:

sudo ip link add veth0 type veth peer name veth1
sudo ip link set veth0 netns server
sudo ip link set veth1 netns client
sudo ip netns exec server ip addr add dev veth0 192.168.99.101/24
sudo ip netns exec client ip addr add dev veth1 192.168.99.202/24
sudo ip netns exec server ip link set dev veth1 up
sudo ip netns exec client ip link set dev veth2 up

Now, applications in client and server can communicate through veth0 and veth1.

But I have a single Ethernet port!

You could use macvlan interfaces to create multiple virtual physical interfaces:

sudo ip link add link eth0 name eth1 type macvlan
sudo ip link add link eth0 name eth2 type macvlan

And then use them as stated above.