Capture Computer Name and User Name

8

I'm developing an application and in one of its methods I need to capture the name of the computer and the user logged in to the machine, then display the screen for the user. What is the best way to do this?

    
asked by anonymous 13.01.2015 / 04:20

2 answers

9

In Windows environment you can use getenv("COMPUTERNAME") , getenv("USER") .

In Linux - getenv("HOSTNAME") , getenv("USER") .

See also reference getenv .

    
13.01.2015 / 04:22
1

Complementing the above answer,

getenv() returns:

  • "A% of% with the value of the requested environment variable, or
  • "A null pointer if no environment variable exists."

C String sets the environment variable that stores the user name to $ USER, so to use the function in linux to get the current user name, make linux .

The getenv("USER") does not have a "USER" environment variable but rather, "USERNAME", which returns the same thing (the username), so to use the function in windows , make windows .

You can type "set" in a console / terminal / prompt window and see all environment variables currently configured in getenv("USERNAME") . There you should find "USERNAME" instead of "USER".

In%%, if you type "env" in the terminal, you will see that there is a "USER" variable, saving the current user name.

windows is set to linux Example:

#include <iostream>
#include <cstdlib>

int main(){
   /*Para obter o nome de usuário no linux*/
   #ifdef __linux__
      std::cout << "O nome do usuário atual é: " << getenv("USER") << std::endl;
   #endif
   /*Para obter o nome de usuário no windows*/
   #ifdef _WIN32
      std::cout << "O nome do usuário atual é: " << getenv("USERNAME") << std::endl; 
   #endif
}
    
19.11.2018 / 22:31