监听unix套接字时检查发送者

Zoh*_*r81 1 c sockets macos unix-socket xnu

我有一个监听 unix 套接字的进程。但是,在阅读之前,我想检查有关此传入消息的一些元数据,例如它的源进程(假设我想删除来自不可信发件人的消息)。是否有任何系统调用可以检索此信息。

    if(listen(sock_fd, 10) != 0) {
        assert("listen failed");
    }

    while((conn_fd = accept(sock_fd,
                       (struct sockaddr *) &address,
                       &address_length)) != -1) {
        int nbytes = 0;
        static char buffer[PAYLOAD_SZ];
        nbytes = (int)read(conn_fd, buffer, PAYLOAD_SZ);
Run Code Online (Sandbox Code Playgroud)

Zoh*_*r81 6

经过一些研究后,我找到了最适合我的需求的答案。

使用getsockopt我能够获得对等 pid。

getsockopt(fd,SOCK_STREAM, LOCAL_PEERPID, &pid, &pid_len); 
Run Code Online (Sandbox Code Playgroud)

使用此功能,我还能够收集对等凭据等等。只需验证发送此查询时对等方没有关闭套接字。