简体   繁体   English

Java InetAddress名称解析

[英]Java InetAddress name resolution

I have the following question for all Java pundits out there. 对于所有Java专家,我都有以下问题。

I am trying to came up with a reliable way of creating an localHost InetAddress object as a fallback way to InetAddress.getLocalHost() . 我试图提出一种创建localHost InetAddress对象的可靠方法,作为对InetAddress.getLocalHost()的后备方法。

I am facing the following issue: 我面临以下问题:

There are cases where my Java application would not start due to an UnknownHostException being thrown, in case the network connection of the machine it runs from is down (deploying on Windows machines). 在某些情况下,我的Java应用程序由于抛出UnknownHostException而无法启动,以防它运行的计算机的网络连接断开(在Windows计算机上部署)。

So my ideas so far are the following: 因此,到目前为止,我的想法如下:

1) Either try to get the localHost InetAddress object from the NetworkInterfaces Enumeration (which I found a bit cumbersome). 1)尝试从NetworkInterfaces枚举中获取localHost InetAddress对象(我发现这有点麻烦)。

2) Try to get the local host name string via the System environment and then trying to create a InetAddress object by doing InetAddress.getByName() . 2)尝试通过系统环境获取本地主机名字符串,然后尝试通过执行InetAddress.getByName()创建一个InetAddress对象。

I strongly favor the second approach as it much easier and seems a bit sleeker, but I am still getting issues getting the InetAddress object I want, in case the network connection is down. 我强烈支持第二种方法,因为它更容易使用,而且看起来更时尚,但是在网络连接断开的情况下,获取所需的InetAddress对象仍然遇到问题。

Now my questions, are two: 现在我的问题是两个:

1) Given the fact that I maintain a hosts file within the said machine, that contains the machine's entry (hostname - IP Address) wouldn't it be possible for #2 to work as intended? 1)鉴于我在上述机器中维护一个主机文件,该文件包含机器的条目(主机名-IP地址),所以#2能否按预期工作? I know that eventually the DNS resolution will come down to the actual OS but shouldn't Windows be able to use their hosts file to do this even no network connection was available. 我知道最终DNS解析将取决于实际的操作系统,但即使没有网络连接,Windows也不能使用其主机文件来执行此操作。

2) Is there any way possible to create an InetAddress object given the host name of a machine but without this machine having an active network connection - interface being down (thus avoiding the UnkownHostException mentioned before)? 2)有没有办法在给定机器主机名的情况下创建一个InetAddress对象,但该机器没有活动的网络连接-接口关闭(因此避免了前面提到的UnkownHostException)?

1) It would work as intended provided that: 1)只要满足以下条件,它将按预期工作:

  • the local DNS resolver was configured to check the "hosts" file before external DNS servers, and 将本地DNS解析器配置为在外部DNS服务器之前检查“主机”文件,并且

  • the entry was correct, and it referred to a working IP address for the local host. 该输入是正确的,并且它引用了本地主机的有效IP地址。

An alternative is to use a loopback address (eg "localhost" / 127.0.0.1) 另一种选择是使用回送地址(例如“ localhost” / 127.0.0.1)

2) Sure. 2)当然。 Use InetAddress.getByAddress(String, byte[]) . 使用InetAddress.getByAddress(String, byte[]) Note that the name is not checked in DNS. 请注意,该名称未在DNS中检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM