题
是否有可能获得当前登录的用户(在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?
和什么将第二个做的,如果你没有一个主机名设置?
解决方案
要获得当前登录的用户:
System.getProperty("user.name"); //platform independent
和机器的主机名:
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());
其他提示
要获得当前登录的用户:
System.getProperty("user.name");
要获得的机器的主机名:
InetAddress.getLocalHost().getHostName();
要回答你的问题的最后一部分,的的Java API 说的gethostname()将返回
此IP地址的主机名,或者如果操作没有被安全检查允许的,IP地址的文本表示。
使用user.name
是不安全的作为环境变量可以伪造。您正在使用的方法是好的,也有基于UNIX操作系统类似的方法,以及
要获得当前登录的用户路径:
System.getProperty("user.home");
不隶属于 StackOverflow