Learning Center
Plans & pricing Sign in
Sign Out
Get this document free




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

Definition: TCP (Transmission Control Protocol) is a connection-based protocol that
provides a reliable flow of data between two computers.


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.

Definition: 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.

For many applications, the guarantee of reliability is critical to the success of the
transfer of information from one end of the connection to the other. However, other
forms of communication don't require such strict standards. In fact, they may be
slowed down by the extra overhead or the reliable connection may invalidate the
service altogether.

Consider, for example, a clock server that sends the current time to its client when
requested to do so. If the client misses a packet, it doesn't really make sense to
resend it because the time will be incorrect when the client receives it on the second
try. If the client makes two requests and receives packets from the server out of
order, it doesn't really matter because the client can figure out that the packets are
out of order and make another request. The reliability of TCP is unnecessary in this
instance because it causes performance degradation and may hinder the usefulness
of the service.
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.

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 from one application to another. 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.

Note: Many firewalls and routers have been configured not to allow UDP packets. If
you're having trouble connecting to a service outside your firewall, or if clients are
having trouble connecting to your service, ask your system administrator if UDP is

Understanding 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:

Definition: 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.

Networking Classes in the JDK

Through the classes in, 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.

Difference between socket and server socket

ServerSocket                                                                        :
/**Theoritacally speeking server is the one which process the response for the
request                                                                          **/
Server is the one which keep on listening the port to process the request. ence you
need the port number .To saywhere it should listen we need to give the following line
in                                   the                                     coding.

ServerSocket ssoc new ServerSocket(8000); // u can give ur own port number

Socket :
/** Theoritacally speaking client is the one which send the request to server and
waiting                   for                   the                   response**/

Socket class is used to send the request to the server waiting for responses .To send
the request we need the ip/hostname (address) of the server and the port in which it
actually                                                                    listening.

Socket soc new Socket( 8000);

Buffered Reader

Read text from a character-input stream, buffering characters so as to provide for
the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default is
large enough for most purposes.


An InputStreamReader is a bridge from byte streams to character streams: It reads
bytes and decodes them into characters using a specified charset. The charset that it
uses may be specified by name or may be given explicitly, or the platform's default
charset may be accepted.

Each invocation of one of an InputStreamReader's read() methods may cause one or
more bytes to be read from the underlying byte-input stream. To enable the efficient
conversion of bytes to characters, more bytes may be read ahead from the
underlying stream than are necessary to satisfy the current read operation.

Use of Flush()

Flushes this output stream and forces any buffered output bytes to be written out.
The general contract of flush is that calling it is an indication that, if any bytes
previously written have been buffered by the implementation of the output stream,
such bytes should immediately be written to their intended destination.

SSLServerSocket Factory

This class extends ServerSockets and provides secure server sockets using protocols
such as the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocols.

Instances of this class are generally created using a SSLServerSocketFactory. The
primary function of SSLServerSockets is to create SSLSockets by accepting

SSLServerSockets contain several pieces of state data which are inherited by
the SSLSocket at socket creation. These include the enabled cipher suites and
protocols, whether client authentication is necessary, and whether created sockets
should begin handshaking in client or server mode. The state inherited by the
created SSLSocket can be overriden by calling the appropriate methods.

SSL Socket

This class extends Sockets and provides secure socket using protocols such as the
"Secure Sockets Layer" (SSL) or IETF "Transport Layer Security" (TLS) protocols.

Such sockets are normal stream sockets, but they add a layer of security protections
over the underlying network transport protocol, such as TCP. Those protections
      Integrity Protection. SSL protects against modification of messages by an
       active wiretapper.
      Authentication. In most modes, SSL provides peer authentication. Servers are
       usually authenticated, and clients may be authenticated as requested by
      Confidentiality (Privacy Protection). In most modes, SSL encrypts data being
       sent between client and server. This protects the confidentiality of data, so
       that passive wiretappers won't see sensitive data such as financial information
       or personal information of many kinds.

These kinds of protection are specified by a "cipher suite", which is a combination of
cryptographic algorithms used by a given SSL connection. During the negotiation
process, the two endpoints must agree on a ciphersuite that is available in both
environments. If there is no such suite in common, no SSL connection can be
established, and no data can be exchanged.

The cipher suite used is established by a negotiation process called "handshaking".
The goal of this process is to create or rejoin a "session", which may protect many
connections over time. After handshaking has completed, you can access session
attributes by using the getSession method. The initial handshake on this connection
can be initiated in one of three ways:

      calling startHandshake which explicitly begins handshakes, or
      any attempt to read or write application data on this socket causes an implicit
       handshake, or
      a call to getSession tries to set up a session if there is no currently valid
       session, and an implicit handshake is done.

If handshaking fails for any reason, the SSLSocket is closed, and no futher
communications can be done.

There are two groups of cipher suites which you will need to know about when
managing cipher suites:

      Supported cipher suites: all the suites which are supported by the SSL
       implementation. This list is reported using getSupportedCipherSuites.
      Enabled cipher suites, which may be fewer than the full set of supported
       suites. This group is set using the setEnabledCipherSuites method, and
       queried using the getEnabledCipherSuites method. Initially, a default set of
       cipher suites will be enabled on a new socket that represents the minimum
       suggested configuration.

Implementation defaults require that only cipher suites which authenticate servers
and provide confidentiality be enabled by default. Only if both sides explicitly agree
to unauthenticated and/or non-private (unencrypted) communications will such a
ciphersuite be selected.

When SSLSockets are first created, no handshaking is done so that applications may
first set their communication preferences: what cipher suites to use, whether the
socket should be in client or server mode, etc. However, security is always provided
by the time that application data is sent over the connection.
You may register to receive event notification of handshake completion. This involves
the use of two additional classes. HandshakeCompletedEvent objects are passed
to HandshakeCompletedListener instances, which are registered by users of this
API.SSLSockets are created by SSLSocketFactorys, or by accepting a connection
from a SSLServerSocket.

A SSL socket may choose to operate in the client or server mode. This will determine
who begins the handshaking process, as well as which messages should be sent by
each party. However, each connection must have one client and one server, or
handshaking will not progress properly.

Data Link Layer

The second-lowest layer (layer 2) in the OSI Reference Model stack is the data link
layer, often abbreviated “DLL” (though that abbreviation has other meanings as well
in the computer world). The data link layer, also sometimes just called the link layer,
is where many wired and wireless local area networking (LAN) technologies primarily
function. For example, Ethernet, Token Ring, FDDI and 802.11 (“wireless Ethernet”
or “Wi-Fi’) are all sometimes called “data link layer technologies”. The set of devices
connected at the data link layer is what is commonly considered a simple “network”,
as opposed to an internetwork.

Data Link Layer Sublayers: Logical Link Control (LLC) and Media Access
Control (MAC)

The data link layer is often conceptually divided into two sublayers: logical link
control (LLC) and media access control (MAC). This split is based on the architecture
used in the IEEE 802 Project, which is the IEEE working group responsible for
creating the standards that define many networking technologies (including all of the
ones I mentioned above except FDDI). By separating LLC and MACfunctions,
interoperability of different network technologies is made easier, as explained in our
earlier discussion of networking model concepts.

Data Link Layer Functions

The following are the key tasks performed at the data link layer:

   o   Logical Link Control (LLC): Logical link control refers to the functions
       required for the establishment and control of logical links between local
       devices on a network. As mentioned above, this is usually considered a DLL
       sublayer; it provides services to the network layer above it and hides the rest
       of the details of the data link layer to allow different technologies to work
       seamlessly with the higher layers. Most local area networking technologies
       use the IEEE 802.2 LLC protocol.

   o   Media Access Control (MAC): This refers to the procedures used by devices
       to control access to the network medium. Since many networks use a shared
       medium (such as a single networkcable, or a series of cables that are
       electrically connected into a single virtual medium) it is necessary to have
            rules for managing the medium to avoid conflicts. For example. Ethernet uses
            the CSMA/CD method of media access control, while Token Ring uses token

        o   Data Framing: The data link layer is responsible for the final encapsulation
            of higher-level messages into frames that are sent over the network at the
            physical layer.

        o   Addressing: The data link layer is the lowest layer in the OSI model that is
            concerned with addressing: labeling information with a particular destination
            location. Each device on a network has a unique number, usually called
            a hardware address or MAC address, that is used by the data link layer
            protocol to ensure that data intended for a specific machine gets to it

        o   Error Detection and Handling: The data link layer handles errors that occur
            at the lower levels of the network stack. For example, a cyclic redundancy
            check (CRC) field is often employed to allow the station receiving data to
            detect if it was received correctly.

How Jpcap works

Jpcap uses an event model to allow you to process packets. To get started, you must
first create a class that implements the interface jpcap.JpcapHandler.

public class JpcapTip implements JpcapHandler {

    public void handlePacket(Packet packet){




In order to capture packets, you need to tell Jpcap which network device you want to
listen with. The API provides the jpcap.Jpcap.getDeviceList() method for this
purpose. The method returns an array of strings, and you use it like this:

String[] devices = Jpcap.getDeviceList();

Once you have a list of device names, you must choose one for listening:

String deviceName = devices[0];

After choosing a device, you open it for listening by using the method
Jpcap.openDevice(). The openDevice() method requires four arguments: the device
name to be opened, the maximum number of bytes to read from the device at one
time, a Boolean value specifying whether to put the device into promiscuous mode,
and a timeout value that will be used if you later call the processPacket() method.
Jpcap jpcap = Jpcap.openDevice(deviceName, 1028, false, 10000);

The openDevice() method returns a reference to a Jpcap object that will be used for
capturing. Now that you have the Jpcap instance, you can start listening by calling
either processPacket() or loopPacket(). Both of the methods take two arguments:
The maximum number of packets to capture can be -1 to indicate no limit and an
instance of a class that implements JpcapHandler.

If you call processPacket(), then Jpcap will capture packets until either the timeout
specified in openDevice is exceeded or the maximum number of packets specified
has been reached. loopPacket() will capture packets until the maximum number of
packets is reached or forever, if there is no maximum.


This class provides the functionality of a cryptographic cipher for encryption and
decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.

In order to create a Cipher object, the application calls the Cipher's getInstance
method, and passes the name of the requested transformation to it. Optionally, the
name of a provider may be specified.

A transformation is a string that describes the operation (or set of operations) to be
performed on the given input, to produce some output. A transformation always
includes the name of a cryptographic algorithm (e.g., DES ), and may be followed by
a feedback mode and padding scheme.

A transformation is of the form:

      " algorithm/mode/padding " or
      " algorithm "

(in the latter case, provider-specific default values for the mode and padding scheme
are used). For example, the following is a valid transformation:

   Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");

Encryption and Decryption

Encryption and decryption are done using a cipher. A cipher is an object that carries
out encryption and decryption according to an encryption scheme or algorithm.
When encrypting, a cipher produces data called cipher text, and when decrypting, a
cipher produces data called plain text.

Data Encryption

Making plain text into cipher text (unreadable text) is known as encryption, and
making cipher text into plain text is known as decryption. The javax.crypto package
lets you encrypt and decrypt data in one step, multiple steps, in streams, or in a
sealed object. All approaches require a Cipher object initialized for either the
encryption or decryption operation.

      javax.crypto.Cipher
      javax.crypto.CipherInputStream
      javax.crypto.CipherOutputStream
      javax.crypto.SealedObject

Symmetric Keys

Data is encrypted and decrypted with a key. There are two types of cryptography:
Secret-key or symmetric cryptography, and public-key or asymmetric cryptography.
JCE 1.2 supports both types of encryption. It provides the functionality to generate
symmetric     session    keys    for    symmetric     encryption,     and   leverage
the KeyPairGenerator class in the Java 2 platform for the creation of asymmetric key
pairs for asymmetric encryption.

Symmetric key cryptography uses a single key to encrypt and decrypt a message. If
someone uses a single key to encrypt a message he or she must find a secure means
of transmitting the key to the receiver for decryption. You can protect a secret key
by wrapping it under the public key(s) of its intended recipient(s) so only the
intended recipient(s) can unwrap it using their corresponding private key(s). An
alternative way to share a secret key is by using a key agreement. A key agreement
is a process used by two or more parties to agree upon a shared secret key without
exchanging any secret information.

      javax.crypto.KeyGenerator
      javax.crypto.SecretKey
      javax.crypto.SecretKeyFactory
      javax.crypto.MAC
      javax.crypto.KeyAgreement

Asymmetric key cryptography uses key pairs that consist of a public and private key
where the private key is mathematically linked to the public key. Asymmetric keys
are generated with the class.


The Cipher and KeyGenerator classes are central to data encryption and decryption.
The following pseudo code segments outline how you would use these and
other javax.crypto classes to encrypt and decrypt a short text string.

Note: Cryptography software is not exportable outside the U.S. and Canada, which
is why the examples in this section are pseudo code rather than source code.
Using Ciphers and Sealed Objects

The pseudo code segments for both examples assume two programs: an encryption
program and a decryption program. The encryption program uses a secret key to
encrypt a text string and a sealed object to wrap the secret key with the recipient's
public key. The decryption program receives the encrypted text and wrapped session
key over the network. It unwraps the secret key by using its private key, and uses
the recovered secret key to decrypt the message.

The SealedObject class can be used to seal any object that is serializable
(implements the interface). One of the arguments to
the SealedObject constructor is the object to be sealed, whose contents are
serialized and encrypted. TheSealedObject instance encapsulates those contents. The
encrypted contents are later unsealed and deserialized to yield the original object.

Encryption Side

The main method creates a Cipher object and SecretKey. Next, the generated
session key is used to initialize the Cipher object for encryption, and
the Cipher object is used to encrypt the message. The session key is sealed with the
intended recipient's public key and sent to the intended recipient with the encrypted

public static void main(String[] args) {
 Create a Cipher object for symmetric
         encryption (e.g., DES)
 Create a KeyGenerator object
 Use KeyGenerator to create a Secret (
                      session) key
 Initialize Cipher object for encryption
                   with session key
 Encrypt message
 Get intended recipient's public key (
                     e.g., from the
    recipient's public key certificate)
 Create Cipher for asymmetric encryption (
                    e.g., RSA), and
          initialize it for encryption with
          recipient's public key
 Create SealedObject to seal session key using
 asymmetric Cipher
   Serialize SealedObject
 Send encrypted message and serialized
 SealedObject to intended recipient

Decryption Side

The decryption application runs the following pseudo=code:

public static void main(String[] args) {
 Receive encrypted message and serialized SealedObject

Deserialize SealedObject
Create asymmetric Cipher object, and initialize it for
decryption with private key (corresponding
to public Key used by the encryption application)
 Unseal the wrapped session key using
                 the asymmetric Cipher
 Create symmetric Cipher object (using the same
 algorithm that was used by the encryption application)
  Initialize symmetric Cipher for decryption with the
           recovered session key
  Decrypt message
Secure Streams

JCE 1.2 provides secure input and output stream functionality with
the javax.crypto.CipherInputStream and javax.crypto.CipherOutputStream classes.
These classes are a FilterInputStream or FilterOutputStream, respectively, and use
aCipher object to encrypt or decrypt the data passing through.

A program uses the javax.crypto.CipherInputStream class to read a stream of data
in and encrypt or decrypt it before returning the data to the program, and
a javax.crypto.CipherOutputStream to encrypt or decrypt a stream of data before
writing it out.

For example, if you want to store some data in encrypted format to a file, you would
create    a FileOutputStream and Cipher object,   initialize   the Cipher object  for
encryption,            and           create               a CipherOutputStream using
the FileOutputStream and Cipherobjects.                             The write method
of CipherOutputStream will encrypt the data passed through it before writing them
out to the file.

To      read    the    encrypted    data      from      the     file,   you     would
create FileInputStream and Cipher objects, initialize the Cipher object for decryption
with the appropriate key, and create a CipherInputStream object from
the FileInputStream and Cipher objects.                               Theread method
of CipherInputStream reads the data from the file and decrypts them before
returning them to the application.

Priority Queue

A priority queue is an abstract data type in computer programming that supports
the following three operations:

      InsertWithPriority: add an element to the queue with an associated priority
      GetNext: remove the element from the queue that has the highest priority,
    and return it (also known as "PopElement(Off)", or "GetMinimum")
      PeekAtNext (optional): look at the element with highest priority without
    removing it

There are a variety of simple, usually inefficient, ways to implement a priority queue.
They provide an analogy to help one understand what a priority queue is:
      Sorted list implementation: Like a checkout line at the supermarket, but
    where important people get to "cut" in front of less important people.
    (O(n) insertion time, O(1) get-next time, O(n*log(n)) to build)
      Unsorted list implementation: Keep a list of elements as the queue. To add an
    element, append it to the end. To get the next element, search through all
    elements for the one with the highest priority. (O(1) insertion time, O(n) get-next
    due to search)

DeadLock Detection

A deadlock is a situation wherein two or more competing actions are waiting for the
other to finish, and thus neither ever does

There are four necessary conditions for a deadlock to occur, known as the Coffman
conditions from their first description in a 1971 article by E. G. Coffman.

    1. Mutual exclusion condition: a resource that cannot be used by more than one
        process at a time
    2. Hold and wait condition: processes already holding resources may request
        new resources
    3. No preemption condition: No resource can be forcibly removed from a process
        holding it, resources can be released only by the explicit action of the process
    4. Circular wait condition: two or more processes form a circular chain where
        each process waits for a resource that the next process in the chain holds

      Removing the mutual exclusion condition means that no process may have
    exclusive access to a resource. This proves impossible for resources that cannot
    be spooled, and even with spooled resources deadlock could still occur.
    Algorithms       that   avoid   mutual     exclusion     are      called non-blocking
    synchronization algorithms.
      The "hold and wait" conditions may be removed by requiring processes to
    request all the resources they will need before starting up (or before embarking
    upon a particular set of operations); this advance knowledge is frequently difficult
    to satisfy and, in any case, is an inefficient use of resources. Another way is to
    require processes to release all their resources before requesting all the
    resources they will need. This too is often impractical. (Such algorithms, such as
    serializing tokens, are known as the all-or-none algorithms.)
      A "no preemption" (lockout) condition may also be difficult or impossible to
    avoid as a process has to be able to have a resource for a certain amount of
    time, or the processing outcome may be inconsistent or thrashing may occur.
    However, inability to enforce preemption may interfere with a priority algorithm.
    (Note: Preemption of a "locked out" resource generally implies a rollback, and is
    to be avoided, since it is very costly in overhead.) Algorithms that allow
    preemption include lock-free and wait-free algorithms and optimistic concurrency
      The circular wait condition: Algorithms that avoid circular waits include
    "disable interrupts during critical sections", and "use a hierarchy to determine
    a partial ordering of resources" (where no obvious hierarchy exists, even the
    memory     address   of    resources   has   been   used   to   determine   ordering)
    and Dijkstra's solution.

To top