获取计算机名称和记录的用户名

时间:2015-01-13 03:07:56

标签: c++ linux windows

我正在开发一个应用程序。其中一种方法需要捕获计算机名称和登录计算机的用户,然后向用户显示。我需要它在Windows和Linux上运行。这样做的最佳方式是什么?

7 个答案:

答案 0 :(得分:21)

<强>窗

您可以尝试使用GetComputerNameGetUserName,这是一个示例:

#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 );

见:GetComputerName  和GetUserName

<强>的Linux

使用gethostname获取计算机名称(请参阅gethostname),使用getlogin_r获取登录用户名。您可以在man page of getlogin_r查看更多信息。 简单用法如下:

#include <unistd.h>
#include <limits.h>

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

答案 1 :(得分:11)

如果您可以使用Boost,则可以轻松获取主机名:

#include <boost/asio/ip/host_name.hpp>
// ... whatever ...
auto host_name = boost::asio::ip::host_name();

答案 2 :(得分:9)

Windows 环境中,您可以使用getenv("COMPUTERNAME")getenv("USERNAME")
Linux - getenv("HOSTNAME")getenv("USER")

请参阅getenv reference

答案 3 :(得分:9)

在POSIX系统上,您可以使用unistd.h中声明的gethostnamegetlogin函数。

/*
   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 <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

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;
}

可能的输出:

Hello 5gon12eder, you are logged in to example.com.

这似乎比依赖环境变量更安全。

我撤回了最后一个陈述,因为

  • getlogin的手册页实际上不鼓励使用getenv("LOGIN")
  • 当我从Emacs而不是交互式终端运行程序时,上述程序中的getlogin_r调用失败并显示ENOTTY,而getenv("USER")在两种情况下均有效。

答案 4 :(得分:3)

使用gethostname()获取计算机名称,同时支持windowslinux

答案 5 :(得分:3)

关于Denis的回答,请注意getenv("HOSTNAME") for Linux may not always work because the environment variables may not be exported to the program

用于获取计算机名称的多平台C ++代码示例(这适用于我的Win7和CentOS计算机):

    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

答案 6 :(得分:0)

在Linux中,您还可以使用Posix库使用以下内容来检索拥有该进程的真实用户: getuid()返回调用过程的真实用户ID。 参见getuid man page

#include <pwd.h>
string userName = "unknownUser";
// Structure to store user info
struct passwd p;
// Get user ID of the application
uid_t uid = getuid();

// Buffer that contains password additional information
char pwdBuffer[ourPwdBufferSize];
// Temporary structure for reentrant function
struct passwd* tempPwdPtr;

if ((getpwuid_r(uid, &p, pwdBuffer, sizeof(pwdBuffer),
        &tempPwdPtr)) == 0) {
    userName = p.pw_name;
}