Get Computer Name and logged user name

前端 未结 6 1406
走了就别回头了
走了就别回头了 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:32

    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
    

提交回复
热议问题