Javaの現在のマシン名とログインしているユーザー? 質問する

Javaの現在のマシン名とログインしているユーザー? 質問する

現在ログインしているユーザーの名前 (Windows/Unix) とマシンのホスト名を取得することは可能ですか?

これは単なる静的環境クラスのプロパティであると想定しています。

ユーザー名でこれを見つけました

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

マシン名は次のようになります:

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

catch(Exception ex) {
    ...
}

最初のものは Windows 専用ですか?

ホスト名が設定されていない場合、2 番目のコマンドはどうなるでしょうか?

ベストアンサー1

現在ログインしているユーザーを取得するには:

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

マシンのホスト名:

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

おすすめ記事