5

I need to get a list of all opened ports on my machine and what application opened them. I need to get this information programmatically.

Thanks.

5 Answers 5

3

You have to implement the following:

  1. socket=ls -l /proc/<pid>/fd | grep socket | sed 's/.*socket:\[//' | sed 's/\]//'

  2. grep $socket /proc/net/tcp

  3. Parse the output from the previous command (second entry contains port information)

1
  • +1 for putting some meat on the very bare bones of my suggestion. If I was implementing, this would probably be enough information. Jul 22, 2010 at 11:17
2

I was hoping a cleverer answer would appear. I did just this (programmatically in Python), in an attempt to rewrite a program called NetHogs. My version is here, specifically here is the module in Python used to parse the table from /proc. If you're not Python literate (go learn it), then take a look at the original NetHogs, which uses a blend of C/C++ (and is a bit painful to read hence the rewrite).

It's worth noting that extensive or quickly repeated attempts to parse socket information from /proc is very CPU intensive, as the operating system has to handle every syscall made, and parse internal structures dynamically. As such you'll find some caching, and timing assumptions made in the source of both projects I've linked you to.

The short of it is, you need to relate the socket inodes given for each process in /proc/<pid>/fd to the connections given in /proc/net/<proto>. Again, example parsing, and how to locate all of these are present in both projects.

1
  • Broken links for your rewrite.
    – luizfls
    Jun 3, 2021 at 1:01
0
exec('netstat');
2
  • netstat tells you which ports are open, but not which applications opened them. lsof will do that. Jul 22, 2010 at 6:03
  • @n0rd: All these years and I didn't know! Thanks a lot for that hint, +1! Jul 22, 2010 at 11:18
0

The information about open files (including sockets) can be dug out of the /proc directory.

This article gives a lot of detail and gets you started.

0
ss -nltup 
netstat -ltupn
lsof  -iTCP -sTCP:LISTEN

Edit: Ah sorry, not programmatic. But helpful if you want to fork a process. No point in re-inventing the wheel every time.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.