I am developing an application. One of the methods needs to capture the computer name and user logged on the machine, then display both to the user. I need it to run on both Win
On POSIX systems you can use the gethostname and getlogin functions, both declared in unistd.h
.
/*
This is a C program (I've seen the C++ tag too late). Converting
it to a pretty C++ program is left as an exercise to the reader.
*/
#include
#include
#include
#include
int
main()
{
char hostname[HOST_NAME_MAX];
char username[LOGIN_NAME_MAX];
int result;
result = gethostname(hostname, HOST_NAME_MAX);
if (result)
{
perror("gethostname");
return EXIT_FAILURE;
}
result = getlogin_r(username, LOGIN_NAME_MAX);
if (result)
{
perror("getlogin_r");
return EXIT_FAILURE;
}
result = printf("Hello %s, you are logged in to %s.\n",
username, hostname);
if (result < 0)
{
perror("printf");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Possible output:
Hello 5gon12eder, you are logged in to example.com.
This seems safer than relying on environment variables which are not always present.
I'm withdrawing that last statement because
getlogin
actually discourages its usage in favour of getenv("LOGIN")
andgetlogin_r
call in the above program fails with ENOTTY
when I run the program from within Emacs instead of an interactive terminal while getenv("USER")
would have worked in both situations.