InetAddress Example Java

InetAddress Example Java


Getting URL from URN

As the name indicates, the InetAddress of java.net 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("www.arkut.com");

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

As there does not exist a Web server by name arkutXYZ.com (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 rediff.com are obtained.


Screenshot of MultipleHostAddresses.java

InetAddress add[] = InetAddress.getAllByName("www.rediff.com");

The above statement returns two IP addresses referring rediff.com. Replace rediff.com with microsoft.com, 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 LocalSystem.java

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 *