如何在 Linux 上获取与登录关联的用户 ID? [英] How can I get the user id associated with a login on Linux?

查看:24
本文介绍了如何在 Linux 上获取与登录关联的用户 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短版本:我想要一种方法来运行 somefunction("username") 并让它返回与 username 关联的用户 ID.例如 somefunction("root") 将返回 0.

Short version: I want a way to run somefunction("username") and have it return the user ID associated with username. For example somefunction("root") would return 0.

我正在编写一个可能使用低编号端口的服务器程序,因此它必须以 root 身份启动.显然,我不希望它以 root 身份运行,所以计划是让用户指定程序应该以什么用户身份运行.问题是 setuid() 需要一个用户 ID,而我不知道如何从登录名中查找用户 ID.我查看了 unistd.h,它似乎只有查找当前用户信息的功能.

I'm writing a server program that could potentially use low-numbered ports, so it has to start as root. Obviously, I don't want it to run as root, so the plan is to let users specify what user the program should run as. The problem is that setuid() requires a user ID and I don't know how to look up a user ID from a login name. I looked in unistd.h and it seems to only have functions for finding info about the current user.

我知道我可以只打开 /etc/passwd,但我宁愿不要在必须有一个函数时这样做.

I know I could just open /etc/passwd, but I'd rather not when there's bound to be a function for this.

推荐答案

你想要 getpwnam.

这是我刚刚写的一个完整示例:

Here's a complete example I just wrote:

#define _POSIX_SOURCE
#include <sys/types.h>
#include <stdio.h>
#include <pwd.h>
#include <unistd.h>

uid_t name_to_uid(char const *name)
{
  if (!name)
    return -1;
  long const buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
  if (buflen == -1)
    return -1;
  // requires c99
  char buf[buflen];
  struct passwd pwbuf, *pwbufp;
  if (0 != getpwnam_r(name, &pwbuf, buf, buflen, &pwbufp)
      || !pwbufp)
    return -1;
  return pwbufp->pw_uid;
}

void main(int argc, char **argv)
{
  printf("%i\n", name_to_uid(argv[1]));
}

这篇关于如何在 Linux 上获取与登录关联的用户 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆