WilliamKF
WilliamKF

Reputation: 43209

How to do a netstat to see if a port is in use in C++?

From the command prompt, I can run netstat to see if a single port is already in use on a machine something like this:

netstat -nap | grep <port-num>

What functions could I call in C++ on Linux to just see whether a particular port is presently in use or not? I'd rather not do a system call to netstat itself.

Upvotes: 2

Views: 1376

Answers (1)

perreal
perreal

Reputation: 98118

If you do:

strace netstat -nap

You can deduce what netstat is doing to get that information.

For example:

open directory: openat(AT_FDCWD, "/proc/2073/fd", ...) = 4)
get entries: getdents(4, /* 15 entries */, 32768)    = 360
read symbolic links: readlink("/proc/2073/fd/4", "socket:[48395]", 29) = 14 
that one was a socket connected on port 48395

Upvotes: 4

Related Questions