Java当前机器名和登录用户?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/473446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java current machine name and logged in user?
提问by Omar Kooheji
Is it possible to get the name of the currently logged in user (Windows/Unix) and the hostname of the machine?
是否可以获取当前登录用户的名称(Windows/Unix)和机器的主机名?
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?
第一个只适用于 Windows 吗?
And what will the second one do, if you don't have a hostname set?
如果您没有设置主机名,第二个会做什么?
采纳答案by cordellcp3
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());
回答by Bill the Lizard
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 APIsays that getHostName() will return
为了回答问题的最后一部分,Java API说 getHostName() 将返回
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.
此 IP 地址的主机名,或者如果安全检查不允许操作,则为 IP 地址的文本表示。
回答by phoenix
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
使用user.name
不安全,因为可以伪造环境变量。您使用的方法很好,基于 unix 的操作系统也有类似的方法
回答by Swapnil1156035
To get the currently logged in user path:
获取当前登录的用户路径:
System.getProperty("user.home");