我正在开发一个应用程序。其中一种方法需要捕获计算机名称和登录到计算机上的用户,然后将两者都显示给用户。我需要它在Windows和Linux上都能运行。做这件事最好的方法是什么?
发布于 2015-01-13 11:16:03
Windows
您可以尝试使用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 );
请参阅: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);
发布于 2017-05-24 16:18:16
如果您可以使用Boost,则可以轻松获取主机名:
#include <boost/asio/ip/host_name.hpp>
// ... whatever ...
const auto host_name = boost::asio::ip::host_name();
https://stackoverflow.com/questions/27914311
复制相似问题