How to list processes belonging to a network namespace?

You could do something like:

netns=myns
find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/"$netns" | cut -d/ -f5

Or with zsh:

print -l /proc/[1-9]*/task/*/ns/net(e:'[ $REPLY -ef /run/netns/$netns ]'::h:h:t)

It checks the inode of the file which the /proc/*/task/*/ns/net symlink points to agains those of the files bind-mounted by ip netns add in /run/netns. That's basically what ip netns identify or ip netns pid in newer versions of iproute2 do.

That works with the 3.13 kernel as from the linux-image-generic-lts-trusty package on Ubuntu 12.04, but not with the 3.2 kernel from the first release of 12.04 where /proc/*/ns/* are not symlinks and each net file there from every process and task gets a different inode which can't help determine namespace membership.

Support for that was added by that commit in 2011, which means you need kernel 3.8 or newer.

With older kernels, you could try and run a program listening on an ABSTRACT socket in the namespace, and then try to enter the namespace of every process to see if you can connect to that socket there like:

sudo ip netns exec "$netns" socat abstract-listen:test-ns,fork /dev/null &
ps -eopid= |
  while read p; do
    nsenter -n"/proc/$p/ns/net" socat -u abstract:test-ns - 2> /dev/null &&
      echo "$p"
  done

The question specifically mentions Ubuntu 12.04, but I note that on newer distros like 16.04 there is a command that does exactly this: ip netns pids <nsname>


ps $(ip netns pids myns) where myns is your namespace