About InetAddress getting IP in Java cannot be used normally

Hits: 0

First, let’s look at the problem

import java.net.*; 
public class person {
   public static void main(String args[]) {
      try{  InetAddress address_1=InetAddress.getByName("www.baidu.com");
           System.out.println(address_1); 
           InetAddress address_2=InetAddress.getByName("14.215.177.39");
           System.out.println(address_2.getHostName());
      }
      catch(UnknownHostException e) {System.out 
           .println ( "Cannot find www.sina.com.cn" );
      } 
   }
}

Our thoughts are that we should output:
www.baidu.com/14.215.177.39
www.baidu.com/14.215.177.39

But the actual situation is:
www.baidu.com/14.215.177.39
14.215.177.39

There are mainly 2 situations that will cause the result to not be output correctly

1: Timeout, if the program cannot obtain the hostname immediately, it will continue to try for a period of time. After a certain period of time, it will be marked as failed, and then the textual representation of the IP address will be returned.

Two: The hostname of this IP address; if the security check does not allow the operation, the textual representation of the IP address is returned. Now most of them do not allow to obtain the host domain name through IP address return

The same is true for the getHostName() function, which should get the domain name contained in the object, but because of the above reasons, it often returns the text representation of the IP address.

You may also like...

Leave a Reply

Your email address will not be published.