UNIX Tutorial One by HC121001215058


									Department of Information Technology

    Internetworking with TCP/IP Lab
   Lab Manual   [Subject Code: MTI 2.6]
    I M Tech – II Semester [Branch: IT]

    Department of Information Technology

          Lab Manual for the Academic Year 2008-09
             (In accordance with JNTU syllabus)

SUBJECT            :   TCP/IP LAB

SUBJECT CODE       :   MTI 2.6

SEMESTER           :   II

STREAM             :   Department of Information Technology

INSTRUCTOR         :


                                                    Head IT

      Department of Information Technology
            Lab Manual for the Academic Year 2008-09
               (In accordance with JNTU syllabus)

Suggestions from Principal:

Enhancement if any:



        S. No   Contents                            Page No.

         1      Lab Objective                       5

         2      Introduction About Lab              5

         3      Guidelines to Students               7

         4      Description about TCP/IP             8

                List of Lab Exercises               11
                Syllabus Programs (JNTU)

         6      Solutions for Programs              12

         7      Solutions for Additional Programs   52

         8      References                          55


Overview of TCP/IP protocols design and implementation to make it more clear to
students effectively.

               There are 66 systems (Compaq Presario) installed in this Lab. Their
configurations are as follows:

Processor                     :      AMD Athelon ™ 1.67 GHz

RAM                           :      256 MB

Hard Disk                     :      40 GB

Mouse                         :      Optical Mouse

Network Interface card        :      Present


    All systems are configured in DUAL BOOT mode i.e., Students can boot from
        Windows XP or Linux as per their lab requirement.

               This is very useful for students because they are familiar with different
               Operating Systems so that they can execute their programs in different
               programming environments.

    Each student has a separate login for database access

        Oracle 9i client version is installed in all systems. On the server, account for each
        student has been created.

               This is very useful because students can save their work (scenarios’, pl/sql
        programs, data related projects, etc) in their own accounts. Each student work is safe
        and secure from other students.

 Latest Technologies like DOT NET and J2EE are installed in some systems.
   Before submitting their final project, they can start doing mini project from 2nd
   year onwards.

 MASM ( Macro Assembler ) is installed in all the systems

   Students can execute their assembly language programs using MASM. MASM
   is very useful students because when they execute their programs they can see
   contents of Processor Registers and how each instruction is being executed in
   the CPU.

 Rational Rose Software is installed in some systems

          Using this software, students can depict UML diagrams of their

 Softwares installed: C, C++, JDK1.5, MASM, OFFICE-XP, J2EE and DOT
   NET, Rational Rose.
 Systems are provided for students in the 1:1 ratio.
 Systems are assigned numbers and same system is allotted for students when
   they do the lab.

Guidelines to Students:

   The Internet has revolutionized many aspects of our daily lives. It has affected the
way we do business as well as the way we spend our leisure time. The Internet is a
communication system that has brought a wealth of information to our fingertips and
organized it for our use.

   In this section, we define two widely used terms: protocols and standards. First, we
define protocol, which is synonymous with rule. Then we discuss standards, which are
agreed-upon rules.

   This Internetworking with TCP/IP lab provides the overall design aspects and
implementation aspects.

Description about TCP/IP

   The Internet protocol suite (commonly TCP/IP) is the set of communications
    protocols that implement the protocol stack on which the Internet and most
    commercial networks run.
   It is named for two of the most important protocols in it: the Transmission Control
    Protocol (TCP) and the Internet Protocol (IP), which were also the first two
    networking protocols defined.
   Today's IP networking represents a synthesis of two developments that began to
    evolve in the 1960s and 1970s, namely LANs (Local Area Networks) and the
    Internet, which, together with the invention of the World Wide Web by Sir Tim
    Berners-Lee in 1989, have revolutionized computing.
   The Internet protocol suite—like many protocol suites—can be viewed as a set of
   Each layer solves a set of problems involving the transmission of data, and provides a
    well-defined service to the upper layer protocols based on using services from some
    lower layers. Upper layers are logically closer to the user and deal with more abstract
    data, relying on lower layer protocols to translate data into forms that can eventually
    be physically transmitted.
   The TCP/IP reference model consists of four layers. From lowest to highest, these are
    the link layer, the network layer, the transport layer, and the application layer.


   The Internet protocol suite came from work done by Defense Advanced Research
    Projects Agency (DARPA) in the early 1970s. After building the pioneering
    ARPANET in the late 1960s, DARPA started work on a number of other data
    transmission technologies.
   In 1972, Robert E. Kahn was hired at the DARPA Information Processing
    Technology Office, where he worked on both satellite packet networks and ground-
    based radio packet networks, and recognized the value of being able to communicate
    across them. In the spring of 1973, Vinton Cerf, the developer of the existing

    ARPANET Network Control Program (NCP) protocol, joined Kahn to work on open-
    architecture interconnection models with the goal of designing the next protocol for
    the ARPANET.
   By the summer of 1973, Kahn and Cerf had soon worked out a fundamental
    reformulation, where the differences between network protocols were hidden by
    using a common internetwork protocol, and instead of the network being responsible
    for reliability, as in the ARPANET, the hosts became responsible. (Cerf credits
    Hubert Zimmerman and Louis Pouzin [designer of the CYCLADES network] with
    important influences on this design.)
   With the role of the network reduced to the bare minimum, it became possible to join
    almost any networks together, no matter what their characteristics were, thereby
    solving Kahn's initial problem. One popular saying has it that TCP/IP, the eventual
    product of Cerf and Kahn's work, will run over "two tin cans and a string." There is
    even an implementation designed to run using homing pigeons, IP over Avian
    Carriers (documented in Request for Comments 1149).
   A computer called a router (a name changed from gateway to avoid confusion with
    other types of gateway) is provided with an interface to each network, and forwards
    packets back and forth between them. Requirements for routers are defined in
    (Request for Comments 1812).
   The idea was worked out in more detailed form by Cerf's networking research group
    at Stanford in the 1973–74 period, resulting in the first TCP specification (Request for
    Comments 675) (The early networking work at Xerox PARC, which produced the
    PARC Universal Packet protocol suite, much of which existed around the same
    period of time (i.e. contemporaneous), was also a significant technical influence;
    people moved between the two).
   DARPA then contracted with BBN Technologies, Stanford University, and the
    University College London to develop operational versions of the protocol on
    different hardware platforms. Four versions were developed: TCP v1, TCP v2, a split
    into TCP v3 and IP v3 in the spring of 1978, and then stability with TCP/IP v4 — the
    standard protocol still in use on the Internet today.
   In 1975, a two-network TCP/IP communications test was performed between
    Stanford and University College London (UCL). In November, 1977, a three-network

    TCP/IP test was conducted between the U.S., UK, and Norway. Between 1978 and
    1983, several other TCP/IP prototypes were developed at multiple research centers. A
    full switchover to TCP/IP on the ARPANET took place January 1, 1983.
   In March 1982, the US Department of Defense made TCP/IP the standard for all
    military computer networking. In 1985, the Internet Architecture Board held a three
    day workshop on TCP/IP for the computer industry, attended by 250 vendor
    representatives, helping popularize the protocol and leading to its increasing
    commercial use.
   On November 9, 2005 Kahn and Cerf were presented with the Presidential Medal of
    Freedom for their contribution to American culture.

 TCP/IP Syllabus Programs (JNTU):

S. No                                Programs
  1.    IP address calculation
  2.    Implementation of CRC
  3.    Implementation of Checksum
  4.    Implementation of BOOTP
  5.    Implementation of DHCP
  6.    Implementation of OSPF
  7.    Implementation of FTP
  8.    Implementation of TFTP

Solutions for Programs:
AIM: IP address calculation


      Internet Protocol version 4 (IPv4) is the fourth iteration of the Internet Protocol (IP)
       and it is the first version of the protocol to be widely deployed. IPv4 is the dominant
       network layer protocol on the Internet and apart from IPv6 it is the only standard
       internetwork-layer protocol used on the Internet.
      It is described in IETF RFC 791 (September 1981) which made obsolete RFC 760
       (January 1980). The United States Department of Defense also standardized it as
      IPv4 is a data-oriented protocol to be used on a packet switched internetwork (e.g.,
       Ethernet). It is a best effort protocol in that it does not guarantee delivery. It does not
       make any guarantees on the correctness of the data; this may result in duplicated
       packets or packets delivered out of order. These aspects are addressed by an upper
       layer protocol (e.g. TCP, and partly by UDP).
      IPv4 uses 32-bit (four-byte) addresses, which limits the address space to
       4,294,967,296 (232) possible unique addresses. However, some are reserved for
       special purposes such as private networks (~18 million addresses) or multicast
       addresses (~16 million addresses). This reduces the number of addresses that can be
       allocated as public Internet addresses. As the number of addresses available are
       consumed, an IPv4 address shortage appears to be inevitable, however Network
       Address Translation (NAT) has significantly delayed this inevitability.
      This limitation has helped stimulate the push towards IPv6, which is currently in the
       early stages of deployment and is currently the only contender to replace IPv4.
Address representations
      When writing IPv4 addresses in human-readable form, the most common notation is
       the dot-decimal notation. There are other notations based on the values of 200.100 in
       the dot-decimal notation which comprises four octets in decimal separated by periods.
       This is the base format used in the conversion in the following table:

Notation              Value                    Conversion from dot-decimal


                      0xC0.0x00.0x02.0xEB      Each octet is individually converted to hex

Dotted Octal          0300.0000.0002.0353      Each octet is individually converted into octal

                                               Concatenation of the octets from the dotted
Hexadecimal           0xC00002EB

Decimal               3221226219               The hexadecimal form converted to decimal

Octal                 030000001353             The hexadecimal form converted to octal

        Most of these formats should work in all browsers. Additionally, in dotted format,
         each octet can be of any of the different bases. For example, 192.0x00.0002.235 is a
         valid (though unconventional) equivalent to the above addresses.
        A final form is not really a notation since it is rarely written in an ASCII string
         notation. That form is a binary form of the hexadecimal notation in binary. This
         difference   is   merely   the   representational   difference   between   the   string
         "0xCF8E83EB" and the 32-bit integer value 0xCF8E83EB. This form is used for
         assigning the source and destination fields in a software program.
Originally, an IP address was divided into two parts:
Network ID: first octet
Host ID: last three octets
This created an upper limit of 256 networks. As the networks began to be allocated, this was
soon seen to be inadequate.
        To overcome this limit, different classes of network were defined, in a system which
         later became known as classful networking. Five classes were created (A, B, C, D,
         and E), three of which (A, B, and C) had different lengths for the network field. The
         rest of an address was used to identify a host within a network, which meant that each
         network class had a different maximum number of hosts. Thus there were a few
         networks with each having many host addresses and numerous networks with each

       only having a few host addresses. Class D was for multicast addresses and Class E
       was reserved.
      Around 1993, these classes were replaced with a Classless Inter-Domain Routing
       (CIDR) scheme, and the previous scheme was dubbed "classful", by contrast. CIDR's
       primary advantage is to allow re-division of Class-A, -B and -C networks so that
       smaller (or larger) blocks of addresses may be allocated to various entities (such as
       Internet service providers, or their customers) or local area networks.
      The actual assignment of an address is not arbitrary. The fundamental principle of
       routing is that the address of a device encodes information about the device's location
       within a network. This implies that an address assigned to one part of a network will
       not function in another part of the network. A hierarchical structure, created by CIDR
       and overseen by the Internet Assigned Numbers Authority (IANA) and its Regional
       Internet Registries (RIRs), manages the assignment of Internet addresses worldwide.
       Each RIR maintains a publicly-searchable WHOIS database that provides information
       about IP address assignments; information from these databases plays a central role in
       numerous tools that attempt to locate IP addresses geographically.
Reserved address blocks

CIDR address block Description                                                   Reference              Current network (only valid as source address)            RFC 1700             Private network                                           RFC 1918             Public data networks (per 2008-02-10, available for use) RFC 1700            Loopback                                                  RFC 3330           Reserved (IANA)                                           RFC 3330         Link-Local                                                RFC 3927          Private network                                           RFC 1918         Reserved (IANA)                                           RFC 3330           Reserved (IANA)                                           RFC 3330           Documentation and example code                            RFC 3330

                                                                                             14            IPv6 to IPv4 relay                                      RFC 3068            Private network                                         RFC 1918             Network benchmark tests                                 RFC 2544          Reserved (IANA)                                         RFC 3330               Multicasts (former Class D network)                     RFC 3171               Reserved (former Class E network)                       RFC 1700           Broadcast

Private networks
        Of the four billion addresses allowed in IPv4, four ranges of address are reserved for
         private networking use only. These ranges are not routable outside of private
         networks, and private machines cannot directly communicate with public networks.
         They can, however, do so through network address translation.
The following are the four ranges reserved for private networks:

                                       Number        of Classful             Largest      CIDR
Name        Address range
                                       addresses        description          block

                                       16,777,216       Single Class A

20-bit–                                 16      contiguous
block                              Class Bs

16-bit–                                256     contiguous
block                             Class Cs

16-bit–                                256     contiguous
block                             Class Cs
The ranges,, and are reserved for private networking
by RFC 1918, while the range is reserved for Link-Local addressing as
defined in RFC 3927.

      In addition to private networking, the address range– (or in CIDR notation) is reserved for localhost communication. Any address
       within this range should never appear on an actual network and any packet sent to this
       address does not leave the source computer, and will appear as an incoming packet on
       that computer (known as loopback).
Addresses ending in 0 or 255
      It is a common misconception that addresses ending in 255 or 0 can never be assigned
       to hosts, but this is only true of networks with subnet masks of at least 24 bits —
       Class C networks in the old classful addressing scheme, or in CIDR, networks with
       masks of /24 to /32 (or–
In classful addressing (now obsolete with the advent of CIDR), there are only three possible
subnet masks: Class A, or /8; Class B, or /16; and Class C, or /24. For example, in the subnet (or the identifier refers to the entire subnet, so it cannot also refer to
an individual device in that subnet.
A broadcast address is an address that allows information to be sent to all machines on a
given subnet rather than a specific machine. Generally, the broadcast address is found by
taking the bit complement of the subnet mask and then OR-ing it bitwise with the network
identifier. More simply, the broadcast address is the last address in the range belonging to the
subnet. In our example, the broadcast address would be, so to avoid confusion
this address also cannot be assigned to a host. On a Class-A, -B, or -C subnet, the broadcast
address would always end in 255.
However, this does not mean that every addresses ending in 255 cannot be used as a host
address. For example, in the case of a Class B subnet (or, equivalent to the address range–, the broadcast
address is However, one can assign,, etc.
(though this can cause confusion). Also, is the network identifier and so cannot
be assigned, but,, etc. can be assigned (though this can also cause
With the advent of CIDR, broadcast addresses do not necessarily end with 255.

In general, the first and last addresses in a subnet are used as the network identifier and
broadcast address, respectively. All other addresses in the subnet can be assigned to hosts on
that subnet.


package com.gnec;

import java.io.BufferedReader;
import java.io.InputStreamReader;
 * @author Administrator
public class IPCal {

       public IPCal() {
               // TODO Auto-generated constructor stub

        * @param args
       public static void main(String[] args) {
               // TODO Auto-generated method stub
               BufferedReader br=new BufferedReader(new
               String str=null;
               System.out.println("Enter the decimal number");
                       catch(Exception e){
                       long[ ] a=new long[4];
                       long num = Long.parseLong(str);
                       for (int i=0;i<4;i++){
                                long rem = num % 255;

                             num = num / 255;

                             //System.out.println("the rem value in "+i+":"+rem);
                       System.out.print("The ip address is:");
              for (int j=3;j>=0;j--){


package com.gnec;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

 * @author Administrator
public class IPAddressss {

        * @param args
       public static void main(String[] args) {
               // TODO Auto-generated method stub
               BufferedReader br=new BufferedReader(new
               String str=null;
               StringTokenizer st;
               int ip[]=new int[4];
               int i;
               System.out.println("Enter IPAddress");
               catch(Exception e){

     st=new StringTokenizer(str,".");
             catch(NumberFormatException e)
                      System.out.println ("Enter correct IPAddress");
             System.out.println ("Enter correct IPAddress");
                      System.out.println ("Enter correct IPAddress");
     if((ip[0]>=0) &&(ip[0]<=127))

     else if((ip[0]>=128)&& (ip[0]<=191))

        else if((ip[0]>=192)&&(ip[0]<=223))

               else if((ip[0]>=224)&&(ip[0]<=239))

                     else if((ip[0]>=240)&&(ip[0]<=255))



Expected Output:

Enter the decimal number
The ip address is:

Enter IPAddress

AIM: Implementation of CRC


A cyclic redundancy check (CRC) is a type of function that takes an input of data stream of
any length and produces as output a value of a certain fixed size. The term CRC is often used
to denote either the function or the function's output. A CRC can be used as a checksum to
detect alteration of data during transmission or storage. CRCs are popular because they are
simple to implement in binary hardware, are easy to analyze mathematically, and are
particularly good at detecting common errors caused by noise in transmission channels. The
CRC was invented by W. Wesley Peterson, and published in his 1961 paper.
A CRC is an error-detecting code whose computation resembles a long division computation
in which the quotient is discarded and the remainder becomes the result, with the important
distinction that the arithmetic used is the carry-less arithmetic of a finite field. The length of
the remainder is always less than the length of the divisor, which therefore determines how
long the result can be. The definition of a particular CRC specifies the divisor to be used,
among other things.
Although CRCs can be constructed using any finite field, all commonly used CRCs employ
the finite field GF(2), the field of two elements, usually called 0 and 1, comfortably matching
computer architecture. The rest of this article will discuss only these binary CRCs, but the
principles are more general.
An important reason for the popularity of CRCs for detecting the accidental alteration of data
is their efficiency guarantee. Typically, an n-bit CRC, applied to a data block of arbitrary
length, will detect any single error burst not longer than n bits (in other words, any single
alteration that spans no more than n bits of the data), and will detect a fraction 1-2-n of all
longer error bursts. Errors in both data transmission channels and magnetic storage media
tend to be distributed non-randomly (i.e. are "bursty"), making CRCs' properties more useful
than alternative schemes such as multiple parity checks.
The simplest error-detection system, the parity bit, is in fact a trivial CRC: it uses the two-bit-
long divisor 11.
CRCs are not, by themselves, suitable for protecting against intentional alteration of data (for
example, in authentication applications for data security), because their convenient

mathematical properties make it easy to compute the CRC adjustment required to match any
given change to the data.
Computation of CRC
The mechanics of computing an n-bit binary CRC are simple. The bits representing the input
are lined up in a row, and the (n+1)-bit pattern representing the CRC's divisor (called a
"polynomial") is positioned underneath the left-hand end of the row. Here is the first
calculation for computing a 3-bit CRC:
11010011101100 <--- Input
1011             <--- divisor (4 Bits)
01100011101100 <--- result
If the input bit above the leftmost divisor bit is 0, do nothing and move the divisor to the right
by one bit. If the input bit above the leftmost divisor bit is 1, the divisor is exclusive-ORed
into the input (in other words, the input bit above each 1-bit in the divisor is toggled). The
divisor is then shifted one bit to the right, and the process is repeated until the divisor reaches
the right-hand end of the input row. Here is the last calculation:
00000000001110 <--- result of multiplication calculation
       1011 <--- divisor
00000000000101 <--- remainder (3 bits)
Since the leftmost divisor bit zeroed every input bit it touched, when this process ends the
only bits in the input row that can be nonzero are the n bits at the right-hand end of the row.
These n bits are the remainder of the division step, and will also be the value of the CRC
function (unless the chosen CRC specification calls for some postprocessing).
Common polynomials
As well as the polynomial, the prefix and the value exclusive-ORed with the remainder are
important for some more complicated checksums (like most forms of CRC-32 and CRC-64).
CRCs less than CRC-16 do not tend to use Initial or final XOR values.
Very often custom versions of checksums are created by changing these values, as it does not
alter the overall mechanics (or math) of the checksum algorithm -- and may provide some
nominal security features. However a CRC algorithm can be reverse-engineered from a small
number of message-CRC pairs by brute force search.

Note: in this table the high-order bit is omitted; see Specifying a CRC above.

                                                            Representations:      Normal   or
Name            Polynomial
                                                            Reverse (Normal of Reciprocal)

                x + 1 (most hardware; also known as
CRC-1                                                       0x1 or 0x1 (0x1)
                parity bit)

CRC-4-ITU       x4 + x + 1 (ITU G.704, p. 12)               0x3 or 0xC (0x9)

CRC-5-ITU       x5 + x4 + x2 + 1 (ITU G.704, p. 9)          0x15 or 0x15 (0x0B)

CRC-5-USB       x5 + x2 + 1 (USB token packets)             0x05 or 0x14 (0x9)

CRC-6-ITU       x6 + x + 1 (ITU G.704, p. 3)                0x03 or 0x30 (0x21)

CRC-7           x7 + x3 + 1 (telecom systems, MMC)          0x09 or 0x48 (0x11)

CRC-8-ATM       x8 + x2 + x + 1 (ATM HEC)                   0x07 or 0xE0 (0xC1)

CRC-8-CCITT x8 + x7 + x3 + x2 + 1 (1-Wire bus)              0x8D or 0xB1 (0x63)

                x8 + x5 + x4 + 1 (1-Wire bus)               0x31 or 0x8C (0x19)

CRC-8           x8 + x7 + x6 + x4 + x2 + 1                  0xD5 or 0xAB (0x57)

                x8 + x4 + x3 + x2 + 1                       0x1D or 0xB8 (0x71)

CRC-10          x10 + x9 + x5 + x4 + x + 1                  0x233 or 0x331 (0x263)

CRC-11          x11 + x9 + x8 + x7 + x2 + 1 (FlexRay)       0x385 or 0x50E (0x21D)

                x12 + x11 + x3 + x2 + x + 1 (telecom
CRC-12                                                      0x80F or 0xF01 (0xE03)

CRC-15-CAN x15 + x14 + x10 + x8 + x7 + x4 + x3 + 1          0x4599 or 0x4CD1 (0x19A3)

                Not a CRC; see Fletcher's checksum          Used in Adler-32 A & B CRCs

                x16 + x12 + x5 + 1 (X.25, V.41, CDMA,
                Bluetooth,    XMODEM,          PPP,   IrDA, 0x1021 or 0x8408 (0x0811)
                BACnet; known as CRC-CCITT)

               x16 + x15 + x2 + 1 (SDLC, USB, many
CRC-16-IBM                                                     0x8005 or 0xA001 (0x4003)
               others; also known as CRC-16)

CRC-24-        x24 + x23 + x18 + x17 + x14 + x11 + x10 + x7 0x864CFB          or     0xDF3261
Radix-64       + x6 + x5 + x4 + x3 + x + 1 (FlexRay)           (0xBE64C3)

               x30 + x29 + x21 + x20 + x15 + x13 + x12 + x11 0x2030B9C7       or   0x38E74301
               + x8 + x7 + x6 + x2 + x + 1 (CDMA)              (0x31CE8603)

CRC-32-Adler Not a CRC; see Adler-32                           See Adler-32

               x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10
CRC-32-IEEE                                                    0x04C11DB7     or   0xEDB88320
               + x8 + x7 + x5 + x4 + x2 + x + 1 (V.42,
802.3                                                          (0xDB710641)
               MPEG-2, PNG )

               x32 + x28 + x27 + x26 + x25 + x23 + x22 + x20
CRC-32C                                                        0x1EDC6F41     or   0x82F63B78
               + x19 + x18 + x14 + x13 + x11 + x10 + x9 + x8
(Castagnoli)                                                   (0x05EC76F1)
               + x6 + 1

               x32 + x30 + x29 + x28 + x26 + x20 + x19 + x17
CRC-32K                                                        0x741B8CD7 or 0xEB31D82E
               + x16 + x15 + x11 + x10 + x7 + x6 + x4 + x2
(Koopman)                                                      (0xD663B05D)

                                                               0x000000000000001B          or
               x64 + x4 + x3 + x + 1 (HDLC — ISO
CRC-64-ISO                                                     0xD800000000000000

               x64 + x62 + x57 + x55 + x54 + x53 + x52 + x47
               + x46 + x45 + x40 + x39 + x38 + x37 + x35 +
                                                               0x42F0E1EBA9EA3693          or
CRC-64-        x33 + x32 + x31 + x29 + x27 + x24 + x23 + x22
ECMA-182       + x21 + x19 + x17 + x13 + x12 + x10 + x9 + x7
               + x4 + x + 1 (as described in ECMA-182
Known to exist, but technologically defunct -- mainly replaced by cryptographic hash
CRC-128 (IEEE)
CRC-256 (IEEE)
Designing CRC polynomials

The selection of generator polynomial is the most important part of implementing the CRC
algorithm. The polynomial must be chosen to maximize the error detecting capabilities while
minimizing overall collision probabilities.
The most important attribute of the polynomial is its length (the number of the highest
nonzero coefficient), because of its direct influence of the length of the computed checksum.
The most commonly used polynomial lengths are
9 bits (CRC-8)
17 bits (CRC-16)
33 bits (CRC-32)
65 bits (CRC-64)
When creating a new CRC polynomial or improving an existing CRC the general
mathematical advice is to use an irreducible polynomial that satisfies all polynomial
irreducibility constraints from modular arithmetics.
Irreducibility in this case means that the polynomial cannot be divided by any polynomial
except itself and 1 with zero remainder.
Reducible polynomials can still be used, but their error correcting and detecting capabilities
will be less effective. Some applications may choose to use reducible polynomials under
certain conditions.
The properties of the generator polynomial can be derived from the algorithm definition
CRCs with more than one nonzero coefficients are able to detect all single bit errors in the
input message.
CRCs can be used to detect all double bit errors in the input message shorter than 2^k, where
k is the length of the longest irreducible part of the polynomial.
If the CRC polynomial is divided by x + 1 then no polynomial with odd number of nonzero
coefficients can be divided by it. Hence, it can be used to detect odd number of errors in the
input message (like single bit parity function).
CRC polynomials detect (single) burst errors shorter than the number of the position of the
highest polynomial coefficient.


package com.gnec;

import java.io.BufferedReader;
import java.io.InputStreamReader;

 * @author Administrator
public class Crc8 {

       public static void main(String[] args)throws Exception {
               // TODO Auto-generated method stub
               BufferedReader br=new BufferedReader(new

           //transmitted data
           System.out.println("HOW MANY NUMBER OF BITS YOU WANT TO
           int n=Integer.parseInt(br.readLine());
           System.out.println("Enter transmitted data in binary form: ");
           int td[]=new int[n];
           for(int i=0;i<n;i++)

              //generator data
              System.out.println("Enter CRC8 polynomial generator data in binary form: ");

              int g[]=new int[9];
              for(int i=0;i<9;i++)

              int l=9,m;
              int stemp[]=null;
              //append zeros
              int atd[]=new int[n+8];
              for(int i=0;i<n;i++)
              for(int i=n;i<n+8;i++)
              System.out.print("Transmitted data after append in binary form: ");

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

              //copy atd[] data into temp[] for modification
              int temp[]=new int[atd.length];
              System.out.println("the length of the atd is:"+atd.length );
              System.out.print("the temp data is:");
              for(int i=0;i<atd.length;i++)
              System.out.println("\nthe l value is :"+l+"\t the m value is:"+m+"\t temp
              /*       for(int i=0;i<atd.length;i++)
              */       int k=0;
              System.out.println("previous data:");
                       for(int i=0;i<l;i++)

                      /*for(int i=0;i<temp.length;i++)
                               System.out.print("the temp data in while loop:"+temp[i]);
                      System.out.println("remaining of data:");
                      for(int i=k;i<m;i++)

                      int count=0;
                      for(int i=0;i<temp.length;i++)
                      {        if(temp[i]==0)


       stemp=new int[m-count];
       int j=0;
       System.out.println("some inter of data:");
       for(int i=count;i<temp.length;i++)


       temp=new int[j];
       for(int i=0;i<temp.length;i++)


int ttemp[]=new int[l-1];
{       int x=0,j;
        int k=(l-1)-temp.length;
        //ttemp[]=new int[l-1];
        for(int i=0;i<k;i++)

       for(int i=j;i<(l-1);i++)
else if(temp.length==(l-1))
         //int ttemp[]=new int[l-1];
         for(int i=0;i<temp.length;i++)

                        System.out.println("some error has been occured");
               System.out.print("The CRC is:");
               for(int i=0;i<stemp.length;i++)



Expected Output:

Enter transmitted data in binary form: 1 1 0 0 1 1 0 0 0 1 1 1 0 0
Enter CRC8 polynomial generator data in binary form:1 0 0 0 0 0 1 1 1
Transmitted data after append in binary form: 1 1 0 0 1 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0
The CRC is: 0 1 0 0 1 0 0 1 0

AIM: Implementation of Checksum Calculation


A checksum is a form of redundancy check, a simple way to protect the integrity of data by
detecting errors in data that are sent through space (telecommunications) or time (storage). It
works by adding up the basic components of a message, typically the asserted bits, and
storing the resulting value. Anyone can later perform the same operation on the data,
compare the result to the authentic checksum and (assuming that the sums match) conclude
that the message was most likely not corrupted.
An example of a simple checksum:
Given 4 bytes of data (can be done with any number of bytes): 0x25, 0x62, 0x3F, 0x52
Step 1: Adding all bytes together gives 0x118.
Step 2: Drop the Carry Nibble to give you 0x18.
Step 3: Get the two's complement of the 0x18 to get 0xE8. This is the checksum byte.
To Test the Checksum byte simply add it to the original group of bytes. This should give you
Drop the carry nibble again giving 0x00. Since it is 0x00 this means no error was detected
(although an undetectable error could have occurred).
The simplest form of checksum, which simply adds up the asserted bits in the data, cannot
detect a number of types of errors. Such a checksum, for example, is not changed by:
Reordering of the bytes in the message.
Inserting or deleting zero-valued bytes.
Multiple errors which sum to zero.
More sophisticated types of redundancy check, including Fletcher's checksum, Adler-32, and
cyclic redundancy checks (CRCs), are designed to address these weaknesses by considering
not only the value of each byte but also its position. The cost of the ability to detect more
types of errors is the increased complexity of computing the redundancy check value.
These types of redundancy check are useful in detecting accidental modification such as
corruption to stored data or errors in a communication channel. However, they provide no
security against a malicious agent as their simple mathematical structure makes them trivial
to circumvent. To provide this level of integrity, the use of a cryptographic hash function,

such as SHA-256, is necessary. (Collisions have been found in the popular MD5 algorithm
and finding collisions in SHA-1 seems possible, but there is no evidence as of 2006 that
SHA-256 suffers similar weaknesses.)
On UNIX, there is a tool called "cksum" that generates both a 32-bit CRC and a byte count
for any given input file.


package com.gnec;
import java.lang.Math;
public class Checksum2 {

     * @param args
    public static void main(String[] args)throws Exception {
            // TODO Auto-generated method stub
            //int td[][]=new int[14][16];
            System.out.println(".......WELCOME TO CHECKSUM
            int td[][]={{1,0,0,1,1,0,0,1,0,0,0,1,0,0,1,0},

               int sum=0;
               for(int i=0;i<14;i++)
                        int temp[]=new int[16];

                       for(int j=0;j<16;j++)

                   int x=15;
                   int deci=0;
                   for(int j=0;j<16;j++)
                            double d=x;
                            double t=2.0;
                            double d2= Math.pow(t,d);
                            deci=deci+(temp[j]* (int)d2);


            int csum=65535-sum,i=0;
            int stemp[]=new int[16];
            System.out.println("The checksum in decimal is="+(65535-sum));
            System.out.print("The checksum in binary is=");
            for(int j=15;j>=0;j--)



Expected Output:
The checksum in decimal is=26900
The checksum in binary is=0110100100010100

AIM: Implementation of BOOTP Protocol


      In computing, Bootstrap Protocol, or BOOTP, is a UDP network protocol used by a
       network client to obtain its IP address automatically. This is usually done during the
       bootstrap process when a computer is starting up. The BOOTP servers assign the IP
       address from a pool of addresses to each client. The BOOTP protocol was originally
       defined in RFC 951.
      BOOTP enables 'diskless workstation' computers to obtain an IP address prior to
       loading any advanced operating system. Historically, it has been used for Unix-like
       diskless workstations (which also obtained the location of their boot image using this
       protocol) and also by corporations to roll out a pre-configured client (e.g. Windows)
       installation to newly purchased PCs.
      Originally requiring the use of a boot floppy disk to establish the initial network
       connection, the protocol became embedded in the BIOS of some network cards
       themselves (such as 3c905c) and in many modern motherboards thus allowing direct
       network booting.
      Recently those with an interest in diskless stand-alone media center PCs have shown
       new interest in this method of booting a Windows operating system.
      DHCP (Dynamic Host Configuration Protocol) is a more advanced protocol based on
       BOOTP, but is far more complex to implement. Most DHCP servers also offer
       BOOTP support.

AIM: Implementation of DHCP Protocol.


      Dynamic Host Configuration Protocol (DHCP) is a protocol used by networked
       devices (clients) to obtain various parameters necessary for the clients to operate in an
       Internet Protocol (IP) network. By using this protocol, system administration
       workload greatly decreases, and devices can be added to the network with minimal or
       no manual configurations.
      Dynamic Host Configuration Protocol is a way to administer network parameter
       assignment from a single DHCP server, or a group of DHCP servers arranged in a
       fault-tolerant manner. Even in small networks, Dynamic Host Configuration Protocol
       is useful because it can make it easy to add new machines to the local network.
      DHCP is also recommended even in the case of servers whose addresses rarely
       change, so that if a server need to be readdressed (RFC2071), changes can be made in
       as few places as possible. For devices such as routers and firewalls, that should not
       use DHCP, it can be useful to put Trivial File Transfer Protocol (TFTP) or SSH
       servers on the same machine that runs DHCP, which also serves to centralize
      DHCP can be used to directly assign addresses to servers and desktop machines, and,
       through a Point-to-Point Protocol (PPP) proxy, to dialup and broadband on-demand
       hosts, as well as for residential Network address translation (NAT) gateways and
       routers. DHCP is generally not appropriate for infrastructure such as non-edge routers
       and DNS servers.

   Basic Protocol Operation:

      The Dynamic Host Configuration Protocol (DHCP) automates the assignment of IP
       addresses, subnet masks, default gateway, and other IP parameters.
      When a DHCP-configured client (be it a computer or any other network-aware
       device) connects to a network, the DHCP client sends a broadcast query requesting

       necessary information from a DHCP server. The DHCP server manages a pool of IP
       addresses and information about client configuration parameters such as the default
       gateway, the domain name, the DNS servers, other servers such as time servers, and
       so forth. Upon receipt of a valid request the server will assign the computer an IP
       address, a lease (the length of time for which the allocation is valid), and other IP
       configuration parameters, such as the subnet mask and the default gateway. The query
       is typically initiated immediately after booting and must be completed before the
       client can initiate IP-based communication with other hosts.
      DHCP provides three modes for allocating IP addresses. The best-known mode is
       dynamic, in which the client is provided a "lease" on an IP address for a period of
       time. Depending on the stability of the network, this could range from hours (a
       wireless network at an airport) to months (for desktops in a wired lab). At any time
       before the lease expires, the DHCP client can request renewal of the lease on the
       current IP address. A properly-functioning client will use the renewal mechanism to
       maintain the same IP address throughout its connection to a single network, otherwise
       it may risk losing its lease while still connected, thus disrupting network connectivity
       while it renegotiates with the server for its original or a new IP address.
      The two other modes for allocation of IP addresses are automatic (also known as
       DHCP Reservation), in which the address is permanently assigned to a client, and
       manual, in which the address is selected by the client (manually by the user or any
       other means) and the DHCP protocol messages are used to inform the server that the
       address has been allocated.
      The automatic and manual methods are generally used when finer-grained control
       over IP address is required (typical of tight firewall setups), although typically a
       firewall will allow access to the range of IP addresses that can be dynamically
       allocated by the DHCP server.
      The process of address allocation is known as ROSA. R-Request, O-Offer, S-Send,

IP Address Allocation:

Depending on implementation, the DHCP server has three methods of allocating IP-
addresses (WARNING--the terminology below contradicts the terminology above in Basic
Control Operation):

      dynamic allocation: A network administrator assigns a range of IP addresses to
       DHCP, and each client computer on the LAN has its IP software configured to
       request an IP address from the DHCP server during network initialization. The
       request-and-grant process uses a lease concept with a controllable time period,
       allowing the DHCP server to reclaim (and then reallocate) IP addresses that are not
       renewed (dynamic re-use of IP addresses).
      automatic allocation: The DHCP server permanently assigns a free IP address to a
       requesting client from the range defined by the administrator.
      manual allocation: The DHCP server allocates an IP address based on a table with
       MAC address - IP address pairs manually filled in by the server administrator. Only
       requesting clients with a MAC address listed in this table will be allocated an IP

Some DHCP server software can manage hosts by more than one of the above methods. For
example, the known hosts on the network can be assigned an IP address based on their MAC
address (manual allocation) whereas "guest" computers (such as laptops via WiFi) are
allocated a temporary address out of a pool compatible with the network to which they're
attached (dynamic allocation).

package com.gnec;

//import java.io.*;
import java.net.*;
import java.util.*;

public class DHCP
        public static int serverPort=67;

public static DatagramSocket ds;
public static String address[]={ new String("0050486281A0"),
                                  new String("0050486281B1"),
                                  new String("0050486281C2")
public static void DHCPServer()throws Exception
        byte b[]=new byte[1024];
        byte r[];
        DatagramPacket p;
        String ip[]={ new String(""),
                     new String(""),
                     new String("")
        String gateway=new String("");
        String bootfile=new String("Startup.dat");
        System.out.println("This is the DHCP Server");
        //boolean bool=true;
                for(int i=0;i<1024;i++)
                p=new DatagramPacket(b,b.length);
                String req=new String(b,0,p.getLength());
                System.out.println("Got the Request:"+req);
                int x=-1;
                for(int i=0;i<address.length;i++)
                String res;
                         res=new String("");
                ds.send(new DatagramPacket(r,r.length,p.getAddress(),p.getPort()));

public static void DHCPClient(int x)throws Exception
        byte rec[]=new byte[1024];
        byte b[];
        DatagramPacket p ;
        String req;

            System.out.println("This is the DHCP Client");
                     req=new String("000000000000");
            System.out.println("Sending Request HA:"+req);
            p=new DatagramPacket(rec,rec.length);
            String res=new String(rec,0,p.getLength());
            StringTokenizer st=new StringTokenizer(res,":");
            String ip=null;
            String gateway=null;
            String bootfile=null;
            String str=null;
            int i=0;
                     else if(i==1)
                              else if(i==2)
                     System.out.println("Negative Response from the server");
                     System.out.println("Got Response:");
                     System.out.println("IP Address:"+ip);
                     System.out.println("Boot File:"+bootfile);

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

                     ds=new DatagramSocket();

                    ds=new DatagramSocket(serverPort);
Expected Output:
E:\gnec\test>java DHCP
This is the DHCP Server
Got the Request:0050486281A0

E:\gnec\test>java DHCP 0
This is the DHCP Client
Sending Request HA:0050486281A0
Got Response:
IP Address:
Boot File:Startup.dat
E:\gnec\test>java DHCP
This is the DHCP Server
Got the Request:0050486281A0
Got the Request:0050486281B1

E:\gnec\test>java DHCP 1
This is the DHCP Client
Sending Request HA:0050486281B1
Got Response:
IP Address:
Boot File:Startup.dat
E:\gnec\test>java DHCP
This is the DHCP Server
Got the Request:0050486281A0
Got the Request:0050486281B1
Got the Request:0050486281C2
Got the Request:000000000000

E:\gnec\test>java DHCP 3
This is the DHCP Client
Sending Request HA:000000000000
Negative Response from the server

AIM: Implementation of Open Shortest Path First (OSPF) Protocol.


The Open Shortest Path First (OSPF) protocol is a hierarchical interior gateway protocol
(IGP) for routing in Internet Protocol, using a link-state in the individual areas that make up
the hierarchy. A computation based on Dijkstra's algorithm is used to calculate the shortest
path tree inside each area. The latest version, Version 3, defined in RFC 2740 (OSPFv3
1999), supports IPv6 only, while OSPF version 2 supports IPv4. (OSPFv2 1998).
A link state database (LSDB) is constructed as a tree-image of the network topology, and
identical copies of the LSDB are periodically updated on all routers in each OSPF-aware area
(region of the network included in an OSPF area type - see "Area types" below). By
convention, area 0 represents the core or "backbone" region of an OSPF-enabled network,
and other OSPF area numbers may be designated to serve other regions of an enterprise
(large, business) network - however every additional OSPF area must have a direct or virtual
connection to the backbone OSPF area. The backbone area has the identifier Inter-
area routing goes via the backbone.
OSPF is perhaps the most widely-used IGP in large enterprise networks; IS-IS is more
common in large service provider networks. The most widely-used exterior gateway protocol
(EGP) is BGP. The OSPF Protocol can operate (communicate with other routers about "best-
path" routes to save in their LSDBs) securely, optionally using a cleartext password or using
MD5 to authenticate peers before forming adjacencies, and before accepting link-state
advertisements (LSA). A natural successor to the Routing Information Protocol (RIP), it was
classless - or able to use Variable-Length Subnet Masking (VLSM) - from its inception.
Multicast extensions to OSPF, the Multicast Open Shortest Path First (MOSPF) protocols,
have been defined but these are not widely used at present.
Routers in the same broadcast domain or at each end of a point-to-point telecommunications
link form adjacencies when they have detected each other. This detection occurs when a
router "sees" itself in a hello packet. This is called a two way state and is the most basic
relationship. The router selects a designated router (DR) and a backup designated router
(BDR) which act as a hub to reduce traffic between routers. OSPF uses both unicast and

multicast to send "hello packets" and link state updates. Multicast addresses (all
SPF/link state routers) and (all Designated Routers) are reserved for OSPF. In
contrast to the Routing Information Protocol (RIP) or the Border Gateway Protocol (BGP),
OSPF does not use TCP or UDP but uses IP directly, via IP protocol 89. OSPF handles its
own error detection and correction, therefore negating the need for TCP or UDP functions.
Area types
An OSPF network is divided into areas, which have 32-bit area identifiers commonly, but
not always, written in the dotted decimal format of an IP address. Area identifiers are not IP
addresses and may duplicate, without conflict, any IP address. While most OSPF
implementations will right-justify an area number written in other than dotted decimal format
(e.g., area 1), it is wise always to use dotted decimal formats. Most implementations would
expand area 1 to the area identifier, but some have been known to expand it as
These are logical groupings of routers whose information may be summarized towards the
rest of the network. Several "special" area types are defined:
Backbone area
The backbone area (also known as area zero or area forms the core of an OSPF
network. All other areas are connected to it, and inter-area routing happens via routers
connected to the backbone area and to their own non-backbone areas. It is the logical and
physical structure for the 'OSPF domain' and is attached to all nonzero areas in the OSPF
domain. Note that in OSPF the term Autonomous System Border Router (ASBR) is historic,
in the sense that many OSPF domains can coexist in the same Internet-visible autonomous
system, RFC1996 (ASGuidelines 1996, p. 25).
The backbone area is responsible for distributing routing information between nonbackbone
areas. The backbone must be contiguous, but it does not need to be physically contiguous;
backbone connectivity can be established and maintained through the configuration of virtual
All OSPF areas must connect to the backbone area. This connection, however, can be
through a virtual link. For example, assume area has a physical connection to area Further assume that area has no direct connection to the backbone, but this
area does have a connection to area Area can use a virtual link through the

transit area to reach the backbone. To be a transit area, an area has to have the transit
attribute, so it cannot be stubby in any way.
Stub area
A stub area is an area which does not receive external routes except the default route, but
does receive inter-area routes. This kind of area is useful when, for example, all Internet
access goes through autonomous system border routers (ASBRs) [Note: ASBR is an ancient
term as written in the "Backbone area" section!] in Area, but there are multiple paths
to other nonzero areas in the OSPF domain.
All routers in the area need to agree they are stub, so that they do not generate types of LSA
not appropriate to a stub area. The Type 3 LSA for the default route is the only external that
should enter the area, and none of its routers may generate externals.
Stub areas do receive inter-area (IA) routes, advertised with Type 3 and Type 4 LSAs. If the
stub area has more than one area border router (ABR), the information on other non-
backbone areas allows the routers in the stub area to pick the best route to another area.
Stub areas do not have the transit attribute and thus cannot be traversed by a virtual link.
Stub areas receive default routes as type 3 network summary LSAs.

package com.gnec;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class OSPF3 {

        * @param args
       public static void main(String[] args) throws Exception{
               // TODO Auto-generated method stub
               int n=0;
               System.out.println(".....WELCOME TO OSPF.....");
               //int A=0,B=1,C=2,D=3,E=4;
               //char A="a",B="b",C="c",D="d",E="e";
               //int V[]=new int[5];
               int V[]={0,1,2,3,4};//new int[5];
               System.out.println("The length of the V:"+V.length);
               int c[][]=new int[V.length][V.length];

             System.out.println("Enter cost Matrix:");
             BufferedReader br=new BufferedReader(new
             for(int i=0;i<V.length;i++)
                      for(int j=0;j<V.length;j++)

                               /* c[V[i]][V[j]]={     {0,10,9999,30,100},
               int s[]={V[0]};
               int d[]=new int[V.length];
               for(int i=0;i<V.length;i++)
               System.out.println("The cost Matrix which is entered by you:");
               for(int i=0;i<d.length;i++)

               int v1[]=new int[V.length-s.length];
               System.out.print("the length of v1 is:\t"+v1.length);
               int x=0;
               for(int i=0;i<5;i++)
                        for(int j=0;j<s.length;j++)

               int w;
               System.out.print("\n The v1 values are:");
               for(int i=0;i<x;i++)

               for(int i=0;i<5;i++)
                        int min=d[v1[0]];
               //       System.out.println("The min value is:"+min);

               int z=v1[0];
               for(int j=1;j<v1.length;j++)
               {        //int y=0;
        //              System.out.println("The z value is:"+z);

        //     System.out.println("The size of s value is:"+s.length);
               System.out.println("The w value is:"+w);
               //s=new int[n+1];
               System.out.println("The s value at before inc is:\t"+s.length);
               System.out.println("The s value at after inc is:\t"+s.length);
               for(int j=0;j<s.length;j++)
                        System.out.println("The s values are:\t"+s[j]);
               int l=0;
               for(int k=0;k<V.length;k++)
                        for(int j=0;j<s.length;j++)
               for(int j=0;j<v1.length;j++)
        System.out.println("The minimum cost from A to all:");
        for(int i=0;i<V.length;i++)

Expected Output:
The length of the V:5
Enter cost Matrix:

the initial s value is: 0
The cost Matrix which is entered by you:
         10      9999 30     100
The minimum cost from A to all:
0        0
1        10
2        50
3        30
4        60

AIM: Implementation of FTP Protocol

In computing, the File Transfer Protocol (FTP) is a network protocol used to transfer data
from one computer to another through a network, such as over the Internet.
FTP is a file transfer protocol for exchanging files over any TCP/IP based network to
manipulate files on another computer on that network regardless of which operating systems
are involved (if the computers permit FTP access). There are many existing FTP client and
server programs. FTP servers can be set up anywhere between game servers, voice servers,
internet hosts, and other physical servers.
Connection methods
FTP runs exclusively over TCP. FTP servers by default listen on port 21 for incoming
connections from FTP clients. A connection to this port from the FTP Client forms the
control stream on which commands are passed to the FTP server from the FTP client and on
occasion from the FTP server to the FTP client. FTP uses out-of-band control, which means
it uses a separate connection for control and data. Thus, for the actual file transfer to take
place, a different connection is required which is called the data stream. Depending on the
transfer mode, the process of setting up the data stream is different.
In active mode, the FTP client opens a dynamic port (49152–65535), sends the FTP server
the dynamic port number on which it is listening over the control stream and waits for a
connection from the FTP server. When the FTP server initiates the data connection to the
FTP client it binds the source port to port 20 on the FTP server.
In order to use active mode, the client sends a PORT command, with the IP and port as
argument. The format for the IP and port is "h1,h2,h3,h4,p1,p2". Each field is a decimal
representation of 8 bits of the host IP, followed by the chosen data port. For example, a client
with an IP of, listening on port 49154 for the data connection will send the
command "PORT 192,168,0,1,192,2". The port fields should be interpreted as p1×256 + p2 =
port, or, in this example, 192×256 + 2 = 49154.
In passive mode, the FTP server opens a dynamic port (49152–65535), sends the FTP client
the server's IP address to connect to and the port on which it is listening (a 16 bit value
broken into a high and low byte, like explained before) over the control stream and waits for

a connection from the FTP client. In this case the FTP client binds the source port of the
connection to a dynamic port between 49152 and 65535.
To use passive mode, the client sends the PASV command to which the server would reply
with something similar to "227 Entering Passive Mode (127,0,0,1,192,52)". The syntax of the
IP address and port are the same as for the argument to the PORT command.
In extended passive mode, the FTP server operates exactly the same as passive mode,
however it only transmits the port number (not broken into high and low bytes) and the client
is to assume that it connects to the same IP address that was originally connected to.
Extended passive mode was added by RFC 2428 in September 1998.
While data is being transferred via the data stream, the control stream sits idle. This can
cause problems with large data transfers through firewalls which time out sessions after
lengthy periods of idleness. While the file may well be successfully transferred, the control
session can be disconnected by the firewall, causing an error to be generated.
The FTP protocol supports resuming of interrupted downloads using the REST command.
The client passes the number of bytes it has already received as argument to the REST
command and restarts the transfer. In some commandline clients for example, there is an
often-ignored but valuable command, "reget" (meaning "get again") that will cause an
interrupted "get" command to be continued, hopefully to completion, after a communications
Resuming uploads is not as easy. Although the FTP protocol supports the APPE command to
append data to a file on the server, the client does not know the exact position at which a
transfer got interrupted. It has to obtain the size of the file some other way, for example over
a directory listing or using the SIZE command.
In ASCII mode (see below), resuming transfers can be troublesome if client and server use
different end of line characters.
The objectives of FTP, as outlined by its RFC, are:
To promote sharing of files (computer programs and/or data).
To encourage indirect or implicit use of remote computers.
To shield a user from variations in file storage systems among different hosts.
To transfer data reliably, and efficiently.

AIM: Implementation of TFTP Protocol
import java.io.*;
import java.net.*;
import java.util.*;
public class TFTP{
        public static int serverPort=69;
        public static DatagramSocket ds;
        public static byte WRQ=2;
        public static byte DATA=3;
        public static byte ACK=4;

       public static void TheServer()throws Exception
       byte b[]=new byte[1024];
       DatagramPacket p;
       String filename="";
       byte opcode;
       byte value;
       byte blockno=-1;
       boolean flag=false;
       FileOutputStream f=null;
       byte databuf[];
       System.out.println("********This is TFTP Server*********");
               for(int i=0;i<1024;i++)
               p=new DatagramPacket(b,b.length);
                        filename=new String(b,1,p.getLength()-1);
                        System.out.println("Got Write Request
                        f=new FileOutputStream(filename);
               else if(opcode==DATA)

             databuf=new byte[2];

                     System.out.println("Data Transfer is Complete");
                     System.out.println("Saved in file\""+filename+"\"");

       public static void TheClient() throws Exception
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       byte b[]=new byte[1024];
       DtagramPacket p;
       FileInputStream f=null;
       String sourceFile,destFile;
       byte opcode;
       byte value;
       byte blockno=0;
       byte databuf[]=new byte[600];
       byte filedata[]=new byte[512];
       int n=0;

       System.out.println("********This is TFTP Client*********");
       System.out.println("Enter the Source filename for TFTP server:");
       System.out.println("Enterthe filename for TFTP server:");

       byte tmp[]=destFile.getBytes();
       for(int i=0;i<tmp.length;i++)
       f=new FileInputStream(sourceFile);

               for(int i=0;i<1024;i++)
               p=new DatagramPacket(b,b.length);
                        System.out.println("Got ack block no="+blockno);
               for(int i=0;i<n;i++)

       public static void main(String args[]) throws Exception{
                        ds=new DatagramSocket();
                        ds=new DatagramSocket(serverPort);
Expected Output:
E:\gnec\test>java TFTP
********This is TFTP Server*********
Got Write Request Filename=s.txtmode=netascii

Data Transfer is Complete
Saved in file"s.txt"

E:\gnec\test>java TFTP 0
********This is TFTP Client*********
Enter the Source filename for TFTP server:
Enterthe filename for TFTP server:
Got ack block no=0
Got ack block no=1
E:\gnec\test>java TFTP
********This is TFTP Server*********
Got Write Request Filename=s.txtmode=netascii
Data Transfer is Complete
Saved in file"s.txt"

E:\gnec\test>java TFTP 1
********This is TFTP Client*********
Enter the Source filename for TFTP server:
Enterthe filename for TFTP server:
Got ack block no=0
Got ack block no=1
Got ack block no=2
Got ack block no=3
Got ack block no=4
Got ack block no=5
Got ack block no=6
Got ack block no=7

Additional Programs:
package com.ulsa.core;
import java.net.Socket;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.InputStream;
import java.io.DataInputStream;
public class Client {

        * @param args
       public static void main(String[] args) throws Exception{
               // TODO Auto-generated method stub
               Socket s=new Socket("SRIVASU",3000);

              OutputStream k=s.getOutputStream();
              PrintStream ps=new PrintStream(k);
              ps.println("hello server");

              InputStream in=s.getInputStream();
              DataInputStream dis= new DataInputStream(in);
              String str=dis.readLine();
              System.out.println("the message received from server:"+str);



package com.ulsa.core;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
 * @author Administrator
public class Server {

        * @param args
       public static void main(String[] args) throws Exception {
               // TODO Auto-generated method stub
               ServerSocket ss=new ServerSocket(3000);
               Socket s=ss.accept();

              InputStream is=s.getInputStream();
              DataInputStream dis=new DataInputStream(is);
              String str1=dis.readLine();
              System.out.println("the message received from client:"+str1);
              OutputStream k=s.getOutputStream();
              PrintStream ps=new PrintStream(k);
              ps.println("hai Client");


package com.gnec;

import java.io.BufferedReader;
import java.io.InputStreamReader;
 * @author Administrator
public class IPTemp {


        * @param args
       public static void main(String[] args) {
               // TODO Auto-generated method stub
               BufferedReader br=new BufferedReader(new
               String str=null;
               System.out.println("Enter the decimal number");
                       catch(Exception e){
                       int[ ] a=new int[4];
                       Long num = Long.parseLong(str);
                       for (int i=0;i<4;i++){
                                int rem = (num.intValue()) % 255;
                                num = num / 255;

                              System.out.println("the rem value in "+i+":"+rem);
                        System.out.print("The ip address is:");
               for (int j=3;j>=0;j--){


1.   TCP/IP Protocol Suite by fourozan ,third edition.

                                                        Annexure - 2

                   Index Page
                                       Page    Sign /
S. No.   Date   Program / Experiment
                                        No.   Remarks


To top