How to find out %COMPUTERNAME% and %USERNAME% ??

124 views (last 30 days)
David
David on 1 Sep 2011
Commented: Walter Roberson on 7 Jan 2017
What the title says.
How do I find out on which machine (computer) MATLAB is running? (Windows CMD variable %COMPUTERNAME%)
How do I find out the name of the user who is logged in? (Windows CMD variable %USERNAME%)
The Matlab help is of no use since none of the search terms "user name", "machine name" and "hostname" lead me to anything useful...
many thanks in advance!

Answers (5)

Daniel Shub
Daniel Shub on 1 Sep 2011
With java you can do this in an OS independent manner:
char(java.lang.System.getProperty('user.name'));
char(java.net.InetAddress.getLocalHost.getHostName);
  1 Comment
Alec Jacobson
Alec Jacobson on 7 Jan 2017
Unlike the genenv solutions above, this does work on Mac OS X.

Sign in to comment.


Ken Atwell
Ken Atwell on 1 Sep 2011
GETENV is a somewhat more "graceful" way to do this:
getenv('COMPUTERNAME')

Fangjun Jiang
Fangjun Jiang on 1 Sep 2011
or
getenv('username')
getenv('computername')
  2 Comments
Walter Roberson
Walter Roberson on 7 Jan 2017
This works fine on osx: it gives back the empty string in both cases, which is exactly what is appropriate when asked to provide system specific information. The question was not about how to fetch the username and computer name on Windows, it was about how to access those particular variables.
The osx equivalent variables are USER and HOSTNAME . USER should be available on on shells, but HOSTNAME might not be available if you have reconfigured the default system shell to csh or you dug out an old sh source somewhere and compiled that and made it your default system shell. Posix does not mandate that the environment variable exists... but the default shell for osx does define it.
I am not sure what the default shell is for the various Linux systems. I am sure it is not csh, but I cannot promise it is ksh or bash instead of sh.... Posix does mandate some shell features that were in ksh but not in sh, but that doesn't matter to Linux systems because Linux is not Posix.

Sign in to comment.


David
David on 1 Sep 2011
Ooooh never mind I found the answer...
>> [s,computername] = dos('ECHO %COMPUTERNAME%')
s =
0
computername =
VARESE
>> [s,username] = dos('ECHO %USERNAME%')
s =
0
username =
myusername
:)

David
David on 1 Sep 2011
Thanks for the tips! getenv seems like just the thing I was looking for. (All comps are Windows, software won't be shipped out any time soon...)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!