Using Network Namespaces on Linux

1 minute read

Published:

Using Network Namespaces on Linux

In this guide, we will explore how to use network namespaces on Linux to enable communication between internal and external networks, along with defining static routes.

Step 1: Creating Network Namespaces

To begin, create an internal and an external network namespace:

sudo ip netns add ns_internal
sudo ip netns add ns_external

Step 2: Adding Interfaces to Network Namespaces

Next, add loopback interfaces to the created network namespaces:

sudo ip netns exec ns_internal ip link set lo up
sudo ip netns exec ns_external ip link set lo up

Now, connect the physical interface to each namespace:

sudo ip link add veth_internal type veth peer name veth_internal_ns
sudo ip link set veth_internal_ns netns ns_internal
sudo ip link set veth_internal up

sudo ip link add veth_external type veth peer name veth_external_ns
sudo ip link set veth_external_ns netns ns_external
sudo ip link set veth_external up

Step 3: Assigning IP Addresses and Enabling Routing

Assign IP addresses to the interfaces within each namespace:

sudo ip netns exec ns_internal ip addr add 192.168.1.1/24 dev veth_internal_ns
sudo ip netns exec ns_external ip addr add 192.168.2.1/24 dev veth_external_ns

Now, configure NAT to enable the internal network to communicate with the outside world:

sudo iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE

Lastly, define a static route for the external network namespace to access the internal network:

sudo ip netns exec ns_external ip route add 192.168.1.0/24 via 192.168.2.1 dev veth_external_ns

Step 4: Testing Communication

It’s time to test the communication between the namespaces. From the internal namespace, ping the external namespace:

sudo ip netns exec ns_internal ping 192.168.2.1

Similarly, from the external namespace, ping the internal namespace:

sudo ip netns exec ns_external ping 192.168.1.1

If everything is set up correctly, you should have successful communication between the internal and external network namespaces.

Keep in mind that this is a basic setup for illustration purposes. In real-world scenarios, additional security measures and more comprehensive configurations may be required. Also, network namespaces and IP routing can be complex, so handle them with care.