有没有办法获得unix套接字连接的另一端的uid

有没有一种方法让UNIX域套接字侦听器只接受来自某个用户的连接( chmod / chown不能用于抽象套接字afaik),换句话说,就是获取传入连接的uid(在Linux上)?

在Linux上使用抽象的unix套接字的Dbus有一个函数GetConnectionUnixUser ,它被polkit用来确定调用者。 所以我想dbus-daemon必须有办法做到这一点。 有谁知道这是如何工作的?

检查对等凭证的最简单方法是使用SO_PEERCRED 。 为套接字sock做这个:

 int len; struct ucred ucred; len = sizeof(struct ucred); if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == -1) // check errno printf("Credentials from SO_PEERCRED: pid=%ld, euid=%ld, egid=%ld\n", (long) ucred.pid, (long) ucred.uid, (long) ucred.gid); 
 SO_PEERCRED Return the credentials of the foreign process connected to this socket. This is possible only for connected AF_UNIX stream sockets and AF_UNIX stream and datagram socket pairs created using socketpair(2); see unix(7). The returned credentials are those that were in effect at the time of the call to connect(2) or socketpair(2). The argument is a ucred structure; define the _GNU_SOURCE feature test macro to obtain the definition of that structure from <sys/socket.h>. This socket option is read-only. 

从一个例子 。 PostgreSQL有其他一些unices的几个变种。

是 – 此操作与FD传递一起,通过SCM_CREDENTIALS类型的辅助消息来支持。 涉及的调用记录在man 7 unix