获取计算机名和日志用户名

时间:2022-11-09 23:22:50

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 Windows and Linux. What is the best way to do this?

我正在开发一个应用程序。其中一种方法需要捕获计算机名和登录到计算机上的用户,然后将这两种方法都显示给用户。我需要它在Windows和Linux上运行。最好的方法是什么?

6 个解决方案

#1


15  

Windows

窗户

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

您可以尝试使用GetComputerName和GetUserName,这里有一个例子:

#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

看:GetComputerName GetUserName

Linux

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:

使用gethostname获取计算机名(参见gethostname),使用getlogin_r获取登录用户名。您可以在getlogin_r的man页面查看更多信息。简单的用法如下:

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

#2


8  

On POSIX systems you can use the gethostname and getlogin functions, both declared in unistd.h.

在POSIX系统上,可以使用gethostname和getlogin函数,这两个函数都在unistd.h中声明。

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

Possible output:

可能的输出:

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

This seems safer than relying on environment variables which are not always present.

这似乎比依赖不总是存在的环境变量更安全。

I'm withdrawing that last statement because

我撤回最后一个声明是因为

  • the man page of getlogin actually discourages its usage in favour of getenv("LOGIN") and
  • getlogin的man页面实际上不鼓励使用getenv(“LOGIN”)和
  • the getlogin_r call in the above program fails with ENOTTY when I run the program from within Emacs instead of an interactive terminal while getenv("USER") would have worked in both situations.
  • 当我在Emacs中运行程序而不是交互式终端时,上面的getlogin_r调用失败了,而getenv(“用户”)在这两种情况下都能工作。

#3


7  

In Windows environment you can use getenv("COMPUTERNAME"), getenv("USERNAME")
In Linux - getenv("HOSTNAME"), getenv("USER")

在Windows环境中,您可以使用getenv(“COMPUTERNAME”)、getenv(“USERNAME”)、getenv(“HOSTNAME”)、getenv(“USER”)

See getenv reference

看到getenv参考

#4


7  

If you can use Boost, you can do this to easily get the host name:

如果您可以使用Boost,您可以这样做来轻松获取主机名:

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

#5


3  

Use gethostname() to get computer name, support both windows and linux.

使用gethostname()获取计算机名,支持windows和linux。

#6


3  

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.

关于Denis的回答,请注意Linux的getenv(“HOSTNAME”)可能并不总是有效,因为环境变量可能不会被导出到程序中。

Multi-platform C++ code example to fetch just the computer name (this is what worked for my Win7 and CentOS machines):

多平台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 (gethostbyname(temp, 512) == 0) { // success = 0, failure = -1
            computerName = temp;
        }
        delete []temp;
        temp = 0;
    }
#endif

#1


15  

Windows

窗户

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

您可以尝试使用GetComputerName和GetUserName,这里有一个例子:

#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

看:GetComputerName GetUserName

Linux

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:

使用gethostname获取计算机名(参见gethostname),使用getlogin_r获取登录用户名。您可以在getlogin_r的man页面查看更多信息。简单的用法如下:

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

#2


8  

On POSIX systems you can use the gethostname and getlogin functions, both declared in unistd.h.

在POSIX系统上,可以使用gethostname和getlogin函数,这两个函数都在unistd.h中声明。

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

Possible output:

可能的输出:

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

This seems safer than relying on environment variables which are not always present.

这似乎比依赖不总是存在的环境变量更安全。

I'm withdrawing that last statement because

我撤回最后一个声明是因为

  • the man page of getlogin actually discourages its usage in favour of getenv("LOGIN") and
  • getlogin的man页面实际上不鼓励使用getenv(“LOGIN”)和
  • the getlogin_r call in the above program fails with ENOTTY when I run the program from within Emacs instead of an interactive terminal while getenv("USER") would have worked in both situations.
  • 当我在Emacs中运行程序而不是交互式终端时,上面的getlogin_r调用失败了,而getenv(“用户”)在这两种情况下都能工作。

#3


7  

In Windows environment you can use getenv("COMPUTERNAME"), getenv("USERNAME")
In Linux - getenv("HOSTNAME"), getenv("USER")

在Windows环境中,您可以使用getenv(“COMPUTERNAME”)、getenv(“USERNAME”)、getenv(“HOSTNAME”)、getenv(“USER”)

See getenv reference

看到getenv参考

#4


7  

If you can use Boost, you can do this to easily get the host name:

如果您可以使用Boost,您可以这样做来轻松获取主机名:

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

#5


3  

Use gethostname() to get computer name, support both windows and linux.

使用gethostname()获取计算机名,支持windows和linux。

#6


3  

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.

关于Denis的回答,请注意Linux的getenv(“HOSTNAME”)可能并不总是有效,因为环境变量可能不会被导出到程序中。

Multi-platform C++ code example to fetch just the computer name (this is what worked for my Win7 and CentOS machines):

多平台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 (gethostbyname(temp, 512) == 0) { // success = 0, failure = -1
            computerName = temp;
        }
        delete []temp;
        temp = 0;
    }
#endif