Using Linux Network Namespaces
You rarely get to work with Linux namespaces directly. Usually they sit behind the scenes in container tooling or hosting platforms that enforce hard resource limits for customers. But sometimes containers are too heavy for the job. I once needed two instances of the same service to talk to each other over the network.
Why not just have them listen on different addresses or ports? Because it isn’t always that simple. If you can’t change the code and only want to replicate a certain behavior, there may be no way to make an instance use a different port. If the protocol also relies on broadcasting, it gets harder still, since you often don’t have two IP addresses on separate interfaces attached to the same network. Virtualization or containers would solve this, but they’re overkill here. A lightweight alternative is to manipulate Linux network namespaces.
Note: Run all commands below as root.
Open two terminals. Call one the “primary” and the other the “secondary”, and keep track of which is which. In the secondary, run:
# unshare -n /bin/bash
# echo $$
xxxxxx
Note the PID that is printed, since you need it in the next step.
In the primary, create a virtual Ethernet pair and configure one end, using the PID from step 1:
# ip link add name veth0 type veth peer name veth1 netns xxxxxx
# ip address add 192.168.10.10/24 dev veth0
# ip link set veth0 up
Then, in the secondary, configure the other end and test the link:
# ip address add 192.168.10.15/24 dev veth1
# ip link set veth1 up
# ping 192.168.10.10
...
I won’t go into detail here, since the goal was only to get a working communication path. It looks easy, and it is. Hope it helps!