8.2. Getting User and Group Information on Unix

Problem

You need to discover information about a user or group, and you have a username or user ID or a group name or ID.

Solution

On Unix, user and group names correspond to numeric identifiers. Most system calls require numeric identifiers upon which to operate, but names are typically easier for people to remember. Therefore, most user interactions involve the use of names rather than numbers. The standard C runtime library provides several functions to map between names and numeric identifiers for both groups and users.

Discussion

Declarations for the functions and data types needed to map between names and numeric identifiers for users are in the header file pwd.h . Strictly speaking, mapping functions do not actually exist. Instead, one function provides the ability to look up user information using the user’s numeric identifier, and another function provides the ability to look up user information using the user’s name.

The function used to look up user information by numeric identifier has the following signature:

#include <sys/types.h>
#include <pwd.h>
   
struct passwd *getpwuid(uid_t uid);

The function used to look up user information by name has the following signature:

#include <sys/types.h>
#include <pwd.h>
   
struct passwd *getpwnam(const char *name);

Both functions return a pointer to a structure allocated internally by the runtime library. One side effect of this behavior is that successive calls replace the information from the ...

Get Secure Programming Cookbook for C and C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.