Building a Network with Namespaces

A network in a box

A network namespace is an isolated copy of the network stack — its own interfaces, addresses and routes. Containers use them to keep each app's network separate. You can make one with ip netns and run a command inside it with ip netns exec:

sudo ip netns add blue
ip netns list
sudo ip netns exec blue ip addr show

In the terminal

student@vulntech:~$ sudo ip netns add blue
[sudo] password for student:
student@vulntech:~$ ip netns list
blue
student@vulntech:~$ sudo ip netns exec blue ip addr show
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00

Inside blue there's only a (down) loopback — a brand-new, empty network.

A virtual cable: veth

To connect two namespaces, make a veth pair: two virtual interfaces joined like the ends of a cable. Put one end in each namespace, give each an address on the same little network, bring them up, and they can talk:

sudo ip netns add red
sudo ip link add vblue type veth peer name vred
sudo ip link set vblue netns blue
sudo ip link set vred netns red
sudo ip netns exec blue ip addr add 10.0.0.1/24 dev vblue
sudo ip netns exec red ip addr add 10.0.0.2/24 dev vred
sudo ip netns exec blue ip link set vblue up
sudo ip netns exec red ip link set vred up
sudo ip netns exec blue ping -c2 10.0.0.2

In the terminal

student@vulntech:~$ sudo ip netns add red
[sudo] password for student:
student@vulntech:~$ sudo ip link add vblue type veth peer name vred
student@vulntech:~$ sudo ip link set vblue netns blue
student@vulntech:~$ sudo ip link set vred netns red
student@vulntech:~$ sudo ip netns exec blue ip addr add 10.0.0.1/24 dev vblue
student@vulntech:~$ sudo ip netns exec red ip addr add 10.0.0.2/24 dev vred
student@vulntech:~$ sudo ip netns exec blue ip link set vblue up
student@vulntech:~$ sudo ip netns exec red ip link set vred up
student@vulntech:~$ sudo ip netns exec blue ping -c2 10.0.0.2
PING 10.0.0.2 (10.0.0.2) 56(84) bytes of data.
64 bytes from 10.0.0.2: icmp_seq=1 ttl=64 time=1.93 ms
64 bytes from 10.0.0.2: icmp_seq=2 ttl=64 time=15.8 ms

--- 10.0.0.2 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1006ms
rtt min/avg/max/mdev = 1.930/8.876/15.823/6.946 ms

Think of it like this: Two namespaces joined by a veth pair are two computers joined by one cable. The 10.0.0.0/24 addresses put them on the same network, so a packet from 10.0.0.1 reaches 10.0.0.2 — the same idea as two real machines on a switch.

Remember: A network namespace is a private network stack (ip netns add, ip netns exec NS command). A veth pair is a virtual cable joining two of them; give each end an address on one subnet and they can ping.

HOME LEARN COMMUNITY DASHBOARD
Practice terminal Starting…