In a unix
environment it is usefull to be able to determine
what group a user is in when limiting access to certain functions, commands, or programs. The problem, however, is that the normal getgid()
functions only return the primary group
a person is a member of. This creates difficulties
if you want to add people to a group to give them special priveledges
while still running the same programs.
To solve this problem, the getgroups(int gidsetlen, gid_t *gidset) function is needed. The code below shows how to use this. Currently the example will set access = to 1 for anyone in group 0 (wheel) or leave access as zero for everyone else. It is set to check a maximum of 5 groups.
By changing the #defines you can easily make this code search for any group, and make it check more or less groups that a user is a member of, depending on how your system is setup.
/* Group to search for, and max groups to look at *
* with the user */
#define GROUP 0
#define MAX_GROUPS 5
/* Get the groups, then loop through to see if *
* desired group is present */
groups = getgroups(MAX_GROUPS, gidset);
for (i=0; i<=groups-1; i++)
if (gidset[i]==GROUP) access=1;
/* Also check if desired group is primary group *
* (then it doesn't show in getgroups) */
if (getegid()==GROUP) access=1;