从请求中获取主机名

时间:2013-11-08 15:28:38

标签: java networking inetaddress

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

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

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

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

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

2 个答案:

答案 0 :(得分:6)

首先尝试

System.out.println("Host = " + request.getServerName());
System.out.println("Port = " + request.getServerPort());

如果不起作用

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

答案 1 :(得分:2)

您需要使用以下函数来获取远程地址/主机名:

request.getRemoteHost();
相关问题