Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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?

1 Answer

0 votes
by (46k points)

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());

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
3 answers
0 votes
1 answer
0 votes
1 answer

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...