How can I get the user id associated with a login on Linux? [duplicate]
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
.
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开发者_如何学Python ID from a login name. I looked in unistd.h
and it seems to only have functions for finding info about the current user.
I know I could just open /etc/passwd
, but I'd rather not when there's bound to be a function for this.
You want 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]));
}
A simpler approach will be:
#include <pwd.h>
#define INVALID_UID -1
uid_t getuid_byName(const char *name)
{
if(name) {
struct passwd *pwd = getpwnam(name); /* don't free, see getpwnam() for details */
if(pwd) return pwd->pw_uid;
}
return INVALID_UID;
}
精彩评论