#include #include #include #include #include #include #include #include #include /* Compile with: * cc -W -Wall -O2 -s -pipe -o getpeercred getpeercred.c */ const char *help = "getpeercred [-hn]\n" \ "Prints the name of the user connected to the local unix stream socket on\n" \ "file descriptor 0, 1, or 2 (stdin, stdout, or stderr, in that order).\n" \ "Prints the uid of that user if -n is given as commandline parameter."; int main (int argc, char* argv[]) { int flag, numeric_flag = 0, fd; struct xucred cred; socklen_t len; struct passwd *pw; while ((flag = getopt(argc, argv, "hn")) != -1) { switch (flag) { case 'h': puts(help); return 0; case 'n': numeric_flag = 1; break; default: errx(1, "See -h for help"); } } for (fd = 0; fd < 3; fd++) { len = sizeof(cred); if (getsockopt(fd, SOL_LOCAL, LOCAL_PEERCRED, &cred, &len) == 0) break; } if (fd >= 3) return -1; if (numeric_flag) { printf("%u\n", cred.cr_uid); } else { errno = 0; pw = getpwuid(cred.cr_uid); if (pw != NULL) printf("%s\n", pw->pw_name); else if (errno != 0) err(1, "UID %u", cred.cr_uid); else errx(1, "UID %u does not exist", cred.cr_uid); } return 0; }