3

How do I get a user UID by username in Objective C/C in OS X? Currently I know how to get UID of user who launched app when I call this code:

uid_t uid = getuid();
NSLog(@"uid: %d", uid);

But I need to get the user's UID by username.

EDIT: Also tried:

struct passwd *ss = getpwnam("myusername");
NSLog(@"uid: %d", ss->pw_uid);

and it returns "502" which is correct. It's heppens in case when I run my application under "myusername".

If I run my app under root using the same code it returns "0" which is incorrect. I expect to receive "502" in both cases because I set parameter "myusername" in both cases.

Serge
  • 2,031
  • 3
  • 33
  • 56
  • 2
    Use `struct passwd`, `getpwnam()` & co. from POSIX ([docs](http://pubs.opengroup.org/onlinepubs/009695299/basedefs/pwd.h.html)). – The Paramagnetic Croissant Jun 17 '14 at 14:22
  • OS X is a UNIX, as @user3477950 said the usual POSIX APIs apply for this. – DarkDust Jun 17 '14 at 14:30
  • @DarkDust The OP knows this; he's already using `getuid()` :D – trojanfoe Jun 17 '14 at 14:31
  • EDITED topic with results – Serge Jun 17 '14 at 14:45
  • Hm, I just tried it myself and it does work correctly for me on Mavericks: it returns the UID of my account no matter whether I run the app as root or normal user. Which version of OS X are you using? – DarkDust Jun 17 '14 at 15:00
  • The same version as my system. And your short test app really queries `getpwnam` and _immediately_ outputs the result? Because if you do another query, [the result may be different](http://stackoverflow.com/questions/12664456/why-is-getpwnam-always-returning-root-information-in-a-function/12664749#12664749). If your test app really is as short as possible and produces the wrong result you might want to file a bug. – DarkDust Jun 18 '14 at 06:49
  • But, when used for another user-name than myself, would I get the uid too? must I run it as root for that purpose? – Motti Shneor Dec 28 '20 at 10:47
  • Could you please also specify what #import/#include should I use on MacOS-X to have getpwnam() ? – Motti Shneor Dec 28 '20 at 16:49

0 Answers0