Java 从请求中获取主机名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19862663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:48:16  来源:igfitidea点击:

Get hostname from request

javanetworkinginetaddress

提问by GoAlves

I'm running my application on Windows Server 2008 on an Intranet.

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

To login the application tries to get the hostname from the request to validate the user. However, sometimes the application returns the IP address instead of the name and some time later, without doing anything the application is able to resolve the name and everything works fine...

登录应用程序尝试从请求中获取主机名以验证用户。但是,有时应用程序返回 IP 地址而不是名称,一段时间后,应用程序无需执行任何操作即可解析名称,一切正常...

This is the code I'm using to get the hostname:

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

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

Is this because of the Intranet configuration (DNS!?), or is something wrong with my code, or witchcraft or something?

这是因为内网配置(DNS!?),还是我的代码有问题,或者巫术什么的?

采纳答案by constantlearner

First try

第一次尝试

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

if doesnt work

如果不起作用

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

回答by Pritam Banerjee

You will need to use the following function to get the remote address/hostname:

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

request.getRemoteHost();

回答by Catalan Cabbage

sometimes the application returns the IP address instead of the name

有时应用程序返回 IP 地址而不是名称

As referenced from this SO answer:

正如这个 SO 答案所引用的:

The issue could be since request.getRemoteHost() does a reverse DNS lookup instead of taking it from the HTTP headers; if it fails to look up the DNS information using the IP, it returns the IP address as a String.

问题可能是因为 request.getRemoteHost() 执行反向 DNS 查找而不是从 HTTP 标头中获取;如果它无法使用 IP 查找 DNS 信息,它会将 IP 地址作为字符串返回。