I am running some application in multiple network namespace. And I need to create socket connection to the loopback address + a specific port in each of the name space. Note that the "specific port" is the same across all network namespaces. Is there a way I can create a socket connection like this in python?
Appreciate any pointer!
This was a fun problem.
Update: I liked it so much that I packed up the solution as an installable Python module, available from https://github.com/larsks/python-netns.
You can access another network namespace through the use of the
setns()
system call. This call isn't exposed natively by Python, so in order to use it you would either (a) need to find a third-party module that wraps it, or (b) use something like thectypes
module to make it available in your Python code.Using the second option (
ctypes
), I came up with this code:Prior to running this code, I created two network namespaces:
I added an interface inside of each namespace, so that the final configuration looked like this:
Running the code (as
root
, because you need to be root in order to make use of thesetns
call), I can connect to either192.168.115.2:7777
(thered
namespace) or192.168.113.2:7777
(theblue
namespace) and things work as expected.