I am trying to get ports used by processes. It can be done via lsof on macOS, i am trying to do it via libproc.
#include <iostream>
#include <libproc.h>
int main(int argc, const char * argv[]) {
pid_t pids[3072];
int count = proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
for (int i = 0; i < count; i++) {
char buffer[1024];
for (int j = 1; j < 50000; j++) { //port range
int ret = proc_pidfileportinfo(pids[i], j, PROC_PIDFILEPORTVNODEPATHINFO, buffer, sizeof(buffer));
if(ret != 0) {
printf("proc_pidfileportinfo returned %d bytes of data\n", ret);
printf("%s\n", name);
}
}
}
return 0;
}
proc_pidfileportinfo
function is not working for any port, i tried iterating till 50K. What i am doing wrong with proc_pidfileportinfo?
how to properly use proc_pidfileportinfo?
OK.
By far the easiest way to do this is to sublaunch lsof
. Normally I don’t recommend such shenanigans but in this case lsof
has specific affordance for it. See the Output for Other Programs section of the lsof
man page.
If you don’t want to do that then, yes, libproc is the right answer. However, you’re barking up the wrong tree with the fileport stuff. A fileport is a Mach port that holds a file descriptor [1]. There is no fileport API per se, but you can see hints of it with other APIs. For example, it’s the mechanism that allows XPC to transfer file descriptors in an XPC message (XPC_TYPE_FD
).
Rather that work with fileports you want to work with file descriptors directly. Call proc_pidinfo
with PROC_PIDLISTFDS
and then call proc_pidfdinfo
with proc_pidfdinfo
with PROC_PIDFDSOCKETINFO
. And if you get stuck, check out the lsof
source code in Darwin.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
[1] Well, not actually the file descriptor but the node that the file descriptor references.