O'Reilly logo

Secure Programming Cookbook for C and C++ by Matt Messier, John Viega

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required