Search code examples
cmacossocketsunix-socketxnu

Check sender when listening to unix socket


I've got process that listen to unix socket. However, before i read, i'd like to check some meta data about this incoming message such as it's source process (say i'd like to drop messages from non trusted senders). is there any syscall that retrieve this information.

    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);

Solution

  • After doing some research, I've found the answer that is most suitable for my needs.

    using getsockopt i was able to get the peer pid.

    getsockopt(fd,SOCK_STREAM, LOCAL_PEERPID, &pid, &pid_len); 
    

    using this function i'm also capable to collect peer credentials, and more. just need to verify that the peer doesn't close the socket when this query is sent.