How to check if a process in run in the root network namespace or not

George Shuklin
OpsOps
Published in
1 min readSep 17, 2021

Generally, there is no way. But if you know, there is no user/pid namespaces involved, there is a simple heuristic.

We know that systemd does not run in the namespace. All we have to do is compare our own namespace FD with systemd.

Each process has own FD associated with its namespace: /proc/self/ns/net.

And we know for sure the PID of systemd, or any other startup system. It’s one.

So:

# readlink /proc/self/ns/net /proc/1/ns/net
net:[4026532427]
net:[4026532427]

If those numbers are different, you are in the different network namespace.
If they are the same, you either in the root network namespace or is in the container, where a separate PID namespace.

Technically, this works for any other process you want to inspect, but, there is a little trick: if you are using ip netns, it allows creation of namespaces without processes. It does so by using bind mount to run/netns. Any other process can do the same (with bind mount) at any random place in filesystem. But those are special, they don’t have processes. If you run a process in such namespace (ip netns exec foobar /bin/bash), your freshly started bash will have /proc/self/ns/net set to a proper value.

--

--

George Shuklin
OpsOps

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux. My hobby is Rust.