Search code examples
clinuxnetstat

How to List Active Ports and Processes using them in Linux, C Code


I am trying to write a C Code to do the same Job as:

netstat -vatp

List all Remote/Local Addresses and Processes using them. But I dunno which files should I be reading?

I tried looking into /proc/net/tcp and /proc/net/udp, but they don't have the process name or process identifier like netstat displays it!

Thanks.


Solution

  • You could check the source code http://freecode.com/projects/net-tools. Just download, unpack the bz2 file and you'll find the netstat.c source code

    Quick analyse:

    /proc/net/tcp for example has an inode tab, in /proc there is a subfolder for each of these inodes, which contains the information you need.

    Some more analysing:

    I think it's even worse. netstat just loops through the /proc directory and checks the contents of the numeric sub-directories to find the actual process matching the inode. Not sure as I'm just analysing

    http://linux.die.net/man/5/proc is very nice reading :)

    For your answer, see How can i match each /proc/net/tcp entry to each opened socket?