Richard G Baldwin (512) 223-4758, baldwin@austin.cc.tx.us, http://www2.austin.cc.tx.us/baldwin/

Network Programming - The InetAddress Class

Java Programming, Lesson # 552, Revised 01/25/98.

Preface

Students in Prof. Baldwin's Advanced Java Programming classes at ACC are responsible for knowing and understanding all of the material in this lesson.

Introduction

Every computer attached to an IP network has a unique four-byte (32-bit) address.

For human consumption, we usually convert each of the four bytes to an unsigned decimal value and display them connected by periods to make them easier to remember. As of this writing, the IP address of www.javasoft.com is 204.160.241.98.

What do we mean when we speak of www.javasoft.com?

Each IP address has a corresponding name known as a domain name. The domain name for the IP address 204.160.241.98 is www.javasoft.com.

For example, I can enter either of these into the Location field of my Netscape Navigator program and use it to connect to the JavaSoft site.

The Domain Name System (DNS) was developed to translate between IP addresses and domain names. Whenever you log your browser onto the internet and attempt to connect to a server using its domain name, the browser first communicates with a DNS server to learn the corresponding numeric IP address. The numeric IP address is encapsulated into the data packets and used by the internet protocol to route those packets from the source to the destination.

We will learn how to use the Java InetAddress class to find the domain name corresponding to an IP address, and to find the IP address corresponding to a domain name in our sample program for this lesson.

We will also learn how to use the methods of the InetAddress class to obtain information about the address of the local host.

Sample Program

This program exercises several of the methods of the InetAddress class.

You must be logged onto an appropriate network for this program to run properly. Otherwise, it will throw an exception of type UnknownHostException.

This program was tested using JDK 1.1.3 under Win95.

The output from one run of this program was as follows. Note that because I use a commercial ISP that assigns an IP address to me each time I log on, the output will be different each time I log onto the ISP and run this program.

As you can see from the boldface line below, after determining the IP address that has been assigned to me for a particular logon session, a reverse lookup on that IP address provides the domain name of the ISP. On this particular occasion, the domain name of the ISP was slip129-37-120-182.tx.us.ibm.net.
 
Get and display IP address of URL by name
www2.austin.cc.tx.us/198.213.3.13
Do reverse lookup on the IP address
ella.austin.cc.tx.us/198.213.3.13
Get and display current IP address of LocalHost
baldwin/129.37.120.182
Do reverse lookup on current IP address of LocalHost
slip129-37-120-182.tx.us.ibm.net/129.37.120.182
Get and display current name of LocalHost
slip129-37-120-182.tx.us.ibm.net
Get and display current IP address of LocalHost
129 37 120 182 
We will look at these lines of output in context as we review the different parts of this program.

Code Fragments

All of the code in this program is contained in the main() method. I will ignore the exception handling code during this discussion. You will find that code in the program listing in the next section.

The InetAddress class provides objects that you can use to manipulate and deal with IP addresses and domain names. However, you don't instantiate those objects directly. Rather, the class provides several static methods that return an object of type InetAddress.

The static getByName(String host) method returns an InetAddress object representing the host passed as a parameter. This method can be used to determine the IP address of a host, given the host's name. The host name can either be a machine name, such as "java.sun.com", or a string representing its IP address, such as "206.26.48.100".

The getAllByName(String host) method returns an array of InetAddress objects. This method can be used to determine all the IP addresses of the specified host.

The getLocalHost() method returns an InetAddress object representing the local host computer.

Our first code fragment obtains an InetAddress object representing a particular server and displays that address using the overridden toString() method of the InetAddress class. As indicated earlier, the output produced by this code fragment was www2.austin.cc.tx.us/198.213.3.13.
 
      InetAddress address = InetAddress.getByName(
                                    "www2.austin.cc.tx.us");
      System.out.println(address);
The next code fragment does a reverse lookup on this IP address and displays the result. As mentioned above, the getByName() method can accept either the name of the server or the IP address of the server as a string.

This code fragment does some string manipulation on the result of the previous code fragment to construct a string containing the numeric portion of the previous result. This string representation of the numeric IP address is then passed to the getByName() method to produce the following result: ella.austin.cc.tx.us/198.213.3.13.

Although I can't explain why, it is interesting to note that the ella portion of the string returned by this method was not included in the name originally used to obtain the IP address.

It is also interesting to note that if the ella portion is included in the name, my Netscape browser is unable to resolve an IP address for the server.
 
      int temp = address.toString().indexOf('/');
      address = InetAddress.getByName(
                     address.toString().substring(temp+1));
      System.out.println(address);
The terminology localhost is used to describe the local computer on which this program is running. When connected to an IP network, the local computer must have an IP address. This is accomplished in a variety of ways. The following discussion is based on a computer that is used to dial into a commercial Internet Service Provider (ISP).

My ISP has reserved a large block of IP addresses to be shared by its many customers. Whenever I dial in and log onto the server, one of those IP addresses is assigned to my connection for the duration of that logon session. If I disconnect and log on again, the probability is high that the IP address assigned for the second session will be different from the one assigned for the first session.

Other situations may be different. For example, if your computer is one of a network of computers in a company, your company may have reserved a block of IP addresses and may have assigned one of those addresses to your computer on a "permanent" basis. In that case, you should get the same address each time you run this program.

It is also possible to get your own "permanent" IP address and domain name.

In any event, the getLocalHost() method can be used to obtain an InetAddress object that represents the computer on which the program is being run. This is illustrated by the following code fragment. This code fragment produced the following output: baldwin/129.37.120.182.

In this case, the numeric portion of the output was the IP address that was assigned to me for a particular logon session with my ISP.

I'm confident that baldwin did not come from the DNS server, but rather is the name by which my operating system (Win95) recognizes my computer. Apparently the overridden toString() method obtained this system parameter and used it to construct the string for display.
 
      address = InetAddress.getLocalHost();
      System.out.println(address);
The next code fragment uses the getByName() method to do a reverse lookup on the numeric portion of the output from the previous code fragment. In particular, this code fragment determines the name by which the DNS server recognizes this numeric address. The output from the code fragment was: slip129-37-120-182.tx.us.ibm.net/129.37.120.182.

As you can see, I am a customer of a commercial ISP venture of IBM corporation commonly referred to as ibm.net.

It is interesting (and somewhat contradictory to the earlier discussion about ella) to note that I can install and run a web server on my computer, and access that server using the portion of the above result to the left of the "/" in the Netscape Navigator Location field (actually, I have to modify it each time I log onto the ISP to correspond to the name returned for that session). In other words, I can use the domain name provided by a reverse lookup on the temporary IP address to log onto a server on my computer.

There are some other interesting peculiarities as well, but they are too complicated to discuss here. I will leave it as an exercise for the student to do this type of experimentation on your own. You will obtain enough simple programs in this series of lessons to do this type of experimentation, including a program for a simple web server that you can install on your computer.
 
      temp = address.toString().indexOf('/');
      address = InetAddress.getByName(
          address.toString().substring(temp+1));
      System.out.println(address);
Once you have an InetAddress object, there are other useful methods of the InetAddress class that you can invoke on that object. For example, the following code fragment invokes the getHostName() method on the object and produces the following output: slip129-37-120-182.tx.us.ibm.net.
 
      System.out.println(address.getHostName());
Similarly, the following code fragment invokes the getAddress() method on the object to produce an array of bytes containing the IP address. In this case, the code fragment displays: 129 37 120 182.

Because there is no such thing as an unsigned byte in Java, converting the array of bytes into something that can be displayed in a meaningful way requires some manipulation of the bytes as shown in the code fragment.
 
      byte[] bytes = address.getAddress();
      
      for(int cnt = 0; cnt < bytes.length; cnt++){
        int uByte = 
            bytes[cnt] < 0 ? bytes[cnt] + 256 : bytes[cnt];
        System.out.print(uByte + " ");
      }//end for loop

Program Listing

A complete listing of the program follows.
 
/*File Url001.java Copyright 1998, R.G.Baldwin
Revised 01/19/98

This program exercises several of the methods of the
InetAddress class.

You must be logged onto an appropriate network for this
program to run properly.  Otherwise, it will throw
an exception of type UnknownHostException.

This program was tested using JDK 1.1.3 under Win95.

The output from one run of this program was as follows.
Note that because I use a commercial ISP that assigns an
IP address to me each time I log on, the output will
be different each time I log onto the ISP and run this
program.


Get and display IP address of URL by name
www2.austin.cc.tx.us/198.213.3.13
Do reverse lookup on the IP address
ella.austin.cc.tx.us/198.213.3.13
Get and display current IP address of LocalHost
baldwin/129.37.120.182
Do reverse lookup on current IP address of LocalHost
slip129-37-120-182.tx.us.ibm.net/129.37.120.182
Get and display current name of LocalHost
slip129-37-120-182.tx.us.ibm.net
Get and display current IP address of LocalHost
129 37 120 182 
**********************************************************/

import java.net.*;

class Url001{
  public static void main(String[] args){
    try{
      System.out.println(
              "Get and display IP address of URL by name");
      InetAddress address = InetAddress.getByName(
                                    "www2.austin.cc.tx.us");
      System.out.println(address);

      System.out.println(
                    "Do reverse lookup on the IP address");
      //Extract the IP address from the string to the right
      // of the /.  Then provide the IP address as a string
      // to the getByName() method.
      int temp = address.toString().indexOf('/');
      address = InetAddress.getByName(
                     address.toString().substring(temp+1));
      System.out.println(address);
      
      System.out.println(
        "Get and display current IP address of LocalHost");
      address = InetAddress.getLocalHost();
      System.out.println(address);

      System.out.println(
                          "Do reverse lookup on current " + 
                                "IP address of LocalHost");
      temp = address.toString().indexOf('/');
      address = InetAddress.getByName(
                     address.toString().substring(temp+1));
      System.out.println(address);

      System.out.println(
              "Get and display current name of LocalHost");
      System.out.println(address.getHostName());
      
      System.out.println(
        "Get and display current IP address of LocalHost");
        
      //Get IP address as an array of bytes.
      byte[] bytes = address.getAddress();
      
      //Convert IP address bytes to unsigned values 
      // and display separated by spaces.
      for(int cnt = 0; cnt < bytes.length; cnt++){
        int uByte = 
            bytes[cnt] < 0 ? bytes[cnt] + 256 : bytes[cnt];
        System.out.print(uByte + " ");
      }//end for loop
      System.out.println();
    }catch(UnknownHostException e){
      System.out.println(e);
      System.out.println("Must be online to run properly.");
    }//end catch
  }//end main
}//end class Url001
-end-