从请求中获取主机名

GoA*_*ves 4 java networking inetaddress

我在Intranet上运行Windows Server 2008上的应用程序.

要登录应用程序,请尝试从请求中获取主机名以验证用户.但是,有时应用程序返回IP地址而不是名称,一段时间之后,没有做任何事情,应用程序能够解析名称,一切正常......

这是我用来获取主机名的代码:

InetAddress inaHost = InetAddress.getByName(request.getRemoteAddr());
String hostname = inaHost.getHostName();
System.out.println("[[ Hostname = " + hostname + " ]]");
Run Code Online (Sandbox Code Playgroud)

这是因为Intranet配置(DNS!?),还是我的代码,巫术或其他东西有问题?

con*_*ner 6

第一次尝试

System.out.println("Host = " + request.getServerName());
System.out.println("Port = " + request.getServerPort());
Run Code Online (Sandbox Code Playgroud)

如果不起作用

hostName == null;
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
{
  while (interfaces.hasMoreElements()) {
    NetworkInterface nic = interfaces.nextElement();
    Enumeration<InetAddress> addresses = nic.getInetAddresses();
    while (hostName == null && addresses.hasMoreElements()) {
      InetAddress address = addresses.nextElement();
      if (!address.isLoopbackAddress()) {
        hostName = address.getHostName();
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)