Java current machine name and logged in user?

JavaEnvironment

Java Problem Overview


Is it possible to get the name of the currently logged in user (Windows/Unix) and the hostname of the machine?

I assume it's just a property of some static environment class.

I've found this for the user name

com.sun.security.auth.module.NTSystem NTSystem = new
        com.sun.security.auth.module.NTSystem();
System.out.println(NTSystem.getName());

and this for the machine name:

import java.net.InetAddress;
...
String computerName;
...
try {
    computerName = InetAddress.getLocalHost().getHostName();
}

catch(Exception ex) {
    ...
}

Is the first one just for Windows?

And what will the second one do, if you don't have a hostname set?

Java Solutions


Solution 1 - Java

To get the currently logged in user:

System.getProperty("user.name"); //platform independent 

and the hostname of the machine:

java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());

Solution 2 - Java

To get the currently logged in user:

System.getProperty("user.name");

To get the host name of the machine:

InetAddress.getLocalHost().getHostName();

To answer the last part of your question, the Java API says that getHostName() will return

> the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.

Solution 3 - Java

Using user.name is not secure as environment variables can be faked. Method you were using is good, there are similar methods for unix based OS as well

Solution 4 - Java

To get the currently logged in user path:

System.getProperty("user.home");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOmar KoohejiView Question on Stackoverflow
Solution 1 - Javacordellcp3View Answer on Stackoverflow
Solution 2 - JavaBill the LizardView Answer on Stackoverflow
Solution 3 - JavaphoenixView Answer on Stackoverflow
Solution 4 - JavaSwapnil1156035View Answer on Stackoverflow