连接到有效的 ip 端口时抛出 UnknownHostException

UnknownHostException is thrown while connecting to a valid ip port

当我尝试连接到套接字时(有效 ip:port)随机抛出 UnknownHostException!

Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 1000);

我们的本地应用程序环境的/etc/resolve.conf配置了我们本地名称服务器的ipAddress,这个配置UnknownHostException是随机发生的(几乎在50:50比率).

但是当resolve.conf的条目被清除并留空时,就不会出现UnknownHostException,并且socket连接顺利建立。

我怎样才能解决这个问题,因为 resolve.conf 也不能留空!

OS: CentOS 7

通常您的 resolv.conf 文件由您的 DHCP 客户端填充。如果你看到这个文件的内容,它可能以

开头
; generated by /sbin/dhclient-script

不建议手动编辑此文件。此文件指向一个 DNS(或多个 DNS 服务器),如果您要使用 DNS 解析,则 DNS 中必须存在正确的映射。

在您的示例中,您没有提及 ipAddress 是什么类型的变量。您描述的行为表明您 ipAddress 变量是一个字符串。这将导致 InetSocketAddress 构造函数尝试主机名解析,这可能会导致您遇到的行为。

我的建议是:

  • 如果您打算使用 IP 地址,您应该确保 InetSocketAddress 接收到一个 java.net.InetAddress 对象。如果您查看此 API 页面,您会看到有 2 个属性可以修改主机名解析缓存的行为。
  • 如果您要在服务器中使用 ip/host 名称映射,另一种方法是编辑您的 /etc/hosts 文件以包含映射。

来自JavaAPI。这些是驱动主机名解析缓存行为的属性:

Two Java security properties control the TTL values used for positive and negative host name resolution caching:

networkaddress.cache.ttl Indicates the caching policy for successful name lookups from the name service. The value is specified as as integer to indicate the number of seconds to cache the successful lookup. The default setting is to cache for an implementation specific period of time. A value of -1 indicates "cache forever".

networkaddress.cache.negative.ttl (default: 10) Indicates the caching policy for un-successful name lookups from the name service. The value is specified as as integer to indicate the number of seconds to cache the failure for un-successful lookups. A value of 0 indicates "never cache". A value of -1 indicates "cache forever".

希望这对您有所帮助。