The Network Package 
Peter Komisar © 
  Conestoga College         latest version   5.8 /  2010


Connection Classes


The java.net package provides an assortment of classes
which encapsulate TCP/IP sockets, URLs, Internet IP
addresses and application level connections. We can
tour these classes and at the same time demonstrate
how many of them are used.


The Socket Class

We saw in the last section that a Java client can be built
using the Socket class. The Socket class constructors
is used to create stream sockets based on the TCP/IP
protocol connecting to other machines on the Internet.

Machines are located using the IP address and port
number. These are supplied as parameters to the Socket
class constructor. The Socket class has the following two
constructors.


Socket Constructors

Socket ( InetAddress address, int port )
Socket ( String host, int port )
 

InetAddress //  IPv6 ready

As can be seen in the Socket object's constructors, a host
can be represented by InetAddress class object. There has
been new activity 'at the library'. In addition to working with
classic 32-bit IP addresses, InetAddress now works with the
newer 128-bit IPv6 addressing system. 

InetAddress class is primarily used to retrieve network
information. The class doesn't supply any constructors
to build an object of the class. Instead the class provides
different static methods from which an InetAddress object
can be obtained. It has methods like getLocalHost( ),
getByName( ), or getAllByName( ).

InetAddress will take either the numerical IP address
or the humanly readable, domain name for that address.


Example    

import java.net.*;

class Internet{
public static void main(String[]args){
try{
   if ( args.length < 1){
     System.out.println("Provide a domain name as an argument at the command line.");
     System.exit(0);
     }
   InetAddress ip = InetAddress.getByName(args[0]);
   System.out.println(ip.getHostAddress());
   }
catch(UnknownHostException uhe){
   System.out.println(uhe);
   }    
 }
}


Port Numbers

Both the Socket class and the ServerSocket class have
constructors that take port numbers. Services provided on
networks by server applications are identified by their port
numbers.

At the application level of the network model, a service is
specified using a port number. We saw that this number is
passed as an int value to the constructor of the ServerSocket
class. The Internet has been around for a while and many of
these numbers have been reserved.


'Well Known' Port Numbers

Reserved port numbers are controlled by ICANN, the
Internet Corporation for Assigned Names and Numbers.
(These numbers were previously controlled by IANA, the
Internet Assigned Numbers Authority.) The reserved or
well known numbers are 1 to 1023.

'No process is allowed to 'bind' or associate with that
well known port unless it has the privileged access of
the 'superuser'. That's 'root' or 'superuser' on a Linux
or Unix machine, supervisor on a NetWare system and
administrator on Windows NT. ' 

ICANN doesn't supervise the ports between 1024 and
65,535.

Well Known Port Numbers Supervised ICANN  // formerly by IANA


Heavily Used Port Ranges

There are two other ranges which are heavily used and
probably should be avoided. 2000 to 2999 is populated
by legacy inter-network applications. 6000 to 6999 are
used heavily by XWindow's programs. Ports above these
ranges will generally be open. You need to verify you are
not running an application on a port that is in use on the
same server. Heller and Robert's in 'The Developer's
Handbook' also suggest avoiding ports that already are
in use on the same network.

Heavily Used Ports                    // that should be avoided


The ServerSocket Class

We saw the ServerSocket class is the server example
in the earlier section. A
server socket provides an accept
method that waits inside a loop for requests
to make a
TCP/IP connection. ServerSocket's accept( ) method
returns a
regular Socket object that completes the
connection to the client. Then streams
can be opened
on the socket and a read write dialogue can take place.

ServerSocket has three constructors. The first takes
a single argument for the port. In this constructor, the
socket will 'backlog' connections to a default value of 50.
Requests for connections are queued up to 50 after
which requests are refused.

Another constructor allows specifying the port number
and queue length. The third constructor allows specifying
a specific IP address for use on a multi-homed host. In
this form the ServerSocket object will only accept connect
requests on the specified IP address.


Server Socket Constructors

ServerSocket(int port)
ServerSocket(int port, int backlog)
ServerSocket(int port, int backlog, InetAddress bindAddr)

// third constructor is for use in multi-homed networks


Multi-Threaded Servers

Thread objects can be combined with the server to create
a server that is multi-threaded capable of serving several
client requests concurrently. Opening too many threads
on the other hand can become counter-productive in
terms of the use of system resources.

A compromise is the creation of a multi-threaded example
that limits the number of thread that are deployed. Because
this is really more an issue of multi-threading we defer
creating a multi-threaded server to the section on Threads.


The SocketPermission Class

SocketPermission is an extension of the Permission class.
As one might expect, Permission is a class in
the java.security
package. SocketPermission provides the means to control
network
access via socket objects. The SocketPermission
constructor allows associating a
set of actions to a given host.

The possible connect modes are as follows:


Connection Modes

These directives can be supplied in combination in a list
of comma-separated
entries that is then put together in
a string literal. 
The "listen" action is only used with
"localhost". The "resolve" action (which involves resolving
Host/IP name service lookups) is provided implicitly when
any of the other actions are specified.

Following are a few examples from the Sun documentation.

Examples from the Sun Documentation

p1 = new SocketPermission
              ("puffin.eng.sun.com:7777", "connect,accept");

// allows connection to port 7777 on puffin.eng.sun.com,
// & accept connections on that port.

p2 = new SocketPermission
                   ("localhost:1024-", "accept,connect,listen");

// allows this code to accept connections on, connect to,
// or listen on ports between 1024 and 65535 on the local host.


The documentation points out that there are security concerns
in granting permission to accept or make connections to remote
hosts. Use of this class would fall under the general context of a
security policy that was configured to protect a network or service.


Internet Protocols



Internet programs run at the top level of the Network Model.
The most widely known and popular programs that run at the
application layer are HTTP or Hypertext Transfer Protocol.
The world of Web browsers requesting HTML pages from
Web servers is all executed over the HTTP protocol in a
distributed application we call the World Wide Web.

The well know port of HTTP is the number 80. FTP or File
Transfer Protocol is popular for downloading (and less well
known for uploading) files quickly over the net. FTP's well
known port number is 21. SMTP is an acronym for 'Simple
Mail Transfer Protocol' and is at the heart of the E-mail
application which is a phenomena in itself. E-Mail apps run
over port 25.

// HTTP --> port 80, FTP --> port 21, SMTP --> port 25

Private protocols can be created and it is often desirable
to do so to create proprietary
communication schemes. In
Java, protocols can be conveniently defined in interfaces

that both the client and server implement.

// have read that using interfaces to define elements of
// a protocol might not be the best design approach
 

Table of Some Well Known Port Numbers for Common Internet Protocols
 

Name of Protocol

Well Known Port Number

 File Transfer Protocol 

  21

 Simple Mail Transfer Protocol

  25

 Domain Name Service 

  53

 Hypter Text Transfer Protocol 

  80



SMTP


The SMTP protocol is a good example of an application
level Internet protocol. Once a TCP/IP connection is made
the protocol requires an exchange of 'words' between the
client and server. After 'getting to know each other' the client
submits the message to the server signalling it is finished.
the server then sends the message to the destination. The
following table hold key information from the original SMTP
RFC written in 1982 by Jonathan Postel (a name to match
the mission!).

RFC 821 - Simple Mail Transfer Protocol   
August 1982  Jonathan B. Postel


 // all quoted from RFC 821

 The objective of Simple Mail Transfer Protocol (SMTP)
 is to transfer mail reliably and efficiently.

    Example of the SMTP Procedure

 This SMTP example shows mail sent by Smith at host
 Alpha.ARPA, to Jones, Green, and Brown at host
 Beta.ARPA.  Here we assume that host Alpha contacts
 host Beta directly.

     S: MAIL FROM:<Smith@Alpha.ARPA>
     R: 250 OK

     S: RCPT TO:<Jones@Beta.ARPA>
     R: 250 OK

     S: RCPT TO:<Green@Beta.ARPA>
     R: 550 No such user here

     S: RCPT TO:<Brown@Beta.ARPA>
     R: 250 OK

     S: DATA
     R: 354 Start mail input; end with <CRLF>.<CRLF>
     S: Blah blah blah...
     S: ...etc. etc. etc.
     S: <CRLF>.<CRLF>
     R: 250 OK

  The mail has now been accepted for Jones and
  Brown.  Green did not have a mailbox at host Beta.     
 


Note after we have a Socket Connection, and we have streams
ready to read and write, it is character data like that described
above in RFC 821 that is sent between the client and server. In
other words, we are in the position to implement this protocol in
Java with the java.net classes we have described.

The following code is long because it includes a GUI along with
the code needed to send e-mail. It is easy to analyse though as
the GUI is built in the constructor while the socket connections
and protocol exchanges are done inside the submit( ) method.

I must warn you, with modern-day firewalls, e-mail you send with
the following code may or may not get through. A 550 reply may
indicate a denial of access for reasons associated with a
security policy.

Generally you will have more success at a location where you
have an account, so the origin matches the stated e-mail address.

In the following code a machine( ) method extracts the IP name
from the e-mail address. The following short code section shows
it in action by itself.

Example

//input to method is 'pkomisar@sentex.net'

class Machine{
  public static void main(String[]args){
  System.out.println(machine("pkomisar@sentex.net"));
   }
static String machine(String address){
   int index=0;
   index=address.indexOf('\u0040'); // @ symbol
   address=address.substring(index+1); // string after @ symbol
   address="mail." + address; // prefix with 'mail.'
   return address;
   }
}

OUTPUT

>java Machine

mail.sentex.net


Following is the complete mail application.

 
The SMTP Protocol Code Sample

// thanks to John Dantzer for code improvements

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


public class EMailer implements ActionListener{

     JFrame frame;
     JButton clear,submit;
     private JTextArea text;
     private JTextField fieldTo,fieldFrom, fieldSubject;
     String subject;
     String message;
     String recipient;
     String sender;
     String store;
     String machine;
      Socket sock;
     DataInputStream dis;
     PrintStream ps;
     InputStreamReader isr;
     BufferedReader bis;

  EMailer(){
            frame=new JFrame("E-Mailer");
            frame.setBackground(new Color(202,202,208));
            JPanel address=new JPanel();
            address.setLayout(new GridLayout(3,6));

            JLabel labelTo=new JLabel("        To");
            address.add(labelTo);
            fieldTo=new JTextField("");
            address.add(fieldTo);
            JLabel fill1=new JLabel("   ");
            address.add(fill1);
            JLabel labelFrom=new JLabel("        From");
            address.add(labelFrom);
            fieldFrom=new JTextField("");
            address.add(fieldFrom);   // all quoted from RFC 821
            JLabel fill2=new JLabel("    ");
            address.add(fill2);
            JLabel labelSubject=new JLabel("    Subject");
            address.add(labelSubject);
            fieldSubject=new JTextField("");
            address.add(fieldSubject);  

            frame.add(address,BorderLayout.NORTH);

            JPanel message=new JPanel();
            message.setLayout(new BorderLayout());
            message.add(new Label("E Mail Message"),BorderLayout.NORTH);
            text=new JTextArea("");
            text.setWrapStyleWord(true);
            text.setLineWrap(true);
 
            message.add(text);
            frame.add(message,BorderLayout.CENTER);

            JPanel controls=new JPanel();
            clear=new JButton("Clear");
            submit=new JButton("Submit");
            clear.addActionListener(this);
            submit.addActionListener(this);
              
            controls.add(clear);
            controls.add(submit);
            frame.add(controls,BorderLayout.SOUTH);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            frame.add(new Label("    "),BorderLayout.EAST);
            frame.add(new Label("    "),BorderLayout.WEST);
            frame.setSize(600,400);
            frame.setVisible(true);
            }
 

public static void main(String args[]){
           new EMailer();
           }

public void actionPerformed(ActionEvent ae){
         if(ae.getSource().equals(clear)){
          text.setText("");
          }
         if(ae.getSource().equals(submit)){
           store=text.getText();
          text.setText("Submitting. . .");
          try{
             submit();
              
             }catch(IOException io){ text.setText("IO Exception thrown"); }
          }
        }

// submit method
void submit() throws IOException{
   // get text
   System.out.println("1. Getting fields");
   message=store.trim();
   recipient=fieldTo.getText().trim();
   sender=fieldFrom.getText().trim();
   subject=fieldSubject.getText().trim();
   machine=machine(sender);

    System.out.println("2. Have fields");
    // get streams
    System.out.println("3. Getting connection");
    sock=new Socket(machine,25);
    dis = new DataInputStream(sock.getInputStream( ));
    isr= new InputStreamReader(dis);
    bis = new BufferedReader(isr);    // buffered in
    ps=new PrintStream(sock.getOutputStream( ));

   System.out.println(bis.readLine());  
    // added wait on server

    System.out.println("3. Have connections doing protocol");
    // do protocol
    ps.println("Helo " + machine);
    System.out.println(bis.readLine( ));
    ps.println("mail from: " + sender);
    System.out.println(bis.readLine( ));
    ps.println("rcpt to: " + recipient);
    System.out.println(bis.readLine());
    ps.println("Data" );
    System.out.println(bis.readLine());

    ps.println("Subject: " + subject);
    ps.println(message);

   // println terminates with the line separator
   //  appropriate for the underlying system

    ps.println( );
    ps.println(".");
    ps.println( );
       

    System.out.println(bis.readLine());
    ps.flush( );
    sock.close( );
    text.setText("Message sent");
    frame.setTitle("Message sent");
    System.out.println("4. Sockets closed ");
   }

  // method to convert an e-address to a machine domain name

   String machine(String address){
   int index=0;
   index=address.indexOf('\u0040'); // @ symbol
   address=address.substring(index+1); // string after @ symbol
   address="mail." + address; // prefix with 'mail.'
   return address;
   }
}


Other Classes of the java.net Package

Besides the socket classes the java.net package offers
many classes that encapsulate
  objects that are used on
the World Wide Web, the network is now largely based
on the HTTP protocol. One of the key aspects of the 'web'

is the use of the URL or Uniform Resource Locator. The
URL is a subset of the larger
group called URI's or Uniform
Resource Locators.


URL Classes 



The URL Class

Class URL encapsulates a Uniform Resource Locator
which can be used to locate
a resource on the World
Wide Web. A resource might be a text or image file, a
directory or more complicated objects like connections
to database resources or CORBA objects on servers.

The URL class has six constructors which are listed
below. The first noted opens on a String representation
of a URL. The second  will create a URL object by
specifying the component aspects of a URL, that is the
protocol, the host machine, the port number and the
destination file. Other constructors take combinations
of URL, String and URLStreamHandler objects.


URL constructors


Following is an example showing one of the constructor's in
use. It shows how the class can be used to cobble together
a complete URL from pieces.

Example

import java.net.*;

class URLer{
  public static void main(String[]args){
 URL url =null;
try{
   url = new URL("http","www.zoo.com", 80,"/homesite.html");
  }
catch(MalformedURLException mue){
    mue.printStackTrace();
   }
  System.out.println(url);
   }
}

OUTPUT

http://www.zoo.com:80/homesite.html


URL Class Methods

There is a set of informational retrieving methods that
return information about
the Uniform Resource Locator.
Methods like getPort( ), getFile( ), getHost( ),
getPath( ),
getProtocol( ), getQuery( ), and getRef( ) all return
information
about the URL object.

// firewalls impede some of these methods from working

The URL class supplies two approaches for making
connections to  the URL's they reference. The

openConnection( ) method returns a URLConnection
object. This class
object has many more methods that
are useful in the HTTP environment.
There is also an
openStream( ) method that connect to the URL and
returns an
InputStream for reading and writing.

The following example shows both the URL and
InetAddress classes in use showing a sample of
method calls made on both.


URL Code Sample

// sample calls from the InetAddress and the URL class

import java.net.*;
import java.io.*;
class netT{
  public static void main(String args[ ]){
    int length=0;
    BufferedInputStream bis;
    try{

 // InetAddress methods

      InetAddress local=InetAddress.getLocalHost( );
      System.out.println(local);

     InetAddress byName=InetAddress.getByName("www.abcnews.com");
     System.out.println(byName);

     InetAddress[] allNames=InetAddress.getAllByName("www.zdnet.com");
     for(int i=0;i<allNames.length;i++)
         System.out.println(allNames[i]);

 // URL methods

     URL u=new URL("http://www.abcnews.org");
     System.out.println("   File: "    + u.getFile( ) +
                       "\n Host: "     + u.getHost( ) +
                       "\n Port: "     + u.getPort( ) +
                       "\n Protocol: " + u.getProtocol( ) +
                       "\n hashCode: " + u.hashCode( )
                       );
    }
    catch(UnknownHostException uhe){
      System.out.println("Unknown Host");
     }
    catch(IOException ioe){
       System.out.println("IO exception");
      }
   }
}  

URLConnection  // no constructor!

The abstract URLConnection doesn't supply a constructor.
Instead the URL
class supplies the openConnection( )
method that returns a URLConnection
object. The class
has
forty-odd information retrieving and connection methods
that can be used once the class object is available.

// no constructor, instead has an openConnection( )  method

Instances of URLConnection can be used both to read and
write to the resource referenced by the URL. The Java API
describes a general approach to using the class is to obtain
a URLConnection from the URL class openConnection( )
method. The actual connection to the resource is then made
using the connect( ) method. Then the header fields and
contents can be accessed.

In the following code sample the URLConnection's version
of getInputStream( ) was used instead to make a steaming
connection over which the contents of the page being requested
was downloaded.

To access header fields and contents there are methods
such as getContent( ) and getHeaderField( ). Other info
can be obtained using the methods, getContentEncoding( ),
getContentLength( ), getContentType( ), getDate( ),
getExpiration( ) and getLastModifed( ).

A Few URLConnection Methods

In the following code sample the URL openConnection( )
method is used to get
a handle to a URLConnection object.
The getContentLength( ) method of the
URLConnection
class returns the number of bytes that make up the body
of the
page. This number is used to read the correct number
of bytes in a for loop. A
RandomAccessFile is used to send
the content to file on the local file system.
You can test this
program by opening on any page on the Internet, downloading

it with this program and then opening the page in a web browser.  


Another Technique for Looping File Content

The following code uses the URLConnection class
getContentLength( )  method. This value can be used
to limit a 'for loop' that reads the bytes from the file.


URLConnection Code Sample
 
  

// * code referenced in exercise

import java.net.*;
import java.io.*;

class netT2{
  public static void main(String args[]){
    int length=0;
    BufferedInputStream bis;
    try{

      URL u=new URL("http://www.sentex.net");
      URLConnection url=u.openConnection( );
      System.out.println("The Connection has been made");
      length=url.getContentLength( );
      System.out.println("Content length is " + length);

      bis=new BufferedInputStream(url.getInputStream());
      RandomAccessFile raf=new RandomAccessFile("page.html","rw");
      String s;
      for(int i=0;i<length;i++){
      int octet=bis.read();
      raf.writeByte(octet);
      }
      System.out.println
("The file page.html should be viewable in a browser.");
 

   }
    catch(MalformedURLException mue){
    System.out.println("malformed url");
    }
    catch(IOException ioe){
    System.out.println("IO exception");
   }
 }
}

JarURLConnection  // Just for Reference

URLConnection is an abstract class representing a connection
to a URL
object. It is the superclass of HttpURLConnection and
JarURLConnection. Following is a few facts about JarURLConnection.


Note on JarURLConnection

JarURLConnection extends URLConnection 
// reference quoted from JDK documentation

 A URL Connection to a Java ARchive (JAR) file or an entry in a JAR file.

 The syntax of a JAR URL is:

 jar:<url>!/{entry}

  for example:

 jar:http://www.foo.com/bar/baz.jar!/COM/foo/Quux.class

Jar URLs should be used to refer to a JAR file or entries in  a JAR file. The example above is a JAR URL which refers  to a JAR entry. If the entry name is omitted, the URL refers to the whole JAR file:

 jar:http://www.foo.com/bar/baz.jar!/

  Users should cast the generic URLConnection to a JarURLConnection when they know that the URL they  created is a JAR URL, and  they need JAR-specific functionality. For example:

  URL url = new URL("jar:file:/home/duke/duke.jar!/");
JarURLConnection jarConnection =
(JarURLConnection)url.openConnection( );

Manifest manifest = jarConnection.getManifest( );


URLDecoder

URLDecoder is a handy utility class that contains a single
static method called
decode( ). The method converts from
the MIME encoding format, with a self-describing name,

"x-www-form-urlencoded",
to a String type. In headers
the form MIME form is '
application / x-www-form-urlencoded'.
To convert to a String, each character is examined in turn
according to the following rules.

Character Conversion Rules

1.  The ASCII characters 'a' through 'z', 'A' through 'Z', and '0'
through '9' remain the same. 

2. 
The plus sign '+' is converted into a space character ' '.

3. The remaining characters are represented by 3-character
strings which begin with the  percent sign followed by 'xy', as
in  "%xy", where xy is the two-digit hexadecimal representation
of the lower 8-bits of the ch
aracter.


The following code sample contains a very hypothetical
URL. The main purpose is to show how the decode( )
method converts '+' symbols to spaces, and how special
characters are escaped using the % sign and a hexadecimal
value in the range of a byte.


URLDecoder Code Sample

import java.net.*;

class Decoder{
public static void main(String[]args){
String string =URLDecoder.decode
("www.cnn.com/cgi/obj+?+color=blue+&+type=large9+&+cyph=+%2F");
System.out.println(string);    
// URL is not real just an example of the actions
}
}

On compilation, the compiler reports that the decode( )
method is deprecated. Running the suggested flags
indicates what it's replacement is. The following table
shows the new recommended method version of decode( )
that includes a String parameter that describes the
encoding used. The W3C recommends specifying
"UTF-8" to avoid irregularities created between different
computer platforms.

 

 The decode( ) Method Deprecation   
// from the Java JDK1.4 documentation


 The single string form of decode has been deprecated.
 Instead the double String version should be used
 (shown below.) 

 public static String decode(String s, String enc)
 throws UnsupportedEncodingException   

 Decodes a application/x-www-form-urlencoded string
 using a specific encoding scheme. The supplied
 encoding is used to determine what characters are
 represented by any consecutive sequences of the
 form "%xy".

 Note: The World Wide Web Consortium Recommendation
 states that UTF-8 should be used. Not doing so may
 introduce 
"incompatibilites". 


Following is the code rewritten using the two String
version of decode( ). You need to catch for the
UnsupportedEncodingException which is in the
java.io package.  The following code imports the
needed exception by adding the import java.io.*;
statement.
 

Example Using the Recommended Decode( ) method and UTF-8 Encoding

import java.net.*;
import java.io.*;

class NewDecoder{
public static void main(String[]args){
try{
String string =URLDecoder.decode
("www.cnn.com/cgi/obj+?+color=blue+&+type=large9+&+cyph=+%2F","UTF-8");
System.out.println(string);   
 
// URL is not real just an example of the actions
}
catch(UnsupportedEncodingException uee){
   System.out.println(uee);
   // taking advantage of Object's toString( ) method
     }
  }
}

URLEncoder

The URLEncoder class supplies the encode( ) method
to do the reverse
function of the URLDecoder decode( )
method. A String is supplied to
show how the encode( )
method will put this String into the World Wide
Web's
"x-www-form-urlencoded" form.

URLEncoder Sample Using Deprecated Method

import java.net.*;

class Encoder{
public static void main(String[]args){
String string =URLEncoder.encode
("www.bbc.uk/cgi/ ? color=blue type=large sym1=@ sym2=#");
System.out.println(string);
}
}

The same deprecation applies to the encode( ) method
as was applied to the decode( ) method. Following is
the revised code that covers these same issues.

Revised URLEncoder Sample

import java.net.*;
import java.io.*;

class Encoder{
public static void main(String[]args){
try{
   String string =URLEncoder.encode
   ("www.bbc.uk/cgi/ ? color=blue type=large sym1=@ sym2=#","UTF-8");
   System.out.println(string);
   }
catch(UnsupportedEncodingException uee){
   System.out.println(uee);
   // taking advantage of Object's toString( ) method
   }
  }
 }

URLStreamHandler  // for reference
//  URLStreamHandler information from JDK documentation

The abstract class URLStreamHandler is the parent of
all stream protocol handlers. A stream protocol handler
is a 'smart' object that knows how to make a connection

for any of a number of protocol types. ( i.e HTTP or FTP ).
Usually a URLStreamHandler
subclass is not built explicitly
by an application. Instead, the first time a protocol name
is
encountered when constructing a URL, the appropriate
stream protocol handler is
automatically loaded.


URLClassLoader
     // for reference

URLClassLoader can access an array of bytes over a
network by referencing a URL. It then can reconstruct
the class inside the runtime environment of the Java
Virtual
Machine.


Net Package Exception Classes & Interfaces



Many Exception classes have been created to handle

problems that might arise in using the java.net classes.
For the most part their names allude
to where they would
be used. For the record, they are listed in the table below
followed
by interfaces that are part of the net package. 
 

 The java.net package Exceptions

 The java.net Package Interfaces

 BindException 
 ConnectException
 MalformedURLException
 NoRouteToHostException
 ProtocolException
 SocketException
 UnknownHostException
 UnknownServiceException

 ContentHandlerFactory
 FileNameMap
 SocketImplFactory
 SocketOptions
 URLStreamHandlerFactory




Self Test                                                 Self Test With Answers



1) Which of the following is not a Socket constructor

a) Socket ( InetAddress address, int port )
b) Socket ( String host, int port )
c) Socket(String host)

2) Which of the following is not correct?

a) InetAddress encapsulates both the numerical IP address
   and the domain name for that address.
b) The InetAddress constructor takes the IP address and
    corresponding domain name
c) The InetAddress methods like getLocalHost( ), getByName( )
    and getAllByName( ). are all static.
d) getByName( ) will return an IP address when passed a
   domain name  

3) ICANN reserves which of the following ranges of TCP/IP
    port numbers?

a) 1  to 1023
b) 2000 to 2999
c) 6000 to 6999
d) 1 to 65,535
 

4) Regarding ServerSocket which of the following is not an
   argument that
the constructors accept?

a) int port
b) int backlog
c) InetAddress bindAddr
d) String protocol

5) Which of the following well known port numbers is not correct?

a) DNS        50
b) SMTP      25
c) FTP          21
d) HTTP       80

6) True or False. URLConnection has one constructor that
   can be used to create a URLConnection object?

7) Which of the following statements is not correct?
  In x-www-form-urlencoding

a) ASCII characters 'a' through 'z', 'A' through 'Z' and '0' through '9' remain the same.
b) Other characters are escaped using 3-character strings which begin with a %
c) The escaped characters are numerically represented using decimal numbers
d ) The plus sign '+' is converted into a space character ' '.
 


Exercise



Lab 

1 ) Run the E-mailer both at the campus and at home. Report
briefly if you were able to get any mail through with it. Generally
if you are at the location where your mail is hosted you should
be successful in using the mailer to mail. On the other hand,
there are firewalls and filters who will recognize that this is not
coming from a browser they are familiar with.

2 ) Run the URLConnection program on a target site. Did you
capture the page! Test in a regular browser.' Briefly report the
result.

3) Surf to generate a relatively complicated URL. Copy it and
run it through the URLDecoder to remove (at least some of ) the
URL extraneous symbols.

Example

http://www.google.com/search?ie=UTF-8&oe=utf-8&q=Wind+Generators+!%40%23%24%25


Code You Will Use


import java.net.*;
import java.io.*;

class NewDecoder
{

public static void main(String[]args)
 {
 try{
   String string =URLDecoder.decode
   ("http://www.google.com/search?ie=UTF-8&oe=utf-8&q=Wind+Generators+!%40%23%24%25","UTF-8");
   System.out.println(string);   
   }
catch(UnsupportedEncodingException uee)
   {
   System.out.println(uee);
   }
 }
}

OUTPUT  // show output

>java NewDecoder
http://www.google.com/search?ie=UTF-8&oe=utf-8&q=Wind Generators !@#$%


Reading Suggestion!

The assignment is light which might make some time to
read over the first four notes of the course!