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
Regarding Denis's answer, note that getenv("HOSTNAME")
for Linux may not always work because the environment variables may not be exported to the program.
Multi-platform C++ code example to fetch just the computer name (this is what worked for my Win7 and CentOS machines):
char *temp = 0;
std::string computerName;
#if defined(WIN32) || defined(_WIN32) || defined(_WIN64)
temp = getenv("COMPUTERNAME");
if (temp != 0) {
computerName = temp;
temp = 0;
}
#else
temp = getenv("HOSTNAME");
if (temp != 0) {
computerName = temp;
temp = 0;
} else {
temp = new char[512];
if (gethostname(temp, 512) == 0) { // success = 0, failure = -1
computerName = temp;
}
delete []temp;
temp = 0;
}
#endif