This is the age of internet. Communication of data from one terminal to other is a common practice in daily routine. Network and internet oriented application development is a growing domain these days. Of course, communication of data involves security risks which are of great importance.

Thankfully, Java includes networking support. Which means, we can developer applications that can exchange data with other applications on the internet. Java.net package provides interfaces, classes an exceptions to do network programming.

Streams for input/output

Java uses streams for reading and writing data. Input streams are used to read data and output streams are used to display/print data. Streams are synchronous which means that if a thread asks a stream to read or write a data, then thread will wait for the data to be read or written before it does anything else.

java.io.OutputStream is an abstract class which is the superclass of all classes representing an output stream of bytes. It includes following methods:

void close()
void flush()
void write(byte[] b)
void write(byte[] b, int off, int len)
abstract void write(int b)

The direct subclasses of OutputStream are:

ByteArrayOutputStream, FileOutputStream, FilterOutputStream, ObjectOutputStream, OutputStream, PipedOutputStream

java.io.InputStream is an abstract class which is the superclass of all classes representing an input stream of bytes. It includes following methods:

int available()
void close()
void mark(int readlimit)
boolean markSupported()
abstract int read()
int read(byte[] b)
int read(byte[] b, int off, int len)
void reset()
long skip(long n)

The direct subclasses of InputStream are:

AudioInputStream, ByteArrayInputStream, FileInputStream, FilterInputStream, InputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream

Getting host name/IP address

Each computer on internet is called a node or a host. Each host has unique address called Internet Protocol (IP) address. IP addresses are not easy for the humans to remember therefore, Domain Name System (DNS) was introduced. DNS assigns a human understandable name to IP addresses.

InetAddress class represents IP addresses which can be useful in networking environment. Let see what we can o with this one:

Following code finds and prints the IP address of a given web host. Please note that some hosts have more than one IP addresses therefore, we will get all the IP addresses in an array and then will print those.

Java Code:
try {
InetAddress[] addresses =
InetAddress.getAllByName("www.cnn.com");
for (int i = 0; i < addresses.length; i++) {
System.out.println(addresses[i]);
}
}
catch (UnknownHostException ex) {
System.out.println("Could not find the host.");
}
Output:

Java Code:
www.cnn.com/64.236.16.20
www.cnn.com/64.236.16.52
www.cnn.com/64.236.24.12
www.cnn.com/64.236.29.120
www.cnn.com/64.236.91.21
www.cnn.com/64.236.91.22
www.cnn.com/64.236.91.23
www.cnn.com/64.236.91.24
UnknownHostException is thrown, if you specify an invalid host name.
Sometimes, you will face reverse scenarios. I mean you want to convert an IP address to its host name. Review the code below:

Java Code:
try {
InetAddress address = InetAddress.getByName("64.236.91.22");
System.out.println(address.getHostName());
}

catch (UnknownHostException ex) {
System.out.println("Could not find the host.");
}
Output:

Java Code:
www.cnn.com
You may also find the address of your local machine using the code below.

Java Code:
try {
InetAddress address = InetAddress.getLocalHost( );
System.out.println(address);
}

catch (UnknownHostException ex) {
System.out.println("Could not find this computer's address.");
}
Output:

Java Code:
javabook/192.168.0.87
If you are not on any network, then your IP address will br 127.0.0.1.

Characteristics of IP addresses

InetAddress class provides methods to get the characteristics of IP addresses. Following methods are of interest:

public boolean isAnyLocalAddress( )
public boolean isLoopbackAddress( )
public boolean isLinkLocalAddress( )
public boolean isSiteLocalAddress( )
public boolean isMulticastAddress( )
public boolean isMCGlobal( )
public boolean isMCNodeLocal( )
public boolean isMCLinkLocal( )
public boolean isMCSiteLocal( )
public boolean isMCOrgLocal( )

There are very useful in order to get a lot of information while just having the IP address or host name of a host. Review the example below:

Java Code:
try {

InetAddress address = InetAddress.getByName("127.0.0.1");
if (address.isAnyLocalAddress( )) {
System.out.println(address + " is a wildcard address.");
}
if (address.isLoopbackAddress( )) {
System.out.println(address + " is loopback address.");
}

if (address.isLinkLocalAddress( )) {
System.out.println(address + " is a link-local address.");
}

else if (address.isSiteLocalAddress( )) {
System.out.println(address + " is a site-local address.");
}

else {
System.out.println(address + " is a global address.");
}

if (address.isMulticastAddress( )) {
if (address.isMCGlobal( )) {
System.out.println(address + " is a global multicast address.");
}          
else if (address.isMCOrgLocal( )) {
System.out.println(address 
+ " is an organization wide multicast address.");
}  
else if (address.isMCSiteLocal( )) {
System.out.println(address + " is a site wide multicast address.");

}  
else if (address.isMCLinkLocal( )) {
System.out.println(address + " is a subnet wide multicast address.");
}

else if (address.isMCNodeLocal( )) {
System.out.println(address + " is an interface-local multicast address.");
}

else {
System.out.println(address + " is an unknown multicast address type.");
}
}

else {

System.out.println(address + " is a unicast address.");
}
}

catch (UnknownHostException ex) {

System.err.println("Could not resolve the host. ");

}

Output:

Java Code:
/127.0.0.1 is loopback address.
/127.0.0.1 is a global address.
/127.0.0.1 is a unicast address.
If we specify the IP address of cnn (64.236.16.20), we will get the following output:

Java Code:
/64.236.16.20 is a global address.
/64.236.16.20 is a unicast address.
Reachability of a web host

Sometimes itís a wise decision to check the reachability of a host before attempting to connect to it or before sending some data to it. InetAddress provides following two methods to check the availability of a host. Time is mentioned in milli seconds.

Java Code:
public boolean isReachable(int timeout) throws IOException
public boolean isReachable(NetworkInterface interface, int ttl, 
                                        int timeout) throws IOException
Comparing two InetAddress objects

Sometimes you will encounter situations where two host names will correspond to the same IP address. In such situations, you might need to compare the objects and then take some decisions. For that, equals(Ö) method is used.

Java Code:
InetAddressObj1.equals(inetAddressObj2);

NetworkInterface

NetworkInterface class represents a local IP address which can be a physical interface (Ethernet card) or virtual interface bound to the same physical hardware. The interface provides methods to enumerate through the local addresses. Lets take an example: Following program will list all the network interfaces.

Java Code:
Enumeration interfaces = NetworkInterface.getNetworkInterfaces( );
while (interfaces.hasMoreElements( )) {
NetworkInterface ni = (NetworkInterface) interfaces.nextElement( );
System.out.println(ni.getDisplayName());
Output on my machine:

Java Code:
MS TCP Loopback interface
Intel(R) PRO/Wireless 3945ABG Network Connection - Packet Scheduler Miniport
Marvell Yukon 88E8055 PCI-E Gigabit Ethernet Controller - Packet Scheduler Miniport
The URL class

Java networking package provides a final class called URL for referring to Uniform Resource Locators. Its signature is:

Java Code:
public final class URL extends Object implements Serializable
It has 6 constructors:

URL(String spec)
URL(String protocol, String host, int port, String file)
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
URL(String protocol, String host, String file)
URL(URL context, String spec)
URL(URL context, String spec, URLStreamHandler handler)

Choose the constructor according to the information you have for the host.

Java Code:
try {
URL u = new URL("http://www.yahoo.com");
}
catch (MalformedURLException ex)  {
System.err.println(ex);
}
If you have the host name, protocol and file name, then you should use the constructor that requires these parameters.
Java Code:
try {
URL u = new URL("http","content-uk.cricinfo.com",80,
                  "/ci/content/current/story/index.html");
}
catch (MalformedURLException ex)  {
System.err.println(ex);
}
If port number is also known, then URL object creation will look like this:


Java Code:
try {
URL u = new URL("http","content-uk.cricinfo.com",
              "/ci/content/current/story/index.html");
}
catch (MalformedURLException ex)  {
System.err.println(ex);
}

Creating URL with address having special characters

Sometimes the URL address contains special characters which makes creating URL objects tricky.

If the address is http://www.cnn.com/hello world, then the space will create problems for you. You should use %20 in place of space.

Java Code:
URL url = new URL("http://www.cnn.com/hello%20world");

Using URI for special characters

Sometimes, URL address may contain special characters. The special characters will cause a lot of problems. java.net.URI class automatically take care of the encoding.

Java Code:
URI uri = new URI("http", "foo.com", "/hello world/", "");
URL url = uri.toURL();
Protocol testing example

Consider the following scenario: You are asked to test your browser with a list of protocols. So, you can do this by making URL objects for a host with each protocol. If object is created, it means protocol is supported, in other case, it simply means that the browser does not support the particular protocol.

Review the applet code below:

Java Code:
public class ProtocolTesterApplet extends Applet {

  TextArea results = new TextArea( );  

  public void init( ) {

    this.setLayout(new BorderLayout( ));    

    this.add("Center", results);

  }

  public void start( ) {
    String host = "http://content-uk.cricinfo.com";
    String file = "/ci/content/current/story/index.html";

    String[] schemes = {"http", "https", "ftp", "mailto", 
                        "telnet", "file",    "ldap", "gopher",
                        "jdbc",   "rmi",     "jndi", "jar",
                        "doc",    "netdoc",  "nfs",  "verbatim",
                        "finger", "daytime", "systemresource"};
                          
    for (int i = 0; i < schemes.length; i++) {
      try {

        URL u = new URL(schemes[i], host, file);
        results.append(schemes[i] + " is supported\r\n");
      }

      catch (MalformedURLException ex) {

        results.append(schemes[i] + " is not supported\r\n");      

      }
    }  
  }

}
Relative URLs

The last two constructors of URL class can be used to create relative URLs. Example below will make things obvious:

Java Code:
URL u1 = new URL("http://www.java-forums.org/faq.php");
URL u2 = new URL (u1, "sendmessage.php");

System.out.println("U1: " + u1.getHost() + " - " + u1.getPath() );
System.out.println("U2: " + u2.getHost() + " - " + u2.getPath() );
Output:

Java Code:
U1: www.java-forums.org - /faq.php
U2: www.java-forums.org - /sendmessage.php
The output makes it clear, that the URL object name u2, is referring to the address we wanted. Itís a relative URL.


Splitting URL

Splitting the URL is very simple. If you are thinking that we will simply parse the URL string and will extract the protocol, host and file information, then itís not right. URL class provides methods that will be used for the subject purpose.

Java Code:
		 URL u1 = new URL("http://www.java-forums.org/faq.php");
		 System.out.println("Host name: " + u1.getHost());
		 System.out.println("Protocol: " + u1.getProtocol());
		 System.out.println("Default port: " + u1.getDefaultPort());
		 System.out.println("File name: " + u1.getFile());
		 System.out.println("Path: " + u1.getPath());
Output:

Java Code:
Host name: www.java-forums.org
Protocol: http
Default port: 80
File name: /faq.php
Path: /faq.php
getRef() method provides fragment identifier part of the URL. If fragment identifier doesnít exist, then null is returned.

Sometimes, usernames are embedded in the URL.For instance mailto:admin@javablogs.com. getUserInfo() is used to get the username from such URLs.

Retrieving data from a URL (using InputStream)

Now we come to the interesting part. A lot of work is being done in this domain. Web crawlers are based to data extraction from URL. Obviously, we are interested in the data. The following example simply retrieves the HTML contents from the URL. We used InputStream to read from the URL. We will read contents byte by byte using read() method of InputStream.

Java Code:
try {

URL u  = new URL("http://www.cricinfo.com");
InputStream in = u.openStream( );
int c
while ((c = in.read( )) != -1) 
System.out.write(c);
}
catch (IOException ex) {
System.err.println(ex);
}
Retrieving data from a URL (using BufferedReader)

Data can also be retrieved from a URL object using BufferedReader. Review the code below:

Java Code:
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
Output is the HTML contents of the site.

Using getContent( ) to download data

The method getContent() of URL class returns object. If the object contains text such as an ASCII or HTML file, the object returned is usually some sort of InputStream.

Java Code:
try {
  URL u = new URL("http://mesola.obspm.fr/");
  Object o = u.getContent( );
  // cast the Object to the appropriate type
  // work with the Object...
} 
catch (Exception ex) {
  System.err.println(ex);
}
Getting image from URL

Following code demonstrates how to get an image from a URL. This is helpful if you are planning to write an application that will download all the images (jpeg, gif, bmp etc) of a website on your machine.


Java Code:
try {
// Create a URL for the image's location
URL url = new URL("http://hostname:80/image.gif");

// Get the image
java.awt.Image image = java.awt.Toolkit.getDefaultToolkit()
                               .getDefaultToolkit().createImage(url);
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Getting a JAR file from a URL

Java Achieve Files contain Java packages in compressed form so they can be transferred easily over the network. Following code samply shows how you can download a JAR file from a URL. To understand the code, follow the comments.

Java Code:
try {
        // Create a URL that refers to a jar file on the net
        URL url = new URL("jar:http://hostname/my.jar!/");
    
        // Create a URL that refers to a jar file in the file system
        url = new URL("jar:file:/c:/almanac/my.jar!/");
    
        // Get the jar file
        JarURLConnection conn = (JarURLConnection)url.openConnection();
        JarFile jarfile = conn.getJarFile();
    
        // When no entry is specified on the URL, the entry name is null
        String entryName = conn.getEntryName();  // null
    
    
        // Create a URL that refers to an entry in the jar file
        url = new URL("jar:file:/c:/almanac/my.jar!/com/mycompany/MyClass.class");
    
        // Get the jar file
        conn = (JarURLConnection)url.openConnection();
        jarfile = conn.getJarFile();
    
        // Get the entry name; it should be the same as specified on URL
        entryName = conn.getEntryName();
    
        // Get the jar entry
        JarEntry jarEntry = conn.getJarEntry();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }

This tutorial ends here. I tried to introduce Java network API along with exciting things that you can do with URLs. The next tutorial will focus on more advanced topics like datagram communication, socket programming etc.