Reputation: 6907
How does InetAddress work? How does it find an IP address of a hostname.
I understand we can use InetAddress in Java for DNS resolutions, but I would like to know how it works. How does it find a DNS server to resolve the address?
I recently saw a misconfigured cname
, which was not being resolved correctly by InetAddress. It was getting resolved intermittently, but failing most of the times. The dig
command succeeded on the same machine all the time. Although after fixing the configuration, InetAddress
worked consistently too. But I don't understand why it was succeeding intermittently before. Either it should have failed consistently or succeeded.
Upvotes: 0
Views: 4297
Reputation: 16185
If you were using InetAddress.getByName(String)
there are a couple of factors that can contribute to inconsistent results:
InetAddress.getAllByName(String)
,getaddrinfo
.What this function does is platform specific. On Linux with glibc, this is configured through gai.conf and nsswitch.conf. This consults many databases (almost always the /etc/hosts
file), before falling back to the dns
database. You can obtain a similar result with:
getent hosts <host_name>
Summarizing, what you obtained with dig
is just the last one of a long sequence of steps.
Upvotes: 0
Reputation: 2930
According to Javadoc, Java's InetAddress
class uses the machines network configuration as strategy to resolve a hostname.
From http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/net/InetAddress.java or https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/InetAddress.html (The InetAddress source):
Host Name Resolution Host name-to-IP address resolution is accomplished through the use of a combination of local machine configuration information and network naming services such as the Domain Name System (DNS) and Network Information Service(NIS). The particular naming services(s) being used is by default the local machine configured one. For any host name, its corresponding IP address is returned.
This means, that if there are multiple networks, or multiple DNS-servers configured for a single network, you may get varying results in resolution, because different hosts might apply different leniency towards fixing broken addresses.
As to why another application might succees more often depends on their resolution strategy.
Upvotes: 0