18 Java Networking – Introduction

Dr M. Vijayalakshmi

Java for Networking

 

Java is practically a synonym for Internet Programming. Using Java we can generate secure, cross-platform and portable code. Java has complete network package to support networking using java.net.* package. I/O stream library in Java also works quite well for TCP/IP. Threading is also very useful for networking and is relatively easy in Java.

 

Networking Basics

 

Internet protocol (IP) addresses

 

1. Every host on Internet has a unique IP address. For example an IP address would look like 143.89.40.46, 203.184.197.198 203.184.197.196, 203.184.197.197, 127.0.0 and soon

2.Every host on the Internet can also be identified more conveniently by using hostname string like cse.ust.hk, tom.com, localhost.

3.Even one hostname can correspond to multiple internet addresses. For example,www.yahoo.com corresponds to many addresses like  66.218.70.49; 66.218.70.50; 66.218.71.80; 66.218.71.84; …

4. Domain Naming Service (DNS) maps these hostnames to numbers.

 

Ports

 

Many different services can be running on the host. A port identifies a service within a host. Many standard port numbers are pre-assigned. They are:

 

time of day 13, FTP 21, TELNET 23, SMTP 25, HTTP 80.

 

We can say that IP address + port number = “phone number“ for service.

 

Protocols

 

Protocols are the rules that facilitate communications between machines.

Some examples of different protocols are,

 

1. HTTP – HyperText Transfer Protocol

2. FTP – File Transfer Protocol

3. SMTP – Simple Message Transfer Protocol

4. TCP -Transmission Control Protocol

5.  UDP – User Datagram Protocol (e.g., video delivery)

Protocols are standardized and documented and so machines can reliably work with one another.

 

Client-Server interaction

 

Communication between hosts is two-way, but usually the two hosts take different roles.

 

1.  Server waits for client to make request

 

Server registered on a known port with the host (“public phone number”) . It usually runs in an endless loop and listens for incoming client connections.

 

2.  Client “calls” server to start a conversation

 

Client making calls using hostname/IP address and port number. Then it sends the request and waits for response.

 

3.  Standard services always running

     Server offers shared resource such as information, database, files, printer and compute power etc. to clients. Server running on host using expected port like ftp, http, smtp, etc.

 

Networking Basics

 

We can try out some services of servers using telnet. Telnet assumes that whether you want to connect to port 23 on the receiving host (port 23 is where the telnet server is listening). However there is an optional argument after the hostname that allows you to connect to a different port. Many servers now refuse telnet connections due to security reasons.

 

Networking with Java

 

Networking package uses the classes in java.net.*. Java programs can use TCP or UDP to communicate over the Internet. The URL and URLConnection classes in the package are used to work with Web applications. The Socket and ServerSocket (client-server applications) classes uses TCP to communicate over the network. The DatagramPacket, DatagramSocket, and MulticastSocket classes are used to work with UDP communication.

 

Java Networking

 

The following are the classes used with the networking package.

 

1.      InetAddress

2.      URL

3.      URLConnection

4.      Using Sockets

 

  InetAddress

 

The InetAddress class is used to encapsulate both the numerical IP address and the domain name for that address. java.net.InetAddress class converts between hostnames and Internet addresses. We can interact with this class by using the name of an IP host, which is more convenient and understandable than its IP address. The InetAddress class hides the number inside. InetAddress can handle both IPv4 and IPv6 addresses.

   

Testing without a Network

 

There are three ways to test the local machine,

a) “localhost”: It is the “local loopback” IP address for testing without a network.InetAddress addr = InetAddress.getByName(null);

b)  Equivalently:InetAddress.getByName(“localhost”);

c) Or using the reserved IP number for the loopback:InetAddress.getByName(“127.0.0.1”);

 

InetAddress

 

InetAddress class is used to dentify a machine either with the hostname or with the IP address.

 

a)      Identifying a Machine – IP (Internet Protocol) address 

1.      DNS (Domain Name System) : www.auist.net

2.      Dotted Quad Form : 123.255.28.120

InetAddress ia=InetAddress.getByName(…);

 

b)  Local Host (for testing)

 

All these forms connect to local host,

 

1.    InetAddress ia=InetAddress.getByName(null) ;

2.    InetAddress ia=InetAddress.getByName(“localhost”);

3.    InetAddress ia=InetAddress.getByName(“127.0.0.1”);

4.    InetAddress ia=InetAddress.getLocalHost()

 

Identifying a Machine

 

A simple program to identify a machine using the hostname is given below,

import java.net.*;

public class WhoAmI {

public static void main(String[] args) throws Exception

{

if(args.length != 1)

{

System.err.println(“Usage: WhoAmI MachineName”); System.exit(1);

}

InetAddress a = InetAddress.getByName(args[0]); System.out.println(a);

}

}

 

To run:

java WhoAmI Vijim

Vijim/127.0.0.1

 

Factory Methods

 

Factory methods are merely a convention whereby static methods in a class return an instance of that class. Three commonly used InetAddress factory methods are shown here:

 

a) static InetAddress getLocalHost( ) throws UnknownHostException

b) static InetAddress getByName(String hostName) throws UnknownHostException

c) static InetAddress[ ] getAllByName(String hostName) throwsUnknownHostException

 

   Factory Method Description

 

 a) getLocalHost():

The getLocalHost( ) method simply returns the InetAddress object that represents the local host.

b) getByName():

The getByName( ) method returns an InetAddress for a host name passed to it. If these methods are unable to resolve the host name, they throw an UnknownHostException.

c) getAllByName():

The getAllByName( ) factory method returns an array of InetAddresses that represent all of the addresses that a particular name resolves to. It will also throw an UnknownHostException if it can’t resolve the name to at least one address.

 

Table 20.1 describes the instance methods of the InetAddress class.

 

 

Example of InetAddress

 

import java.net.*;

import java.io.*;

public class IPAddress

{

public static void main(String[] args)

{

try {

//  Get hostname by textual representation of IP address InetAddress addr = InetAddress.getByName(“java -tips.org”);

System.out.println(” Address” + addr);

//  Get hostname by a byte array containing the IP address byte[] ipAddr = new byte[]{127, 0, 0, 1};

InetAddress addr1 = InetAddress.getByAddress(ipAddr); System.out.println(” Address1″ + addr1);

//  Get the host name

String hostname = addr1.getHostName();

System.out.println(” hostname” + hostname);

// Get canonical host name

String canonicalhostname = addr1.getCanonicalHostName();

System.out.println(” canonical host name” + canonicalhostname);

} catch (UnknownHostException e)

{

}

}

}

The example code uses the method, getByName() that gets the hostname by textual representation of IP address and returns the InetAddress object. It also uses the method getByAddress() that gets the hostname by a byte array containing the IP address and returns the InetAddress object. The code demonstrates getHostName() that gets the host name and returns the InetAddress object. The code also demonstrates getCanonicalHostName() that gets the canonical host name and returns the InetAddress object.

The output of the above code is shown in Figure 20.1.

 

Output of InetAddress Program

 

    Example of IPAddress

 

import java.net.*;

import java.io.*;

public class IPAddress1

{

public static void main(String[] args)

{

try

{

     InetAddress addr = InetAddress.getByName(“java -tips.org”); byte[] ipAddr = addr.getAddress(); System.out.println(“ByteAdress:” + ipAddr );

String HostAddress = addr.getHostAddress(); System.out.println(“HostAdress:” + HostAddress ); String HostName = addr.getHostName(); System.out.println(“HostName:” + HostName );

String ipAddrStr = “”;

for (int i=0; i<ipAddr.length; i++)

{

if (i > 0) {      ipAddrStr += “.”;   }

ipAddrStr += ipAddr[i]&0xFF;

System.out.println(“IPAdress:” + ipAddrStr);

InetAddress localhostIP = InetAddress.getByAddress(“127.0.0.1”,new byte[]{127, 0, 0, 1});

System.out.println(“get by Ip Address:” + localhostIP); String HostName1 = localhostIP.getHostName(); System.out.println(“HostName:” + HostName1 );

String hostname2 = InetAddress.getByName(“127.0.0.1”).getHostName(); System.out.println(“HostName:” + hostname2 );

}

} catch (UnknownHostException e) {

}

}

}

 

This example code is to demonstrate the instance methods of InetAddress object. It retrieves the InetAddress object using the method getByName() by passing the host name as “java-tips.org”. The getAddress() method returns the object’s IP address as byte array in network byte order from the InetAddress object. The method getHostAddress() returns a string that represents the host address associated with the InetAddress object and the method getHostName() returns a string that represents the host name associated with the InetAddress object. Then there exists a for loop which retrieves evry single byte from the IP addr and prints it.The output of this code is shown in Figure 20.2.

    Output of IPAddress

 

Inet4Address and Inet6Address

 

Beginning with version 1.4, Java has included support for IPv6 addresses. Two subclasses of InetAddress were created, they are: Inet4Address and Inet6Address. Inet4Address represents a traditional-style IPv4 address. Inet6Address encapsulates a new-style IPv6 address.

 

URL

 

The java.ne t.URL class can be used to identify the files on the Internet. URL (Uniform Resource Locator) is a pointer to a “resource” on the World Wide Web. A resource can be something as simple as a file or a directory. We can create a URL object using the following constructor:public URL(String spec) throws MalformedURLException

 

There exists two classes for URL processing in Java.

  • java.net.URL which represents an URL resource
  • java.net.URLConnection which is used to open a connection to a URL resource.

     We can create an absolute URL object using an constructor of the URL class as follows,

  •   By Constructor : URL(String)
  •   URL myurl = new URL(“http://cs.biu.ac.il/”) ;

We can create a URL relative to another URL. This is used for relative hyperlinks in an HTML page.

Given a URL, <A HREF=“MyPres.html”>Presentations</A>

 

By Constructor : URL(URL, String)

URL myurl = new URL(“http://cs.biu.ac.il/~freskom1/”) ;

URL mypres = new URL(myurl, “MyPres.html”) ;

Other URL Constructors that exists are,

 

(i)    URL(String protocol, String host, int port, String file)

(ii)   URL(String protocol, String host, String file)

(iii)  URL(String spec)

(iv)  URL(URL context, String spec)

 

All constructors throw MalformedURLExce ption

 

 

Parsing a URL

 

Once a URL object is created, we can parse the URL and retrieve the individual components in the URL like what protocol is mentioned, the name of the host, port,file mentioned in the URL, and reference if present in the URL.

 

1.    String getProtocol()

2.    String getHost()

3.    int getPort()

4.    String getFile()

5.    String getRef()

 

Example of ParseURL

 

import java.net.*;

import java.io.*;

public class ParseURL

{

public static void main(String args[]) throws Exception {

URL u = new URL(“http://java.sun.com/docs/books/tutorial/#down “);

System.out.println(“protocol =” + u.getProtocol());

System.out.println(“host =” + u.getHost());

System.out.println(“filename =” + u.getFile());

System.out.println(“port =” + u.getPort());

System.out.println(“ref =”+  u.getRef());

}

}

This example demonstrates about the instance methods of URL. The method getProtocol() retrieves the protocol from the URL. The method getHost() retrieves the hostname from the URL. The method getFile() retrieves the filename, the method getPort() retrieves the port no if exists in the URL and getRef() retrieves the reference from the URL.

 

The output of this code is shown in Figure 20.3.

 

Output of ParseURL

 

 

Summary

 

This module discusses about the basics for Internet Programming. This module also explores about working with InetAddress class for obtaining the Internet Address and also gives an idea about URL class and the URLConnection class.

 

Web Links

  • Herbert Schildt, ” Java: The Complete Reference”, 9th Edition, Mcgraw-Hill, 2014.