How to print the current user and system name in Unix? - c++

Please i am looking forward to learn how to print the current logged-in user and system name in Unix.
#include <unistd.h>
#include <fcntl.h>
using namespace std;
int main(int argc, char **argv)
{
//Print the current logged-in user / username.
//Print the name of the system / computer name.
return 0;
}
I would be grateful if you can provide a line of code or two as demonstration. Thanks

User --> getuid() (see also geteuid()).
Machine name --> gethostname().
That is pure C. I don't know whether C++ has other library calls for that.

You need to call the uname, gethostname, getuid (and perhaps getgid) system calls, and to convert the numerical uid with getpwent function.

getuid() gets the id not the username. To get the username you'll have to additionally use getpwuid():
struct passwd *passwd;
passwd = getpwuid ( getuid());
printf("The Login Name is %s ", passwd->pw_name);
See it
And for getting the hostname you can use the gethostname() function.

Related

How do I get username and appname for file path

How am I able to define a path like "C:/Users/<USER>/AppData/Local/<APPNAME>", for different username and app? How do I set this to automatically get the user and the appname? Thank you.
You can use SHGetKnownFolderPath to get the full path of App Local:
...
#include <KnownFolders.h>
#include <ShlObj.h>
...
SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_SIMPLE_IDLIST, NULL, &path); // NULL for current user
...
To get the Local AppData path for a given user, use SHGetFolderPath() specifying CSIDL_LOCAL_APPDATA, or SHGetKnownFolderPath() specifying FOLDERID_LocalAppData. Both take an optional user token for the desired user account to query. If you don't provide a token, the user associated with the calling thread is used.
To get the username:
char username[MAX_PATH];
DWORD size = MAX_PATH;
GetUserName(username,&size);
To get the appname(Executable File Name without ".exe"):
char appname[MAX_PATH];
char buffer[MAX_PATH];
GetModuleFileName(NULL, appname,MAX_PATH); //get the string: "PATH\\appname.exe"
char *szExe = NULL;
//Remove prefix
GetFullPathName(appname, MAX_PATH, buffer, &szExe);
//Remove suffix
strncpy_s(appname, szExe, strlen(szExe) - strlen(".exe"));

How to get running application name in UWP?

I have a C++ dll that is used by different UWP apps. Inside my dll I want to get the name of the running app. Standard winapi functions seem to not work, because they return exe names of some "wrappers" (e.g. ApplicationFrameHost.exe...).
ITNOA
As you can see [UWP]How to get running application name in UWP?, Azat Tazayan says you can like below to retrieve name
Package^ package = Package::Current;
PackageId^ packageId = package->Id;
String^ name= packageId->Name ;
But the above code is just return name of Package, if your exe file name is different with package name, above code is return incorrect name.
So you must use some code like below (based on How do I get the name of the current executable in C#?)
char filename[MAX_PATH];
DWORD size = GetModuleFileNameA(nullptr, filename, MAX_PATH);
std::reverse_iterator<char*> it = std::find_if(std::rbegin(filename), std::rend(filename), [](const char c) { return c == '\\'; });
const std::string exeName(it.base());

Steamworks checking if a user is logged in

So the code that I've been using to get a user's Steam ID is:
CSteamID uid = SteamUser()->GetSteamID();
uint64 pid = uid.ConvertToUint64();
std::ostringstream sin;
sin << pid;
std::string s = sin.str();
return s.c_str();
This works just fine, but when a user is not logged into Steam, this crashes.
Access violation - code c0000005 (first/second chance not available)
Does Steam provide a function that I can use to check if the user is logged in before running code that depends on the user being logged in? Or is there some sort of try/catch block I can use here to make sure that this does not break and return false if the user is not logged in?
Thanks to #Lightning Racis in Orbit. A simple nullptr check fixed it.
if(SteamUser() == nullptr)
return false;

Get logged on user's name or email on Windows 8 using C++ and WinAPIs

On Windows 7 to retrieve the name of a logged on user I can do this:
LPTSTR pUserName = NULL;
DWORD dwcbSzUserName = 0;
//'dwSessID' = user session ID
if(WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, dwSessID, WTSUserName, &pUserName, &dwcbSzUserName))
{
//Got user name in 'pUserName'
}
if(pUserName)
WTSFreeMemory(pUserName);
But on Windows 8 it returns some abbreviated name, for instance, "john_000" when the actual user's name is "John A. Doe".
So what is the way to retrieve the name of the logged on user (and possibly their email) on Windows 8 with C++ using WinAPIs as it's shown at log-on screen?
You could try NetUserGetInfo with USER_INFO_23 to get full name.
Something basically like:
//Got user name in 'pUserName'
NetUserGetInfo(NULL, pUserName, 23, my_USER_INFO_23);
//Got display name in my_USER_INFO_23.usri23_full_name

Check if process user is an administrator c++

I want to get the process's user name and check if it is a local administrator . Or check directly if the current procees user is a local administrator
Get the current username with GetUserName(), then call NetUserGetInfo() with the server name (NULL for local) and username you just got. Pass it a USER_INFO_1 structure, and then access usri1_priv in the structure. If the value is USER_PRIV_ADMIN, then you'll know that the username is an admin.
Tested on Windows XP SP3, Windows 7 32 bit and 64 bit with admin user and non-admin user.
Code ported from equivalent C# and uses ATL windows security wrapper classes.
#include <atlbase.h>
#include <atlsecurity.h>
// The function returns true if the user who is running the
// application is a member of the Administrators group,
// which does not necessarily mean the process has admin privileges.
bool IsAdministrator(HRESULT &rHr)
{
bool bIsAdmin = false;
try
{
// Open the access token of the current process.
ATL::CAccessToken aToken;
if (!aToken.GetProcessToken(TOKEN_QUERY))
{
throw MAKE_SCODE(SEVERITY_ERROR, FACILITY_WIN32,
::GetLastError());
}
// Query for the access token's group information.
ATL::CTokenGroups groups;
if (!aToken.GetGroups(&groups))
{
throw MAKE_SCODE(SEVERITY_ERROR, FACILITY_WIN32,
::GetLastError());
}
// Iterate through the access token's groups
// looking for a match against the builtin admins group.
ATL::CSid::CSidArray groupSids;
ATL::CAtlArray<DWORD> groupAttribs;
groups.GetSidsAndAttributes(&groupSids, &groupAttribs);
for (UINT i = 0; !bIsAdmin && i < groupSids.GetCount(); ++i)
{
bIsAdmin = groupSids.GetAt(i) == ATL::Sids::Admins();
}
rHr = S_OK;
}
catch (HRESULT hr)
{
rHr = hr;
}
return bIsAdmin;
}
Presuming you're on a Window OS there's a shell function: IsUserAnAdmin
See MSDN article
This article does suggest rolling your own function though, use CheckTokenMembership. There is even a code example to help you along.