Although the socket class has the settimeout () method, URLConnection has the Setconnecttimeout () method, but this does not add a time limit to the DNS query process, that is, if the DNS server is hung, Then the code blocks for a few 10 seconds to throw an exception. I recently encountered this problem, when the DNS server problem, SetTimeout () Set the timeout time will not work.
After Google, we found that Java currently does not have a ready-made API to handle the DNS query timeout problem. However, a foreigner's blog has given a way to the salvation of the curve:
public class Dnslookupthread extends Thread {private inetaddress addr;private String hostname;public dnslookupthread ( String hostname) {this.hostname = hostname;} public void Run () {try {inetaddress add = inetaddress.getbyname (hostname); set (add);} catch (Unknownhostexception e) {}}PR Ivate synchronized void set (InetAddress addr) {this.addr = addr;} Public synchronized String GetIP () {if (null! = this.addr) {return addr.gethostaddress ();} return null;}}
The following methods are used for the class:
DnsQuery dnsth = new DnsQuery ();d Nsth.start ();d Nsth.join (2000); System.out.println (Dnsth.get ())
The effect of the above code is equivalent to adding a 2-second time-out limit to the DNS query.
A simple analysis of how to do it:
The DNS thread executes the Inetaddress.getbyname () method to initiate a query request to DNS, at which point the main thread does not continue because the network Io,dns thread is blocked, but because the main thread calls the join. There are 2 scenarios:
1. Network IO completes, the DNS thread continues execution, the Getbyname () method returns, and the InetAddress object containing the target host IP is saved to the member variable.
2. Network IO is not completed, but 2 seconds has past, the main thread's join () call returns, the main thread continues execution, but getip () returns NULL, which means the DNS query failed.
This perfectly solves the DNS query timeout problem.
Add time-out Limit functionality for Inetaddress.getbyname () DNS queries by thread skillfully