gpt4 book ai didi

java - java 中的客户端计算机名称

转载 作者:行者123 更新时间:2023-11-30 06:37:03 24 4
gpt4 key购买 nike

我想在java中查找客户端计算机名称。我的应用程序在内联网中运行。所以我使用下面的代码

   public String findClientComputerName(HttpServletRequest request) {
String computerName = null;
String remoteAddress = request.getRemoteAddr();
System.out.println("remoteAddress: " + remoteAddress);
try {
InetAddress inetAddress = InetAddress.getByName(remoteAddress);
System.out.println("inetAddress: " + inetAddress);
computerName = inetAddress.getHostName();
System.out.println("computerName: " + computerName);
if (computerName.equalsIgnoreCase("localhost")) {
computerName = java.net.InetAddress.getLocalHost().getCanonicalHostName();
}
} catch (UnknownHostException e) {
log.error("UnknownHostException detected in StartAction. ", e);
}
if(StringUtils.trim(computerName).length()>0) computerName = computerName.toUpperCase();
System.out.println("computerName: " + computerName);
return computerName;
}

但有时我能正确获取主机名,但有时却不能。我得到了正确的IP。这可能是什么原因?为什么 inetAddress.getHostName(); 无法提供主机名?非常感谢您的帮助。

最佳答案

   private String getHostName (InetAddress inaHost) throws UnknownHostException
{
try
{
Class clazz = Class.forName("java.net.InetAddress");
Constructor[] constructors = clazz.getDeclaredConstructors();
constructors[0].setAccessible(true);
InetAddress ina = (InetAddress) constructors[0].newInstance();

Field[] fields = ina.getClass().getDeclaredFields();
for (Field field: fields)
{
if (field.getName().equals("nameService"))
{
field.setAccessible(true);
Method[] methods = field.get(null).getClass().getDeclaredMethods();
for (Method method: methods)
{
if (method.getName().equals("getHostByAddr"))
{
method.setAccessible(true);
return (String) method.invoke(field.get (null), inaHost.getAddress());
}
}
}
}
} catch (ClassNotFoundException cnfe) {
} catch (IllegalAccessException iae) {
} catch (InstantiationException ie) {
} catch (InvocationTargetException ite) {
throw (UnknownHostException) ite.getCause();
}
return null;
}

以上函数在内网中正确返回主机名。对于本地,它将返回 localhost。要获取本地主机的名称,我们使用 computerName = java.net.InetAddress.getLocalHost().getCanonicalHostName();

关于java - java 中的客户端计算机名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3993021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com