Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Computer Name and logged user name

Tags:

c++

linux

windows

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?

like image 493
Mrdk Avatar asked Sep 01 '25 01:09

Mrdk


2 Answers

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);
like image 159
pezy Avatar answered Sep 02 '25 16:09

pezy


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();
like image 25
Vivit Avatar answered Sep 02 '25 15:09

Vivit