Ask Your Question
3

What is the method for obtaining the pid of a socket's peer using programming in MacOS?

asked 2021-09-17 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-04-07 16:00:00 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-17 11:00:00 +0000

Seen: 8 times

Last updated: Apr 07 '23