Android Development of InetAddress Basic Introduction and Source Code Examples

  • 2021-11-29 08:23:52
  • OfStack

Recently, when learning soket programming, I saw the need to get IP address, so I went to see how to get IP address of host name.

In fact, a class InetAddress is needed. He is under the java. net package.

Objects of the InetAddress class are used for IP addresses and domain names, and the class provides the following methods:

getByName (String s): Obtains an InetAddress object containing the host's IP address and domain name, which represents the information it contains in the following format: www. sina. com. cn/202. 108. 37.40;

String getHostName (): Gets the domain name of the InetAddress object;

String getHostAddress (): Gets the IP address of the InetAddress object;

getLocalHost (): Get an InetAddress object that contains the domain name and IP address of the local machine.


private void test() {
    try {
      InetAddress locAdd = InetAddress.getLocalHost(); // Get local InetAddress Object 
      /* get www.baidu.com's ip */
      InetAddress remAdd = InetAddress.getByName("www.baidu.com"); // Get remote InetAddress Object 
      System.out.println(" Native machine IP Address: " + locAdd.getHostAddress()); // Get local IP Address 
      System.out.println(" Baidu IP Address: " + remAdd.getHostAddress()); // Get Baidu IP Address 
      System.out.println(" Can this machine reach: " + locAdd.isReachable(10000)); //10000 Is a timeout, 10s
      /*
         Print: 
         Native machine IP Address: 192.168.1.109
         Baidu IP Address: 115.239.210.26
         Can this machine reach: true
      */
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

In many cases, there may be more than one host IP corresponding to a domain name 1, and we can also take it back at 11. As follows:


private void test2() {
    try {
      /*  Baidu may have multiple IP Address, parsed back, so we can use 1 The number is assembled  */
      InetAddress[] addrs = InetAddress.getAllByName("www.baidu.com");
      if (addrs != null && addrs.length > 0) {
        for (InetAddress addr : addrs) {
          System.out.println("--->" + addr.getHostAddress());
        }
      }
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
  }

The IP address is a 32-bit (IPv4) or 128-bit (IPv6) unsigned number used by IP and is the basis of the transport layer protocols TCP and UDP. InetAddress is the encapsulation of IP address by Java, and many classes in java. net use InetAddress, including ServerSocket, Socket, DatagramSocket and so on.

The instance object of InetAddress contains the address of IP stored in numeric form, and may also contain the host name (if the host name is used to get an instance of InetAddress, or if it is constructed in numeric form and reverse host name resolution is enabled). The InetAddress class provides a way to resolve a host name to an IP address (or vice versa).

InetAddress resolves domain names using local machine configuration or network naming services such as Domain Name System (Domain Name System, DNS) and Network Information Service (Network Information Service, NIS).

For DNS, the local needs to send a query request to the DNS server, and then the server returns the corresponding IP address according to a series of operations. In order to improve efficiency, the local usually caches the mapping of 1 host name and IP address, so that accessing the same address does not need to send DNS requests repeatedly.

This strategy is also used in the java. net. InetAddress classes. By default, a finite-time map is cached, and for unsuccessful hostname resolution, a very short time (10 seconds) is cached to improve performance.

Class InetAddress

This class represents the ip address, followed by two subclasses, Inet4Address and Inet6Address, which represent the IPV4 and IPV6 addresses, respectively

This class has no constructor and can get an instance of InetAddress through its two static methods

> getByName (String host) gets the corresponding InetAddress object based on the host name

When you create an InetAddress object using an IP address (getByName, getAllByName, and getByAddress methods can all create an InetAddress object from an IP address), you do not need to access an DNS server. Therefore, the getHostName method does the job of finding the domain name through the DNS server.

If the IP address does not exist or the DNS server does not allow IP address and domain name mapping, this IP address is returned.

InetAddress address=InetAddress.getByName("141.146.8.66");

System. out. println (address. getHostName ()); //You need to access the DNS server to get the domain name

InetAddress address = InetAddress. getByName ("1.2. 3.4"); //IP address does not exist

System. out. println (address. getHostName ()); //Return directly to the IP address

The InetAddress object obtained by using the domain name as the parameter of getByName and getAllByName methods will get the domain name. When calling getHostName, you don't need to visit the DNS server again, but directly return the domain name.

InetAddress address=InetAddress.getByName("www.ofstack.com");

System. out. println (address. getHostName ()); //You don't need to access the DNS server to get the domain name


try {
	InetAddress address = InetAddress.getByName("www.ofstack.com");
	System.out.println(address);//www.ofstack.com/119.75.218.70
} catch (UnknownHostException e) {
	e.printStackTrace();
}

> getByAddress (byte [] addr) gets the InetAddress object from the source ip address


InetAddress address;
try {
	address= InetAddress.getByAddress(new byte[]{119,75,218,70});
	System.out.println(address);// The output is: /119.75.218.70 And string str Phase 1 To 
	address = InetAddress.getByAddress("www.ofstack.com", ipBuf);
	System.out.println(address);// The output is www.ofstack.com/119.75.218.70
} catch (UnknownHostException e) {
	e.printStackTrace();
}

> InetAddress. getLocalHost () Gets the host name of the ip address of this machine


try {
	InetAddress a = InetAddress.getLocalHost();
	System.out.println(a);// Native user name -PC/ Native machine Ip
} catch (UnknownHostException e) {
	e.printStackTrace();
}

Several other methods commonly used by this class:


try {
	InetAddress address=InetAddress.getLocalHost();
	System.out.println(address.getHostAddress());// Output ip String 
	System.out.println(address.getHostName());// Output user name 
	System.out.println(address.getCanonicalHostName());// Output the host name of this machine . Domain name with authority (lan)
} catch (UnknownHostException e) {			
	e.printStackTrace();		
}

getCanonicalHostName () method

Definition: public String getCanonicalHostName ()

This method, like getHostName method 1, also obtains the domain name of the remote host. The difference is that this method gets the host name and getHostName gets the host alias.

1. Create an InetAddress object using getLocalHost ()

In this case, the getCanonicalHostName method and the getHostName method both get the native name

2. Create an InetAddress object using a domain name

After an InetAddress object is created with a domain name, the getHostName method does not access the DNS server

However, the getCanonicalHostName method is not fixed, depending on how the DNS server interprets the host name and host alias

3. Create an InetAddress object using an IP address

The getCanonicalHostName method is identical to the getHostName method and returns the host name instead of the host alias.

Host aliases are used because sometimes host names can be complex, such as the host name bigip-otn-portal. oracle. com on the official website of Oracle, so simpler host aliases, such as www. oracle. com, are added to make it easier for users to access the website

This article mainly introduces Android InetAddress basic introduction and source code example, more about Android development skills please see the following links


Related articles: