Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the user id associated with a login on Linux? [duplicate]

Tags:

c

unix

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.

like image 619
Brendan Long Avatar asked Oct 01 '10 03:10

Brendan Long


People also ask

How do I find the username ID in Linux?

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.

Where are Linux user accounts stored?

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.


1 Answers

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]));
}
like image 171
Matt Joiner Avatar answered Oct 21 '22 11:10

Matt Joiner