In MacOS, you can obtain the process ID (pid) of a socket's peer using the getsockopt()
function with the SO_PEERCRED
option. Here's an example code snippet in C:
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ucred.h>
// ...
int sockfd; // socket descriptor
ucred ucred;
socklen_t len = sizeof(ucred);
if (getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
pid_t pid = ucred.pid;
// do something with the pid
} else {
// error handling
}
Note that this method requires that the socket is connected, and that the peer process sets up the socket with its credentials before sending data.
Asked: 2021-09-17 11:00:00 +0000
Seen: 8 times
Last updated: Apr 07 '23