gpt4 book ai didi

linux - 识别连接到 Unix 域套接字的程序

转载 作者:IT王子 更新时间:2023-10-29 00:03:18 25 4
gpt4 key购买 nike

我有一个正在监听 Unix 域套接字的程序。

当客户端连接到套接字时,我想找出连接的程序,然后决定是否允许连接(基于用户/组设置)。

这在 Linux 下是否可行,如果可行,如何实现?

最佳答案

是的,这在 Linux 上是可能的,但它不是很便携。它是通过 sendmsg/recvmsg 使用所谓的“辅助数据”实现的。

  • 使用 SO_PASSCREDsetsockopt
  • 使用SCM_CREDENTIALSstruct ucred结构

这个结构在 Linux 中定义:

struct ucred {
pid_t pid; /* process ID of the sending process */
uid_t uid; /* user ID of the sending process */
gid_t gid; /* group ID of the sending process */
};

请注意,您必须在 msghdr.control 中填写这些内容,内核将检查它们是否正确。

主要的可移植性障碍是这种结构在其他 Unix 上不同 - 例如在 FreeBSD 上它是:

struct cmsgcred {
pid_t cmcred_pid; /* PID of sending process */
uid_t cmcred_uid; /* real UID of sending process */
uid_t cmcred_euid; /* effective UID of sending process */
gid_t cmcred_gid; /* real GID of sending process */
short cmcred_ngroups; /* number or groups */
gid_t cmcred_groups[CMGROUP_MAX]; /* groups */
};

关于linux - 识别连接到 Unix 域套接字的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8104904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com