Processing Internet Addresses - IP Addresses and Domain Names

Internet programs need to use internet addresses - both host names and IP addresses. The Java library provides a class InetAddress that facilitates using these addresses.

Converting a domain name to an IP address

If a user supplies an internet address as a domain name, the software must convert it to an IP address so that packets can be transmitted across the internet. The following program allows the user to enter a host name into a text field. Pressing the button causes it to display the equivalent IP address. The name of any host in the world can be entered; the program displays its IP address. If you type in a domain name that does not exist (is not registered), you get an error message.

// IPFinder.java
/ Finds the IP address of a domain name.

import java.awt.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;

public class IPFinder
    extends Frame
    implements ActionListener
{

    private TextField txtOutput, txtInput;
    private Button btnDisplay;
    private Button exit;

    public static void main(String [] args)
    {
        IPFinder m = new IPFinder();
        m.makeGUI();
        m.setSize(500, 100);
        m.setVisible(true);
    }

    public void makeGUI()
    {
        setLayout(new FlowLayout());

        txtInput = new TextField(50);
        txtOutput = new TextField(50);
        btnDisplay = new Button("Display");
        btnDisplay.addActionListener(this);
        add(txtInput);
        add(btnDisplay);
        add(txtOutput);

        exit = new Button("Exit");
        add(exit);
        exit.addActionListener(this);
    }

    public void actionPerformed(ActionEvent event)
    {
        if (event.getSource() == exit) System.exit(0);

        String host = txtInput.getText();
        try
        {
              InetAddress address = InetAddress.getByName(host);
              txtOutput.setText(address.toString());
        }
        catch (UnknownHostException e)
        {
            txtOutput.setText("Could not find " + host);
        }
   }
}

The library class InetAddress represents an internet address. It maintains two representations of an address - a host name and an IP address. These two items are encapsulated within an object of type InetAddress and cannot be accessed directly. This accords with the general OOP strategy of disallowing direct access to data.

Class InetAddress is unusual in not providing any constructor methods. Instead it provides a class (static) method called getByName(). This is used in the above program. The parameter is a host name (a string) and it returns the IP address of its parameter. This object is of type InetAddress.

An object of type InetAddress can be converted to a string using the toString() method, as used in the program.

When getByName() is called, the library method uses the domain name system (DNS) to obtain the IP address. If a host with the specified name cannot be found, an exception is thrown. This is handled in the above program by displaying an error message.


Getting the local IP address

Next, an application that displays the IP address of the current machine, the machine that the program is running on:

// MyLocalIPAddress.java
// Finds the IP address of your local machine.

import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class MyLocalIPAddress
    extends Frame
    implements ActionListener
{
    private Button btnDisplayIp;
    private TextField txtIpAddress;
    private Button exit;

    public static void main(String [] args)
    {
        MyLocalIPAddress m = new MyLocalIPAddress();
        m.makeGUI();
        m.setSize(300, 120);
        m.setVisible(true);
    }

    public void makeGUI()
    {
        setLayout(new FlowLayout());

        btnDisplayIp = new Button("Display local IP address");
        txtIpAddress = new TextField(40);
        btnDisplayIp.addActionListener(this);
        txtIpAddress.addActionListener(this);
        add(btnDisplayIp);
        add(txtIpAddress);

        exit = new Button("Exit");
        add(exit);
        exit.addActionListener(this);
    }

    public void actionPerformed(ActionEvent event)
    {
        if (event.getSource() == exit) System.exit(0);

        try
        {
            InetAddress address = InetAddress.getLocalHost();
            txtIpAddress.setText(address + "");
        }
        catch (UnknownHostException e)
        {
            txtIpAddress.setText("Could not find the local address");
        }
    }
}

The core of this program is a call on getLocalHost() - another static method within the class InetAddress. It returns an object of type InetAddress. This object is the representation of the local address. It can be displayed as shown, using the toString method of InetAddress. Actually, in this piece of code, toString() is called implicitly because the object appears alongside the string concatenation operator +.

If the local address cannot be found, an exception is raised. Should this happen, this program catches the exception and displays an error message.

The class InetAddress is (almost) a classic example of a Java class. The data is encapsulated along with its associated methods, as usual. The representation of the data is hidden. The benefit of this will certainly be seen when IP addresses eventually become 8 bytes rather than the current 4 bytes. This change is being made in order to cope with the need for many more IP addresses. But any program that uses InetAddress will not need to be changed when the changeover takes place.


So, Java provides the library class InetAddress that models both an IP address and a host name.

Class name:

InetAddress

Import

import java.net


Summary of class InetAddress Info

Method

Description

Example(s)

Constructors (none)

 

 

Static Methods:

 

 

public static InetAddress getByName(String hostname)

Creates an InetAddress object, given either a host name or an IP address.

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

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

public static InetAddress getLocalHost()

Creates an InetAdress object corresponding to the machine on which it is running.

InetAddress thisComputer = InetAddress.getLocalHost();

Object Methods:

 

 

public String getHostName()

Returns the host name as a string. If the machine does not have a host name, a string version of the IP address is returned.

String name = thisMachine.getHostName();

public String toString()

Returns host name and IP address.

String name = thisComputer.toString();


Exercise: The aims of this exercise are to experiment with, and clarify your understanding of, host names and IP addresses. Begin by running the two programs given above. When running IPFinder.java, enter localhost as one of the host names you try. When running MyLocalIPAddress.java, check that the IP address of the local machine from this program coincides with the IP address that can be obtained by using the

ipconfig

in the case of DOS, or

ifconfig

in the case of Linux.

The programs given above convert a host name to an IP address. The opposite is called reverse host name resolution - converting an IP address to a host name. This might be useful, say, in analyzing a web server log file. You might want to try writing a program to do this. It will need to make use of the method called getHostName(). When applied to an InetAddress object, it returns the host name as a string.