[java] Java current machine name and logged in user?

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?

This question is related to java environment

The answer is


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


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.


To get the currently logged in user path:

System.getProperty("user.home");

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.


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.


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


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.


To get the currently logged in user path:

System.getProperty("user.home");