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 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.
In Linux, the /etc/passwd file stores the user information, such as the user's name, UID, group id (GID), user's home directory, and user's shell. We can get the username by parsing the /etc/passwd file.
Every user on a Linux system, whether created as an account for a real human being or associated with a particular service or system function, is stored in a file called "/etc/passwd". The "/etc/passwd" file contains information about the users on the system.
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]));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With