Reputation: 120
When i try to connect to a socket (valid ip:port) UnknownHostException is thrown randomly!
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 1000);
Our local application environment's /etc/resolve.conf is configured with the ipAddress of our local nameserver, with this configuration UnknownHostException occurs randomly (almost in 50:50 ratio).
But when the resolve.conf's entries are cleared and left blank UnknownHostException never occurs, and the socket connection is smoothly established.
How can I be able to resolve this issue as it is not possible to leave the resolve.conf blank also!
OS: CentOS 7
Upvotes: 0
Views: 2343
Reputation: 794
Usually your resolv.conf file is populated by your DHCP client. If you see the content of this file, it may start with
; generated by /sbin/dhclient-script
It is not recommended to manually edit this file. This file points to a DNS (or multiple DNS servers) and if you are going to use DNS resolution then the correct mapping must exist in the DNS.
In your example you don't mention what type of variable is ipAddress. The behavior you describe indicates that you ipAddress variable is a string. Which will cause the InetSocketAddress constructor to attempt host name resolution which might cause the behavior you are experiencing.
My suggestions are:
From the Java API. These are the properties that drive host name resolution caching behavior:
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".
Hope this helps.
Upvotes: 1