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
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 <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);
If you can use Boost, you can do this to easily get the host name:
#include <boost/asio/ip/host_name.hpp>
// ... whatever ...
const auto host_name = boost::asio::ip::host_name();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With