Java network programming from getting started to mastering (4): DNS Caching

Source: Internet
Author: User

In the process of finding a domain name through DNS, it is possible to go through multiple intermediate DNS servers to find the specified domain name, so finding the domain name on the DNS server is a very expensive operation. In Java, the DNS cache is provided to alleviate this problem. when the InetAddress class first uses a domain name (such as www.csdn.net) to create the InetAddress object, the JVM saves the domain name and the information it obtains from DNS (such as the IP address) in the DNS cache. The next time the InetAddress class uses the domain name, it obtains the required information directly from the DNS cache without having to access the DNS server.

The DNS cache will always retain the domain name information that has been visited by default, but we can modify this default value. There are generally two ways to modify this default value:

1. set the value of the security attribute Networkaddress.cache.ttl (in seconds) in the program by using the Java.security.Security.setProperty method. The following code sets the cache timeout to 10 seconds:

Java.security.Security.setProperty ("Networkaddress.cache.ttl", 10);

2. Set the Networkaddress.cache.negative.ttl property in the Java.security file. Assuming that the JDK installation directory is C:\jdk1.6, the Java.security file is located in the C:\jdk1.6\jre\lib\security directory. Open this file, locate the Networkaddress.cache.ttl property, and set the property value to the corresponding cache timeout (in seconds).

If you set the Networkaddress.cache.ttl property value to 1, the DNS cache data will never be freed. The following code shows the effect of using and not using the DNS cache:

PackageMyNet;
Import java.net.*;
public class mydns {    public static void main (String[] args)  throws  exception     {        // args[0]:  Native name  args[1]: Buffer time         if  (ARGS.LENGTH < 2)             return;         java.security.security.setproperty ("Networkaddress.cache.ttl",  ARGS[1]);         long time = system.currenttimemillis ();         InetAddress addresses1[] =  Inetaddress.getallbyname (Args[0]);         system.out.println ("addresses1:   "                           + string.valueof (System.currenttimemillis ()  - time)                          +   "MS");         for  (INETADDRESS ADDRESS : ADDRESSES1)             SYSTEM.OUT.PRINTLN (address);         system.out.print ("Press any key to continue");         system.in.read ();         time = system.currenttimemillis ();         InetAddress addresses2[] =  Inetaddress.getallbyname (Args[0]);         system.out.println ("addresses2:   "                          + string.valueof (System.currenttimemillis ()  - time)                          +  "MS");         for  (Inetaddress address : addresses2)             SYSTEM.OUT.PRINTLN (address);     }}

The DNS cache timeout (via the args[1] parameter) is set in the preceding code, and the user can pass this value into Mydns via command line arguments. This program first uses Getallbyname to create an inetaddress array and then pauses the program through System.in.read. After the user waits for a period of time, you can press any key to continue, and use the same domain name (args[0]) to build a inetaddress array. If the user waits a little longer than the DNS cache timeout, the elements in the Addresses2 and addresses1 arrays are the same regardless of the situation, and the time it takes to create the Addresses2 array is typically 0 milliseconds (less than 1 milliseconds later, Java cannot get more precise time).

Test 1 :

Execute the following command (set the DNS cache timeout to 5 seconds):

Java mynet. Mydns www.126.com 5

Run result 1 (press any key within 5 seconds):

addresses1:344 Ms Www.126.com/202.108.9.77 Press any key to continue addresses2:0 milliseconds www.126.com/202.108.9.77

Run result 2 (press any key after 5 seconds):

addresses1:344 Ms Www.126.com/202.108.9.77 Press any key to continue addresses2:484 milliseconds www.126.com/202.108.9.77

There may be two running results in the above test. If after "Press any key to continue ..." After 5 seconds to press any key to continue, you will get the result of running 1, from this result can be seen, Addresses2 time is 0 milliseconds, that is, Addresses2 does not really access the DNS server, Instead, the data is obtained directly from the in-memory DNS cache. When you press any key after 5 seconds to continue, you get run result 2, at which time the data in the in-memory DNS cache is released, so Addresses2 has to access the DNS server again, so The addresses2 time is 484 milliseconds (the number of milliseconds after addresses1 and addresses2 may not be the same in different environments, but in general, the value of Addresses2 running result 1 is 0 or a number close to 0, such as 5. The value of the addresses2 that runs the result 2 is generally close to the value of addresses1, or a number far greater than 0, such as 1200).

Test 2 :

Execute the following command (ComputerName is the native computer name, and the DNS cache timeout is set to never expire [-1]):

Java mynet. Mydns ComputerName-1

Run the result (delete 192.168.18.20 before pressing any key to continue):

Addresses1:31 Ms myuniverse/192.168.18.10 myuniverse/192.168.18.20 Press any key to continue addresses2:0 milliseconds myuniverse/192.168.18.10 Myu niverse/192.168.18.20

As can be seen from the above test, the DNS cache is set to never expire, no matter how much time, after pressing any key, Addresses2 still gets two IP addresses (192.168.18.10 and 192.168.18.20), and the addresses2 time is 0 milliseconds, but at this point 192.168.18.20 has been removed. It is therefore possible to judge that Addresses2 is the data obtained from the DNS cache. If you run the following command and press any key after 5 seconds, Addresses2 will have only one IP address (192.168.18.10) left.  

Java mynet. Mydns ComputerName 5

If the domain name does not exist on the DNS server, the client throws a Unknownhostexception exception after a period of attempt (averaging 5 seconds). In order for the next time to access this domain name no longer wait, the DNS cache will also save this error message. That is, only the first time to access the wrong domain name of the attempt to make 5 or so, and then access the domain name will be directly thrown unknownhostexception exception, and no longer wait for 5 seconds,

Failure to access the domain name may be the reason that the domain name does not exist, it may be due to a DNS server or other hardware or software temporary failure, it is generally not possible to keep this domain error message. In Java, you can set the time to retain this information through the Networkaddress.cache.negative.ttl property. The default value for this property is 10 seconds. It can also be set through the Java.security.Security.setProperty method or the Java.security file. The following code demonstrates the use of the Networkaddress.cache.negative.ttl property:

PackageMyNet;
Import java.net.*;
Public class  mydns1 {    public static void main (String[] args)  throws  exception     {         Java.security.Security.setProperty ("Networkaddress.cache.negative.ttl",                           "5 ");         long time = 0;         try         {             time = system.currenttimemillis ();             inetaddress.getbyname ("www.ppp123.com" );                  catch  ( Exception e)          {            system.out.println (" Www.ppp123.com does not exist! address1:  "                             +  String.valueof (System.currenttimemillis ()  - time)                               +  "MS");         }         // Thread.Sleep (6000); //  delay 6 sec         try          {            time  = system.currenttimemillis ();             inetaddress.Getbyname ("www.ppp123.com");                  catch  ( Exception e)         {             system.out.println ("www.ppp123.com does not exist! address2: "                               + string.valueof (System.currenttimemillis ()  - time)                              +  "MS");         }     }}

In the code above, set the Networkaddress.cache.negative.ttl property value to 5 seconds. This program tests Address1 and ADDRESS2 access www.ppp123.com (This is a non-existent domain name, the reader can replace it with any non-existent domain name), how long it takes to throw the unknownhostexception exception.

Operation Result:

Www.ppp123.com does not exist! address1:4688 milliseconds www.ppp123.com not exist! Address2:0 ms

As we can see from the running results above, Address2 used 0 milliseconds to throw an exception, so It can be concluded that Address2 obtained the domain name www.ppp123.com inaccessible information from the DNS cache, so the unknowhostexception exception is thrown directly. If you remove the comment from the delay code in the above code, you might get the following result:

Www.ppp123.com does not exist! address1:4688 milliseconds www.ppp123.com not exist! address1:4420 ms

As can be seen from the results above, in the 6th second, the data in the DNS cache has been freed, so address2 still needs to access the DNS server to know that www.ppp123.com is an inaccessible domain name.  

There are two points to note when using the DNS cache:

1. You can set the value of the Networkaddress.cache.ttl property according to the actual situation. The value of this property is generally set to-1. However, if you are accessing a dynamically mapped domain name (such as a dynamic IP that maps a domain name to ADSL using a dynamic Domain Name service), it is possible that the client will get the same IP address when the IP address changes.

2. When setting the Networkaddress.cache.negative.ttl property value, it is best not to set it to 1, otherwise if a domain name because of a temporary failure to access, then the program again to access the domain name, even if the domain name returned to normal, the program can no longer access the domain name. Unless you run the program again.
Next: Java network programming from getting started to mastering (5): Obtaining a domain name using the GetHostName method of the InetAddress class

Java network programming from getting started to mastering (4): DNS Caching

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.