InetAddress Example Java

InetAddress Example Java

Getting URL from URN

As the name indicates, the InetAddress of package refers a Web server address in Internet. We know earlier, URN (Universal Resource Name) is easier to remember than URL (Universal Resource Locator). With InetAddress, we can get a lot of information of a Web server. In the following program, when URN is supplied, InetAddress class returns the URL.

InetAddress Example Java

InetAddress Example Java
Screenshot on InetAddress Example Java

Note: To execute the above program, see your system is connected to Internet.

InetAddress ia1 = InetAddress.getByName("");

The InetAddress class includes a method getByName(). This method returns the URL when URN is passed as parameter. Observe the screenshot, the IP address is

As there does not exist a Web server by name (not in the list of DNS (Domain Naming Service) authority), it throws UnknownHostException, a checked exception.

All By Name – Getting multiple IP Numbers for an URN

To take the load of multiple clients, a group of servers, with different URLs, is given a common name. Using getAllByName() method of InetAddress, the list of IP addresses of the Web server can be obtained. In the following program, the two URLs referred by are obtained.

Screenshot of

InetAddress add[] = InetAddress.getAllByName("");

The above statement returns two IP addresses referring Replace with, you get five addresses. The static method getAllByName() throws a checked exception, UnknownHostException.

Who Am I – Getting Other System Data

InetAddress class is useful to know the local system (where the programming is getting executed) address as a URN and URL.

Screenshot of

InetAddress local = InetAddress.getLocalHost();

The InetAddress class does not have any constructors. For this reason, in all the programs, we obtained an object of InetAddress by using some of its static methods like getByName() and getAllByName(). Now, getLocalHost() method returns an object of InetAddress.

System.out.println(“URN: ” + add.getHostName());
System.out.println(“URL: ” + add.getHostAddress());

The InetAddress class comes with many getXXX() methods with which the particulars of a system can be obtained. Now, the methods getHostName() and getHostAddress() return the system address as URN and URL.

Leave a Reply

Your email address will not be published. Required fields are marked *