DEV Community

BC
BC

Posted on

Use `getpwnam` to get uid by user's login name - C Lang

We can use getpwnam to get user's system UID by its login name, the function is:

#include <pwd.h>

struct passwd* getpwnam(const char*name);
Enter fullscreen mode Exit fullscreen mode

And the passwd struct is:

struct passwd {
  char* pw_name;    // login name (username) 
  char* pw_passwd;  // Encryped password
  uid_t pw_uid;     // User ID
  gid_t pw_gid;     // Group ID
  char* pw_gecos;   // Comment
  char* pw_dir;     // Initial working (home) dir
  char* pw_shell;   // login shell
}
Enter fullscreen mode Exit fullscreen mode

Example:

#include <stdio.h>
#include <pwd.h>
#include <string.h>

int main() {
    char name[30] = {0};
    struct passwd* pwd;
    size_t nread = 0;
    while (1) {
        printf("Query UID for login name: ");
        fgets(name, sizeof(name), stdin);

        nread = strlen(name);
        if (name[nread-1] == '\n') {
            name[strlen(name)-1] = 0;
        }
        // or use: name[strcspn(name, "\n")] = 0;

        if (strcmp(name, "quit") == 0) {
            break;
        }
        pwd = getpwnam(name);
        if (pwd == NULL) {
            printf("Cannot find UID for name %s\n", name); 
            continue;
        }
        printf("UID: %ld, Login Shell: %s\n", 
               (long)pwd->pw_uid, pwd->pw_shell);
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Compile gcc main.c -o main and run:

Query UID for login name: root
UID: 0, Login Shell: /bin/bash
Query UID for login name: nobody
UID: 65534, Login Shell: /usr/sbin/nologin
Query UID for login name: quit
Enter fullscreen mode Exit fullscreen mode

Top comments (0)