Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can get ports associated to the application that opened them?

Tags:

c++

linux

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.

like image 966
Night Walker Avatar asked Jul 22 '10 05:07

Night Walker


2 Answers

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)

like image 54
Michael Spector Avatar answered Sep 19 '22 02:09

Michael Spector


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.

like image 28
Matt Joiner Avatar answered Sep 21 '22 02:09

Matt Joiner