How to print current user and system name on Unix?

Please, I am pleased to learn how to print the current username and system name on Unix.

#include <unistd.h> #include <fcntl.h> using namespace std; int main(int argc, char **argv) { //Print the current logged-in user / username. //Print the name of the system / computer name. return 0; } 

I would appreciate it if you could present a line of code or two as a demonstration. Thanks

+4
source share
3 answers

getuid() gets identifier not username. To get the username, you have to additionally use getpwuid() :

 struct passwd *passwd; passwd = getpwuid ( getuid()); printf("The Login Name is %s ", passwd->pw_name); 

Look it up

And to get the host name you can use the gethostname() function.

+3
source

User - getuid() (see also geteuid() ).

Machine Name - gethostname() .

This is pure C. I don’t know if there are other library calls in C ++ for this.

+5
source

You need to call uname , gethostname , getuid (and possibly getgid ) system calls , and to convert the numeric uid with getpwent .

+4
source

Source: https://habr.com/ru/post/1389223/


All Articles