AJP Unit-4
AJP Unit-4
AJP Unit-4
Computers running on the Internet communicate to each other using either the Transmission Control
Protocol (TCP) or the User Datagram Protocol (UDP), as this diagram illustrates:
When you write Java programs that communicate over the network, you are programming at the
application layer. Typically, you don't need to concern yourself with the TCP and UDP layers.
Instead, you can use the classes in the java.net package.
Java is a premier language for network programming. java.net package encapsulate large number of
classes and interface that provides an easy-to use means to access network resources. Here are some
important classes and interfaces of java.net package.
Classes:
CacheRequest InetAddress Proxy URL
CookieManager Socket Datagrampacket URLConnection
CookieHandler ServerSocket DatagramSocket
Interfaces:
CookiePolicy CookieStore SocketImplFactory
FileNameMap SocketOption ProtocolFamily
Through the classes in java.net, Java programs can use TCP or UDP to communicate over the
Internet. The URL, URLConnection, Socket, and ServerSocket classes all use TCP to communicate
over the network. The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use
with UDP.
The Internet Protocol (IP) is the method or protocol by which data is sent from one computer to
another on the Internet. Each computer (known as a host) on the Internet has at least one IP address
that uniquely identifies it from all other computers on the Internet.
Because a message is divided into a number of packets, each packet can, if necessary, be sent by a
different route across the Internet. Packets can arrive in a different order than the order they were
sent in. The Internet Protocol just delivers them. It's up to another protocol, the Transmission Control
Protocol (TCP) to put them back in the right order.
IP is a connectionless protocol, which means that there is no continuing connection between the end
points that are communicating. Each packet that travels through the Internet is treated as an
independent unit of data without any relation to any other unit of data. (The reason the packets do get
put in the right order is because of TCP, the connection-oriented protocol that keeps track of the
packet sequence in a message.)
Internet Protocol hierarchy contains several classes of IP Addresses to be used efficiently in various
situations as per the requirement of hosts per network. Broadly, the IPv4 Addressing system is
divided into five classes of IP Addresses. All the five classes are identified by the first octet of IP
Address.
Internet Corporation for Assigned Names and Numbers is responsible for assigning IP addresses.
The first octet referred here is the left most of all. The octets numbered as follows depicting dotted
decimal notation of IP Address:
The number of networks and the number of hosts per class can be derived by this formula:
When calculating hosts' IP addresses, 2 IP addresses are decreased because they cannot be assigned
to hosts, i.e. the first IP of a network is network number and the last IP is reserved for Broadcast IP.
Class A Address
The first bit of the first octet is always set to 0 (zero). Thus the first octet ranges from 1 – 127, i.e.
Class A addresses only include IP starting from 1.x.x.x to 126.x.x.x only. The IP range 127.x.x.x is
reserved for loopback IP addresses.
Class B Address
An IP address which belongs to class B has the first two bits in the first octet set to 10, i.e.
Class B IP Addresses range from 128.0.x.x to 191.255.x.x. The default subnet mask for Class B is
255.255.x.x.
Class C Address
The first octet of Class C IP address has its first 3 bits set to 110, that is:
Class C IP addresses range from 192.0.0.x to 223.255.255.x. The default subnet mask for Class C is
255.255.255.x.
Class D Address
Very first four bits of the first octet in Class D IP addresses are set to 1110, giving a range of:
Class D has IP address rage from 224.0.0.0 to 239.255.255.255. Class D is reserved for Multicasting.
In multicasting data is not destined for a particular host, that is why there is no need to extract host
address from the IP address, and Class D does not have any subnet mask.
Class E Address
This IP Class is reserved for experimental purposes only for R&D or Study. IP addresses in this class
ranges from 240.0.0.0 to 255.255.255.254. Like Class D, this class too is not equipped with any
subnet mask.
2) (224 – 2)
128 – 16,382 65,534 (216 –
B 10 N.N.H.H 255.255.0.0
191 (214 – 2) 2)
192 – 2,097,150
C 110 N.N.N.H 255.255.255.0 254 (28 – 2)
223 (221 – 2)
224 –
D 1110 Reserved for Multicasting
239
240 –
E 1111 Experimental; used for research
254
1. TCP
When two applications want to communicate to each other reliably, they establish a connection and
send data back and forth over that connection. This is analogous to making a telephone call. Like the
phone company, TCP guarantees that data sent from one end of the connection actually gets to the
other end and in the same order it was sent. Otherwise, an error is reported.
TCP provides a point-to-point channel for applications that require reliable communications. The
Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of
applications that require a reliable communication channel. The order in which the data is sent and
received over the network is critical to the success of these applications. When HTTP is used to read
from a URL, the data must be received in the order in which it was sent. Otherwise, you end up with a
jumbled HTML file, a corrupt zip file, or some other invalid information.
TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of
data between two computers.
2. UDP
The UDP protocol provides for communication that is not guaranteed between two applications on the
network. UDP is not connection-based like TCP. Rather, it sends independent packets of data,
called datagrams, from one application to another. Sending datagrams is much like sending a letter
through the postal service: The order of delivery is not important and is not guaranteed, and each
message is independent of any other. Sending datagrams is much like sending a letter through the mail
service: The order of delivery is not important and is not guaranteed, and each message is independent
of any others.
UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called
datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-
based like TCP.
Another example of a service that doesn't need the guarantee of a reliable channel is the ping
command. The purpose of the ping command is to test the communication between two programs
over the network. In fact, ping needs to know about dropped or out-of-order packets to determine how
good or bad the connection is. A reliable channel would invalidate this service altogether.
A DNS server is requested with FQDN and it responds back with the IP address mapped with it.
DNS uses UDP port 53.
Message Transfer Agent uses SMTP to forward the email to another Message Transfer Agent
(Server side). While SMTP is used by end user to only send the emails, the Servers normally use
SMTP to send as well as receive emails. SMTP uses TCP port number 25 and 587.
Client software uses Internet Message Access Protocol (IMAP) or POP protocols to receive emails.
FTP uses out-of-band controlling i.e. FTP uses TCP port 20 for exchanging controlling information
and the actual data is sent over TCP port 21.
The client requests the server for a file. When the server receives a request for a file, it opens a TCP
connection for the client and transfers the file. After the transfer is complete, the server closes the
connection. For a second file, client requests again and the server reopens a new TCP connection.
When a client needs to retrieve mails from server, it opens a connection with the server on TCP port
110. User can then access his mails and download them to the local computer. POP3 works in two
modes. The most common mode the delete mode, is to delete the emails from remote server after
they are downloaded to local machines. The second mode, the keep mode, does not delete the email
from mail server and gives the user an option to access mails later on mail server.
To access the web pages, a client normally uses web browsers, who are responsible for initiating,
maintaining, and closing TCP connections. HTTP is a stateless protocol, which means the Server
maintains no information about earlier requests by clients.
HTTP versions
HTTP 1.0 uses non persistent HTTP. At most one object can be sent over a single TCP
connection.
HTTP 1.1 uses persistent HTTP. In this version, multiple objects can be sent over a single
TCP connection.
3.5 Ports
Generally speaking, a computer has a single physical connection to the network. All data destined for
a particular computer arrives through that connection. However, the data may be intended for
different applications running on the computer. So how does the computer know to which application
to forward the data? Through the use of ports.
Data transmitted over the Internet is accompanied by addressing information that identifies the
computer and the port for which it is destined. The computer is identified by its 32-bit IP address,
which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit
number, which TCP and UDP use to deliver the data to the right application.
In connection-based communication such as TCP, a server application binds a socket to a specific port
number. This has the effect of registering the server with the system to receive all data destined for
that port. A client can then rendezvous with the server at the server's port, as illustrated here:
The TCP and UDP protocols use ports to map incoming data to a particular process running on a
computer.
In datagram-based communication such as UDP, the datagram packet contains the port number of its
destination and UDP routes the packet to the appropriate application, as illustrated in this figure:
Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port
numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such
as HTTP and FTP and other system services. These ports are called well-known ports. Your
applications should not attempt to bind to them.
3.6 InetAddress
InetAddress encapsulates both numerical IP address and the domain name for that address. Inet
address can handle both IPv4 and Ipv6 addresses. InetAddress class has no visible constructor. To
create an inet Address object, you have to use Factory methods.
Method Description
public static InetAddress getByName(String host) It returns the instance of InetAddress containing
throws UnknownHostException LocalHost IP and name.
public static InetAddress getLocalHost() It returns the instance of InetAdddress containing
throws UnknownHostException local host name and address.
static InetAddress[] getAllByName (String Determines all the IP addresses of a host, given the
hostname) throws UnknownHostException host's name.
Method Description
public boolean equals(Object obj) compare this object with specified object
public byte[] getAddress() This method returns the IP address associated with this object as
an array of bytes in network order.
public String getHostAddress() This method returns a string representation of the IP address
associated with this object. For example: "206.175.64.78".
public String getHostName() Returns the hostname associated with this object.
public int hashCode() Returns the hashcode based on the IP address of the object.
public boolean isMulticastAddress() True if this object represents a multicast address; false otherwise.
toString This method returns a String that contains both the hostname and
IP address of this object.
Example:
import java.net.*;
class Test
{
public static void main(String[] args)
{
The two key classes from the java.net package used in creation of server and client programs are:
ServerSocket
Socket
A server program creates a specific type of socket that is used to listen for client requests (server
socket), In the case of a connection request, the program creates a new socket through which it will
exchange data with the client using input and output streams. The socket abstraction is very similar to
the file concept: developers have to open a socket, perform I/O, and close it. Figure 13.5 illustrates
key steps involved in creating socket-based server and client programs.
Socket class
In order to connect to a server over the internet (via TCP/IP) in Java, you need to create
a java.net.Socket and connect it to the server.
The Socket class has five constructors that a client uses to connect to a server:
SN Methods Description
1 public Socket(String host, int port) throws This method attempts to connect to the specified
UnknownHostException, IOException. server at the specified port. If this constructor does
not throw an exception, the connection is successful
and the client is connected to the server.
2 public Socket(InetAddress host, int port) This method is identical to the previous constructor,
throws IOException except that the host is denoted by an InetAddress
object.
3 public Socket(String host, int port, Connects to the specified host and port, creating a
InetAddress localAddress, int localPort) socket on the local host at the specified address and
throws IOException. port.
4 public Socket(InetAddress host, int port, This method is identical to the previous constructor,
InetAddress localAddress, int localPort) except that the host is denoted by an InetAddress
throws IOException. object instead of a String
SN Methods Description
1 public void connect(SocketAddress host, This method connects the socket to the specified
int timeout) throws IOException host. This method is needed only when you
instantiated the Socket using the no-argument
constructor.
2 public InetAddress getInetAddress() This method returns the address of the other
computer that this socket is connected to.
3 public int getPort() Returns the port the socket is bound to on the remote
machine.
4 public int getLocalPort() Returns the port the socket is bound to on the local
machine.
6 public InputStream getInputStream() Returns the input stream of the socket. The input
throws IOException stream is connected to the output stream of the
remote socket.
7 public OutputStream getOutputStream() Returns the output stream of the socket. The output
throws IOException stream is connected to the input stream of the remote
socket
8 public void close() throws IOException Closes the socket, which makes this Socket object no
longer capable of connecting again to any server
ServerSocket Class
In order to implement a Java server that listens for incoming connections from clients via TCP/IP, you
need to use a java.net.ServerSocket .
SN Methods Description
1 public ServerSocket(int port) throws Attempts to create a server socket bound to the
IOException specified port. An exception occurs if the port
is already bound by another application.
2 public ServerSocket(int port, int backlog) throws Similar to the previous constructor, the
IOException backlog parameter specifies how many
incoming clients to store in a wait queue.
3 public ServerSocket(int port, int backlog, Similar to the previous constructor, the
InetAddress address) throws IOException InetAddress parameter specifies the local IP
address to bind to. The InetAddress is used for
servers that may have multiple IP addresses,
allowing the server to specify which of its IP
addresses to accept client requests on
4 public ServerSocket() throws IOException Creates an unbound server socket. When using
this constructor, use the bind() method when
you are ready to bind the server socket
SN Methods Description
1 public int getLocalPort() Returns the port that the server socket is
listening on. This method is useful if you
passed in 0 as the port number in a constructor
and let the server find a port for you.
2 public Socket accept() throws IOException Waits for an incoming client. This method
blocks until either a client connects to the
server on the specified port or the socket times
out, assuming that the time-out value has been
set using the setSoTimeout() method.
Otherwise, this method blocks indefinitely
3 public void setSoTimeout(int timeout) Sets the time-out value for how long the server
socket waits for a client during the accept().
4 public void bind(SocketAddress host, int Binds the socket to the specified server and
backlog) port in the SocketAddress object. Use this
method if you instantiated the ServerSocket
using the no-argument constructor.
import java.net.*;
import java.io.*;
public class SimpleServer
{
public static void main(String args[]) throws IOException
{
ServerSocket s = new ServerSocket(1254); // Register service on port 1254
Socket s1=s.accept(); // Wait and accept a connection
import java.net.*;
import java.io.*;
public class SimpleClient
{
public static void main(String args[]) throws IOException
{
// Open your connection to a server, at port 1254
Socket s1 = new Socket("localhost",1254);
// Get an input file handle from the socket and read the input
InputStream In = s1.getInputStream();
DataInputStream dis = new DataInputStream(In);
String st = new String (dis.readUTF());
System.out.println(st);
dis.close();
In.close();
s1.close();
}
}
Output: hi there
DatagramPacket
DatagramSocket: Datagram Socket is used to send or receive Datagrams .
Constructors of DatagramPacket
DatagramPacket (byte[] buf, int off, int len) Constructs a DatagramPacket for receiving
packets of length len, specifying an offset of off
bytes into the buffer.
DatagramPacket ((byte[] buf, int len, Constructs a datagram packet for sending packets
InetAddress addr, int port) of length len to the specified port number on the
specified host.
DatagramPacker (byte[] buf, int off, int len, Constructs a datagram packet for sending packets
InetAddress addr, int port) of length len with offset off to the specified port
number on the specified host.
DatagramPacket (byte[] buf, int off, int len, Constructs a datagram packet for sending packets
SocketAddress addr) of length len with offset off to the specified port
number on the specified host.
Constructors of DatagramSocket
specified DatagramSocketImpl.
DatagramSocket (int port) Constructs a datagram socket and binds it to the
specified port on the local host.
DatagramSocket (int port, InetAddress iaddr) Creates a datagram socket, bound to the specified
local address.
DatagramSocket (SocketAddress bindaddr) Creates a datagram socket, bound to the
specified local socket address.
Example:
try
{
String s="hello, how are you";
aSocket = new DatagramSocket();
byte [] m = s.getBytes();
InetAddress aHost = InetAddress.getLocalHost();
int serverPort = 1234;
DatagramPacket request = new DatagramPacket(m, s.length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
System.out.println("Reply: " + new String(reply.getData()));
}
catch (Exception e) {
}
}
}
Constructor Desciption
URL (String spec) Creates a URL object from the String
representation.
URL (String protocol, String host, int port, String Creates a URL object from the specified protocol,
file) host, port number, and file.
URL (String protocol, String host, int port, String Creates a URL object from the specified protocol,
file, URLStreamHandler handler) host, port number, file, and handler.
URL (String protocol, String host, String file) Creates a URL from the specified protocol name,
host name, and file name.
URL (URL context, String spec) Creates a URL by parsing the given spec within a
specified context.
URL (URL context, String spec, Creates a URL by parsing the given spec with the
URLStreamHandler handler) specified handler within a specified context.
Methods Description
protected void set(String protocol, String host, int Sets the fields of the URL. This is not a public
port, String file, String ref) method so that only URLStreamHandlers can
modify URL fields. URLs are otherwise constant.
public int getPort() Gets the port number. Returns -1 if the port is not
set.
public String getProtocol() Gets the protocol name.
public String getHost() Gets the host name.
public String getFile() Gets the file name.
public String getPath () Gets the path part of URL
public String getQuery () Gets the query part of URL
public boolean equals(Object obj) Compares two URLs. Returns true if and only if
they are equal, false otherwise.
public URLConnection openConnection() Creates (if not already in existance) a
throws IOException URLConnection object that contains a connection
to the remote object referred to by the URL.
public final InputStream openStream() throws Opens an input stream.
IOException
public final Object getContent() throws Gets the contents from this opened connection.
IOException
Example:
import java.net.*;
class Test
{
public static void main(String[] arg)
{
try
15 Advanced java Programming
UNIT-4 Networking
{
URL hp = new URL("http://www.yahoo.com:80/index");
System.out.println(hp.getProtocol());
System.out.println(hp.getPath());
System.out.println(hp.getHost());
System.out.println(hp.getFile());
System.out.println(hp.getPort());
}
catch(MalformedURLException e){}
}
}
Ouput:
http
/index
www.yahoo.com
/index
80
3. The actual connection to the remote object is made, using the connect method.
4. The remote object becomes available. The header fields and the contents of the remote
object can be accessed.
protected boolean allowUserInteraction If true allow user interactions in the URL being
examined
protected boolean connected If true, the communications link has been
established.
protected boolean doInput Setting the doInput flag to true allows the
application to read data from the URL connection.
protected boolean doOutput Setting the doOutput flag to true allows the
application to write data to the URL connection.
protected long ifModifiedSince Returns the time in milliseconds since last
modified.
protected URL url The URL represents the remote object on the
World Wide Web to which this connection is
opened.
protected boolean useCaches If true, the protocol is allowed to use caching
whenever it can.
public Object getContent(Class[] classes)throws Retrieves the contents of this URL connection.
IOException
Example:
import java.net.*;
import java.io.*;
The java.security package contains the classes and interfaces that implement the Java security
architecture. These classes can be divided into two broad categories.
First, there are classes that implement access control and prevent untrusted code from performing
sensitive operations.
Second, there are authentication classes that implement message digests and digital signatures and can
authenticate Java classes and other objects.
The central access control class is AccessController; it uses the currently installed Policy object to
decide whether a given class has Permission to access a given system resource.
The Permissions and ProtectionDomain classes are also important pieces of the Java access control
architecture. Figure 1 shows the access control classes of this package.
The key classes for authentication are MessageDigest and Signature; they compute and verify
cryptographic message digests and digital signatures. These classes use public-key cryptography
techniques and rely on the PublicKey and PrivateKey classes. They also rely on an infrastructure of
related classes, such as SecureRandom for producing cryptographic-strength pseudo-random
numbers, KeyPairGenerator for generating pairs of public and private keys, and KeyStore for
managing a collection of keys and certificates.
The basic entity that the access controller operates on is a permission object--an instance of
the Permission class (java.security.Permission). The Permission class itself is an abstract class that
represents a particular operation. A permission object can reflect two things. When it is associated
with a class (through a code source and a protection domain), a permission object represents an actual
permission that has been granted to that class. Otherwise, a permission object allows us to ask if we
have a specific permission.
For example, if we construct a permission object that represents access to a file, possession of that
object does not mean that we have permission to access the file. Rather, possession of the object
allows us to ask if we have permission to access the file.
An instance of the Permission class represents one specific permission. A set of permissions--e.g., all
the permissions that are given to classes signed by a particular individual--is represented by an
instance of the Permissions class (java.security.Permissions).
Subclasses of the Permission class are required to implement their own test for equality. Often
this is simply done by comparing the name (and actions, if applicable) of the permission.
Subclasses of the Permission class are required to implement their own hash code. In order
for the access controller to function correctly, the hash code for a given permission object
must never change during execution of the virtual machine. In addition, permissions that
compare as equal must return the same hash code from this method.
Return the canonical form of the actions (if any) that were used to construct this permission.
The convention for printing a permission is to print in parentheses the class name, the name of
the permission, and the actions.
This method is one of the keys of the Permission class: it is responsible for determining
whether or not a class that is granted one permission is granted another. This method is
normally responsible for performing wildcard matching, so that, for example, the file
permission /myclasses/- implies the file permission /myclasses/xyz/HRApplet.class. But this
method need not rely on wildcards; permission to write a particular object in a database would
probably imply permission to read that object as well.
Return a permission collection suitable for holding instances of this type of permission. We'll
discuss the topic of permission collections in the next section. This method returns null by
default.
Call the security manager to see if the permission (i.e., the this variable) has been granted,
generating a SecurityException if the permission has not been granted. The object parameter
of this method is unused. We'll give more details about this method later in this chapter.
The third building block for the access controller is the facility to specify which permissions should
apply to which code sources. We call this global set of permissions the security policy; it is
encapsulated by the Policy class (java.security.Policy).
public Policy()
Create a policy class. The constructor should initialize the policy object according to its
internal rules
Like the security manager, only a single instance of the policy class can be installed in the virtual
machine at any time. However, unlike the security manager, the actual instance of the policy class can
be replaced. These two methods install and retrieve the policy:
Install the given policy object, replacing whatever policy object was previously installed.
Create a permissions object that contains the set of permissions that should be granted to
classes that came from the given code source (i.e., loaded from the code source's URL and
signed by the keys in the code source).
Refresh the policy object. For example, if the initial policy came from a file, re-read the file
and install a new policy object based on the (presumably changed) information from the file.
MCQ’s