views:

4188

answers:

4

Is is 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 2nd one do if you dont have a hostname set?

A: 

Found machine name in a cached page on google which doesn't appear to be there anymore:

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

catch(Exception ex) {
    ...
}

Originally from here Does anyone know if this will return the host ip if the machine doesn't have a name?

Still looking for current user.

Omar Kooheji
+15  A: 

To get the currently logged in user:

System.getProperty("user.name");

and the hostname of the machine:

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

regards, cordell

cordellcp3
+6  A: 

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.

Bill the Lizard
A: 

InetAddress.getLocalHost().getHostAddress() will display host address But this displays server address where applicaiton is installed. But not client name. How to get this?

vishnu