In part 1 of this series, I demonstrated the use of unshare() and setns() to create new network namespaces and enter existing ones. I didn’t call attention to it in that post, but you may have noticed that the new network namespace only has a down loopback device, which makes it quite uninteresting without further configuration.

Now I could start executing some iproute2 commands, but I’m also using Zig to tinker with the Netlink protocol (see Using Comptime for Netlink). At this point, I have a program that can manage links and addresses (though supporting very few options) and have also implemented the namespace process as described in part 2.

Demo

As a reminder, the code is all here1. The program writes namespace PIDs to ${HOME}/.local/state/net/${name}.pid according to the XDG spec2.

$ ./zig-out/bin/net ns add demo
$ ./zig-out/bin/net ns list
|-----------------------------------------------------|
| name             | pid        | created             |
|-----------------------------------------------------|
| demo             | 219257     | 2023-09-01 18:09:19 |
|-----------------------------------------------------|
$ ./zig-out/bin/net ns enter demo
$ ./zig-out/bin/net link list
|------------------------------------------------------------|
| id  | name            | type      | address           | up |
|------------------------------------------------------------|
| 1   | lo              | loopback  | 00:00:00:00:00:00 |    |
|------------------------------------------------------------|
$ ./zig-out/bin/net link add asdf dummy
$ ./zig-out/bin/net link set asdf up
$ ./zig-out/bin/net link list
|------------------------------------------------------------|
| id  | name            | type      | address           | up |
|------------------------------------------------------------|
| 1   | lo              | loopback  | 00:00:00:00:00:00 |    |
| 2   | asdf            | ether     | 02:57:49:31:10:71 | *  |
|------------------------------------------------------------|
$ ./zig-out/bin/net addr add 192.0.2.0 asdf
$ ./zig-out/bin/net addr list
|----------------------------------------------------------------|
| name             | address                                     |
|----------------------------------------------------------------|
| asdf             | 192.0.2.0/32                                |
|----------------------------------------------------------------|
$ exit
$ ./zig-out/bin/net ns del demo

So far, my program is just a worse version of iproute2. I mean I like the tabular output and all, but the add subcommands support probably less than 10% of the options by comparison.

The one reason I’ll have it installed on my machine is for the unprivileged network namespace. I could not perform the steps above with iproute2 without either using sudo or the combination of unshare and nsenter to create the namespace.