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?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
Regarding Denis's answer, note that
getenv("HOSTNAME")
for Linux may not always work because the environment variables may not be exported to the program.Multi-platform C++ code example to fetch just the computer name (this is what worked for my Win7 and CentOS machines):
If you can use Boost, you can do this to easily get the host name:
On POSIX systems you can use the
gethostname
andgetlogin
functions, both declared inunistd.h
.Possible output:
This seems safer than relying on environment variables which are not always present.I'm withdrawing that last statement because
getlogin
actually discourages its usage in favour ofgetenv("LOGIN")
andgetlogin_r
call in the above program fails withENOTTY
when I run the program from within Emacs instead of an interactive terminal whilegetenv("USER")
would have worked in both situations.Use
gethostname()
to get computer name, support both windows and linux.Windows
You can try to use
GetComputerName
andGetUserName
, here is a example:see: GetComputerName and GetUserName
Linux
Use
gethostname
to get computer name(see gethostname), andgetlogin_r
to get login username. You can look more information at man page of getlogin_r. Simple usage as follows:in Linux you can also use the following using Posix library to retrieve the real user that owns the process: getuid() returns the real user ID of the calling process. see getuid man page