1

Is there a way to use Python's socket module to replicate some of the functionality of the Linux ss utility?

ss is used to dump socket statistics. It allows showing information similar to netstat. It can display more TCP and state informations than other tools.

Pretty much all of the socket documentation revolves around creating new sockets, but I can't find any information on getting statistics from the system's sockets.

1
  • Why? What use is it in an applicaion? Commented Jan 6, 2020 at 0:06

1 Answer 1

2

I don't see how such functionality could be implemented purely with the socket module. The socket module is for working directly with sockets: opening/closing, sending/receiving, etc. It's simply a thin wrapper over the standard BSD socket interface.

On the other hand, getting metadata about existing sockets already allocated on the system requires knowledge of the other processes running on a system. This has little to do with actually manipulating a socket, and much more to do with monitoring other processes and/or their file descriptors.

For example, it seems that both ss and netstat are actually implemented (at least on Linux) by reading and parsing the /proc pseudo-filesystem. (See here and here, for examples.) The kernel manages the processes and their opened sockets, and exposes (some of) the information about them to other processes via procfs. This provides a simple and safe way of exporting some of the information about processes to userspace, obviating the need for lots of system calls or reading kernel data structures directly.

Note that it pretty much has to work this way. Strong process isolation necessitates that information about another process's open files, including sockets, has to come through the kernel in some way. That could be either via procfs on Linux, or some kernel-provided API (e.g. libproc on macOS). Anything else would be a massive security hole.

As an alternative to the socket module, you could try the psutil package or something similar. The psutil.net_connections() function seems appropriate.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much for the details explanation and suggestion to look into psutil! That looks like it'll do the trick perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.