Get Computer Name and logged user name

前端 未结 6 1596
走了就别回头了
走了就别回头了 2021-02-07 01:59

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

6条回答
  •  無奈伤痛
    2021-02-07 02:19

    Windows

    You can try to use GetComputerName and GetUserName, here is a example:

    #define INFO_BUFFER_SIZE 32767
    TCHAR  infoBuf[INFO_BUFFER_SIZE];
    DWORD  bufCharCount = INFO_BUFFER_SIZE;
    
    // Get and display the name of the computer.
    if( !GetComputerName( infoBuf, &bufCharCount ) )
      printError( TEXT("GetComputerName") ); 
    _tprintf( TEXT("\nComputer name:      %s"), infoBuf ); 
    
    // Get and display the user name.
    if( !GetUserName( infoBuf, &bufCharCount ) )
      printError( TEXT("GetUserName") ); 
    _tprintf( TEXT("\nUser name:          %s"), infoBuf );
    

    see: GetComputerName and GetUserName

    Linux

    Use gethostname to get computer name(see gethostname), and getlogin_r to get login username. You can look more information at man page of getlogin_r. Simple usage as follows:

    #include 
    #include 
    
    char hostname[HOST_NAME_MAX];
    char username[LOGIN_NAME_MAX];
    gethostname(hostname, HOST_NAME_MAX);
    getlogin_r(username, LOGIN_NAME_MAX);
    

提交回复
热议问题