我想在Java中找到客户端计算机名称。我的应用程序在Intranet中运行。所以我用下面的代码

   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;
    }


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

10-08 18:56