Linux Network Namespace – How to Query and Change

linuxnetwork-namespace

I was wondering if there is a way to

  1. Query the network namespace the current shell is in
  2. Change the current network namespace of the current shell

I know I can do things like

sudo ip netns exec <namespace_name> <some command>

to execute a certain command in a certain network namespace, but I was thinking of something like

:~$ sudo query_current_namespace
some_namespace
:~$ sudo change_current_namespace_to other_namespace
:~$ sudo query_current_namespace
other_namespac
:~$ dothings in newnamespace

Just like changerooting into into some subdir, so I won't have to prefix every command with the sudo ip netns exec <namespace> thingy.

Searching the net it looks like I would have to write my own littel C Program, like suggested in this blog post. Is there allready a "standard" tool for this?

Edit: I just found that I could do

sudo ip netns exec <namespace> bash

which will give me a root shell in a new namespace. So almost there, but how do I query the current namespace?

Best Answer

See the man page:

   ip netns identify PID - Report network namespaces names for process
       This command walks through /var/run/netns and finds all the network
       namespace names for network namespace of the specified process.

So you would do something like:

ip netns identify $$