简体   繁体   中英

How does InetAddress find the IP of a given hostname?

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.

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.

If you were using InetAddress.getByName(String) there are a couple of factors that can contribute to inconsistent results:

  1. It returns only the first address from a call to InetAddress.getAllByName(String) ,
  2. Repeated queries for the same address are cached, even negative results,
  3. If a query is not in the cache, it is forwarded to the platform name resolution service. For both Windows and Unixes this results in a call to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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