Get GID Name
2002-12-01 15:38:16
Category: c:linux
Description: Convert a gid into its proper name, lists users in your group from /etc/group, and retrieves the passwd string.
Author: detour
Viewed: 2289
Rating: (3 votes)


/* getgrgid.c by detour@metalshell.com
 *
 * Convert a gid into its name, list all the users
 * in the same group, and retrieve the passwd string.
 *
 * http://www.metalshell.com/
 *
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <grp.h>
 
int main() {
    struct group* grp;
    gid_t gid;
    char** users;
    int x = 1;
 
    // Get the group id of whoever runs this.
    gid = getgid();
    printf("Group ID: %d\n", gid);
 
    // If NULL is returned there was an error
    if((grp = getgrgid(gid)) == NULL )
      return 1;
 
    // Your group name in char format
    printf("Group: %s\n", grp->gr_name );
 
    // List users in your group, from /etc/group
    printf("Users in your group\n");
    printf("-------------------\n");
 
    for( users = grp->gr_mem; *users != NULL; users++,++x )
      printf( "%d.  %s\n", x, *users );
 
    printf("-------------------\n");
 
    // Encrypted passwd as seen in /etc/passwd.
    if(strcmp(grp->gr_passwd,"x") == 0)
      printf("Password is protected by shadow file.\n");
    else
      printf("Password: %s\n", grp->gr_passwd);
 
    return 0;
}