开发者

Objective C and OS user type

Is there any way to get currently logged in user type (root, admin or normal) through objective C?

I know about NSFullUserName() which gives user name, but how to retrie开发者_StackOverflowve user type?

Thanks.


You can retrieve the user group using getpwnam or getpwuid then use getgrgid to get the group name from the gid.

These are C functions in the standard library.

-- EDIT: Here is a short, poorly coded C example ---

Here is a small example, on mac os in the terminal it should build using make (if you name the file getpwnam_example.c you can do $ make getpwnam_example in the same directory as the c file).

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <strings.h>
#include <pwd.h>
#include <grp.h>

int main(int argc, char **argv) {

    uid_t current_user_id = getuid();
    printf("My Current UID is %d\n", current_user_id);

    struct passwd *pwentry = getpwuid(current_user_id);
    printf("My Current Name is %s\n", pwentry->pw_gecos);
    printf("My Current Group ID is %d\n", pwentry->pw_gid);

    struct group *grentry = getgrgid(getgid());
    printf("My Current Group Name is %s\n", grentry->gr_name);

    printf("Am I an admin? ");
    struct group *admin_group = getgrnam("admin");
    while(*admin_group->gr_mem != NULL) {
        if (strcmp(pwentry->pw_name, *admin_group->gr_mem) == 0) {
            printf("yes!\n");
        }
        admin_group->gr_mem++;
    }

    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜