How can I get used ports and their states on Linux? Basically, everything that netstat
can do, but in C?
Asked
Active
Viewed 1,186 times
3

Mateen Ulhaq
- 24,552
- 19
- 101
- 135

Doddy
- 1,311
- 1
- 17
- 31
-
3What makes you think that netstat isn't written in C? http://src.gnu-darwin.org/src/usr.bin/systat/netstat.c.html or code.turnkeylinux.org/busybox/networking/netstat.c – fvu Dec 22 '11 at 22:38
-
Also, if `netstat` already does what you want, why the need to rewrite it? – dreamlax Dec 22 '11 at 22:40
-
I don't intend to rewrite netstat, just have similar functionality in one of my own programs. – Doddy Dec 22 '11 at 22:47
2 Answers
3
Running strace on a run of netstat will show you the system calls it makes and their arguments.
$ strace netstat
...
open("/proc/net/tcp6", O_RDONLY) = 3
open("/proc/net/udp", O_RDONLY) = 3
...
This is often a good way to find out what a program is doing or the calls it makes and can sometimes be easier than looking at the source if all you need is to find out which call to look up on a man page.

Paul Rubel
- 26,632
- 7
- 60
- 80
1
Well, for “everything that netstat can do,” you could start with netstat
itself. The source code is here:
It should be noted that most of what netstat
does, it obtains from the /proc
filesystem; it looks like the *_do_one
routines hold most of the "interesting" guts.

BRPocock
- 13,638
- 3
- 31
- 50
-
I didn't mean it to be a naive question, I was just hoping there was a set of methods, but I'm surprised to learn that it reads files from `/proc`... isn't that a bad tactic for programs? As an example, I would use `sysinfo()` to get uptime, as opposed to reading `/proc/uptime`. – Doddy Dec 22 '11 at 22:56
-
1@bean: Remember that `/proc/uptime` is not a standard *file*, but directly accesses the device driver in the kernel that provides the uptime (in text format). The rest of the things in `/proc` work the same way. – Greg Hewgill Dec 22 '11 at 22:59
-
In general, the `/proc` and `/sys` filesystems *are* the preferred interfaces to a lot of Linux kernel subsystems. When there are library functions available that provide duplicate functionality, they're often (but not always) implemented in the libc as a wrapper around access to proc. I don't know, offhand, if `sysinfo` is such a call, but its manpage does link to proc(5). – BRPocock Dec 22 '11 at 23:10