user1914520
user1914520

Reputation: 11

How to list all supplementary groups for unix user using c++

I am trying to find a way to get a list of all groups a unix user has access to. I want to be able to pass either the unix username or the uid of a user to a c++ program as an argument and then return a list of groups that this user has access to. I have done some reading about this and as far as I can see this can be achieved using getgroups() but I can't find an example of how to do this by passing in a particular username or uid to getgroups. All the examples I have found seem to just display all the groups for my user account or whoever is the effective uid of the person running the program. Please can you help me with how I can do this?

I can get all the user account info from struct passwd and am able to pass argv[1] which is a unix users username and pass this to getgrgid: (getpwnam_r(argv[1], my_passwd, pwdbuffer, pwdlinelen, &tempPwdPtr)) != 0) I just don't know how to use the value of argv[1] and find out all the groups a unix user has access to using getgroups

Upvotes: 1

Views: 1345

Answers (1)

anydot
anydot

Reputation: 1539

Use getgrouplist(3) function, it does exactly what you want. It expected username so if you want to list all the groups user with given UID is part of, you need first to translate UID to username with help of getpwuid_r(3) function.

Upvotes: 2

Related Questions