H4cKL0rD
H4cKL0rD

Reputation: 5508

How can I get the username of the person executing my program?

How can I get the username of the process owner (the user who is executing my program) in C++?

Upvotes: 12

Views: 15354

Answers (5)

Michael F
Michael F

Reputation: 1409

On Mac OSX:

getenv("USER");

On Linux:

getenv("USERNAME");

Upvotes: 3

Andreas Bonini
Andreas Bonini

Reputation: 44832

Windows

GetUserName()

Example:

 char user_name[UNLEN+1];
 DWORD user_name_size = sizeof(user_name);
 if (GetUserName(user_name, &user_name_size))
     cout << "Your user name is: " << user_name << endl;
 else
     /* Handle error */

Linux

Look at getpwuid:

The getpwuid() function shall search the user database for an entry with a matching uid.

The getpwuid() function shall return a pointer to a struct passwd

The struct passwd will contain char *pw_name.

Use getuid to get the user id.

Upvotes: 31

Anders
Anders

Reputation: 101764

On windows, a thread can be impersonated, a process can not. To get the process owner you should call GetTokenInformation with the TokenUser infoclass on your process token, this will give you a SID, this SID can be converted to a username with LookupAccountSid. If you don't care about thread vs process, GetUserName() is fine.

Upvotes: 1

Notinlist
Notinlist

Reputation: 16650

It is not a C++ related question. You can find information (not 100% sure) in the environment variables when using UNIX like systems. You can also use the 'id' program on these systems.

In general, the fastest way is to make a platform-dependent kernel / API call.

On windows under cmd.exe the USERNAME environment variable holds the username (which is also informational not factual). Search in WINAPI documentation for precise.

Upvotes: 0

Graeme Perrow
Graeme Perrow

Reputation: 57278

This is specific to the operating system. On Windows, use GetUserName. On unix, use getuid.

Upvotes: 1

Related Questions