76
Department of Computer Science & Engineering Computer Networks Lab manual Academic Year 2014-15 Guru Nanak Institute of Engineering and Technology. Dahegaon, Kalmeshwar Road, NAGPUR– 441501 (M.S.) Prepared by: Approved & Reviewed by: Issued by: w.e.f Date: Prof. Milind Tote 15-12-2014

Cnlab Manual14-15 (1)

Embed Size (px)

DESCRIPTION

computer network program

Citation preview

  • Department of Computer Science & Engineering

    Computer Networks Lab manual

    Academic Year 2014-15

    Guru Nanak Institute of Engineering and Technology.Dahegaon, Kalmeshwar Road, NAGPUR 441501 (M.S.)

    Prepared by: Approved & Reviewedby:

    Issued by: w.e.f Date:

    Prof. Milind Tote 15-12-2014

  • Guru Nanak Institute of Engineering and Technology. Dahegaon, Kalmeshwar Road, NAGPUR 441501 (M.S.)

    DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

    Lab Manual for the Academic Year 2014-15

    (In accordance with RTMNU syllabus)

    SUBJECT : COMPUTER NETWORKS

    SUBJECT CODE : BECSE309P

    SEMESTER : VI SEM CBS

    STREAM : COMPUTER SCIENCE & ENGINEERING

    PROGRAMMERS : PROF.MILIND TOTE

    INSTRUCTOR : PROF.ISHANT LAMBHATE

    Head CSE

  • Guru Nanak Institute of Engineering and Technology. Dahegaon, Kalmeshwar Road, NAGPUR 441501 (M.S.)

    Suggestions from Principal:

    Enhancement if any:

    Comments:

  • INDEX

    S. No. CONTENT Page. No

    1 Introduction About Lab 4

    2 Lab Code to Students 5

    3List of Lab Exercises

    Syllabus Programs (RTMNU)6

    4 Solutions for Programs 8

    Result: _______________ Signature of the faculty

    In-charge

  • INTRODUCTION ABOUT LABThere are 30 systems installed in this Lab. Their configurations are as follows:

    Processor : Core 2 Duo

    RAM : 1 GB

    Hard Disk : 160 GB

    Monitor : 17 TFT Color Monitor

    Mouse : Optical Mouse

    Key Board : Multimedia Keyboard

    Network Interface card : Present

    Software

    All systems are configured in Single Boot mode.

    Each student has a separate login for database access.

    Technologies like Java are installed in some systems.

    Softwares installed: C, C++

    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.

  • LAB CODE:

    Equipment in the lab for the use of student community. Students need to maintain a properdocument in the computer lab. Students must use the equipment with care. Any damage is causedis punishable.

    Students are required to carry their observation / programs book with completed exercises whileentering the lab.

    Students are supposed to occupy the machines allotted to them and are not supposed to talk ormake noise in the lab. The allocation is put up on the lab notice board.

    Lab can be used in free time / lunch hours by the students who need to use the systems shouldtake prior permission from the lab in-charge.

    Lab records need to be submitted on or before date of submission.

    Students are not supposed to use floppy disks/USB

  • LIST OF LAB EXERCISES:

    Sr. No.

    Name of Experiment

    1 Write a Program to Implement Bit Stuffing at Data Link Layer

    2 Write a Program to Implement Character Stuffing at Data Link Layer

    3 Write a Program to Implement Sliding window Protocol

    4 Write a Program to Implement Hamming Code using C

    5 Write a Program to Implement Shortest Path Algorithm (DIJKSRTRA's ALGORITHM).

    6 Write a Program to Implement Distance Vector Routing Algorithm

    7 Write a Program to Implement Leaky Bucket Algorithm

    8Write a Program to Implement Link State Routing

    9 Write a Program to Implement MONO ALPHABETIC CIPHER algorithm

    10 To write a java program to implement the File Transfer Protocol

    11 To write a java program to implement the concept of Simple Mail TransferProtocol.

    12 Aim : Study of NS2(Network Simulator)I)Basics of NS2II) Simulation with 2 nodes

    A) Creating a Simple Topology

    B) Getting Traces

    C) Using NAM

    III) A Simple Network Topology and Simulation Scenario

  • Experiment No 1

    AIM: Write a Program to Implement Bit Stuffing at Data Link Layer using C++

    THEORY:

    This method allows data frames to contain an arbitrary number of bits and allows character codeswith an arbitrary number of bits per character. At the start and end of each frame is a flag byteconsisting of the special bit pattern 01111110 . Whenever the sender's data link layer encountersfive consecutive 1s in the data, it automatically stuffs a zero bit into the outgoing bit stream. Thistechnique is called bit stuffing.

    When the receiver sees five consecutive 1s in the incoming data stream, followed by a zero bit, itautomatically destuffs the 0 bit. The boundary between two frames can be determined bylocating the flag pattern.

    Example : Original Bit Sequence: 0110111111111111111100

    After stuffing bits at sender 0110111110111110111110100

    ALGORITHM:

    1. Start

    2. Initialize the array for transmitted stream with the special bit pattern 0111 1110 which indicatesthe beginning of the frame.

    3. Get the bit stream to be transmitted in to the array.

    4. Check for five consecutive ones and if they occur, stuff a bit 0

    5. Display the data transmitted as it appears on the data line after appending 0111 1110

    at the end

    6. For destuffing, copy the transmitted data to another array after detecting the stuffed bits

    7. Display the received bit stream

    8. Stop

  • PROGRAM:

    #include

    //#include

    #include

    using namespace std;

    int main()

    {

    coutn;

    cout

  • {data[j+1]=data[j];

    }

    data[i+1]=0;

    c=0;

    }

    }

    cout

  • 01

    The transformed data is:

    11111011101

    Result: Thus we execute the program for Bit Stuffing at Data Link Layer

    Viva Voce:-

    1. What are the responsibilities of data link layer?

    Specific responsibilities of data link layer include the following.

    a) Framing

    b) Physical addressing

    c) Flow control

    d) Error control

    e) Access control

    2. What is redundancy?

    It is the error detecting mechanism, which means a shorter group of bits or extra bits may beappended at the destination of each unit.

    3. List out the available detection methods.

    There are 4 types of redundancy checks are used in data communication.

    a) Vertical redundancy checks (VRC).

    b) Longitudinal redundancy checks (LRC).

    c) Cyclic redundancy checks (CRC).

    d) Checksum

    4. Define flow control.

    Flow control refers to a set of procedures used to restrict the amount of data. The sender can sendbefore waiting for acknowledgment

  • Experiment No. 2

    AIM: Write a program to implement Character Stuffing at Data Link Layer using C

    THEORY: While sending the data ,to separate two frames we use flags, a flag may be anysequence of characters which indicates start and end of the frame. The problem may occur if theflag byte occurs in the data of the frame, to resolve the problem we stuff ESC string beforeeach flag byte in the data. If the ESC occurs in middle of the data then another ESC byte isinserted before ESC byte in the data. At receiver side if the two esc sequences are seen then itremoves one esc, if esc is followed with some data then it removes esc sequence and considersthe remaining data

    Character Stuffing

    Delimit with DLE STX or DLE ETX character flags

    Insert DLE before accidental DLE in data

    Remove stuffed character at destination

    ALGORITHM:

    1. Start

    2. Append DLE STX at the beginning of the string

    3. Check the data if character is present; if character DLE is present in the string (example DOODLE) insert another DLE in the string (ex: DOODLEDLE)

    4. Transmit DLE ETX at the end of the string

    5. Display the string

    6. Stop

    PROGRAM:

    #include

    #include

    //#include

    void main()

  • {int j,l,m,c,k;

    char a[50],b[50];

    printf("Enter the string:");

    scanf("%s",a);

    strcpy(b,"DLESTX");

    m=strlen(a);

    for(j=0;j

  • }a[j+3]='d';

    a[j+4]='l';

    a[j+5]='e';

    a[m]='\0';

    j+=5;

    }}}

    j++;

    }

    strcat(b,a);

    strcat(b,"DLEETX");

    printf("\n%s",b);

    printf("\nReceiverside:\n");

    m=strlen(a);

    for(j=0;j

  • for(k=c;k
  • Viva-Voce:-

    1) What is the use of router?

    A router is considered as a layer-3 relay that operates in the network layer, that is it acts on network layer frames. It can be used to link two dissimilar LANs. A router isolates LANs in to subnets to manage and control network traffic

    2) What is the need of the proxy server?

    In computer networks, a proxy server is a server (a computer system or an application program)that acts as an intermediary for requests from clients seeking resources from other servers.

    A client connects to the proxy server, requesting some service, such as a file, connection, webpage, or other resource, available from a different server. The proxy server evaluates the requestaccording to its filtering rules.

    For example, it may filter traffic by IP address or protocol. If the request is validated by the filter,the proxy provides the resource by connecting to the relevant server and requesting the serviceon behalf of the client. A proxy server may optionally alter the client's request or the server'sresponse, and sometimes it may serve the request without contacting the specified server..

    A proxy server has many potential purposes, including:

    To keep machines behind it anonymous (mainly for security) To speed up access to resources (using caching). Web proxies are commonly used to

    cache web pages from a web server

    To apply access policy to network services or content, e.g. to block undesired sites.

    To log / audit usage, i.e. to provide company employee Internet usage reporting.

    To bypass security/ parental controls.

    To scan transmitted content before delivery for malware.

    To scan outbound content, e.g. for data leak protection.

    To circumvent regional restrictions.

    4) What is Bridge?

    The device that can be used to interconnect two separate LANs is known as a bridge. It iscommonly used to connect two similar or dissimilar LANs. The bridge operates in layer 2, that isdata-link layer and that is why it is called level-2 relay Use of bridges offer a number ofadvantages, such as higher reliability, performance, security, convenience and larger geographiccoverage. Key features of a bridge are mentioned below:

  • A bridge operates both in physical and data-link layer

    A bridge uses a table for filtering/routing

    A bridge does not change the physical (MAC) addresses in a frame

    Types of bridges:

    0 Transparent Bridges 1 Source routing bridges

    5) What is switch?

    A switch is essentially a fast bridge having additional sophistication that allows fasterprocessing of frames. Some of important functionalities are:

    Ports are provided with buffer

    Switch maintains a directory: #address - port#

    Each frame is forwarded after examining the #address and forwarded to the proper port#

    Three possible forwarding approaches: Cut-through, Collision-free and Fully-buffered asbriefly explained below.

  • Experiment No 3

    AIM: Write a Program to Implement Sliding Window Protocol

    THEORY:

    Basics of all sliding window protocols:

    A sequence number is associated with each transmitted frame. Sequence numbers range from 0up to some maximum () circularly.

    A window is a list of consecutive sequence numbers. The size of a window is determined by twopointers: the lower edge and the higher edge. The size can be fixed or dynamically extended andshrink .

    The sender maintains a sending window with consecutive sequence numbers corresponding toframes sent but has yet not acknowledged.

    Whenever a new packet arrives from the network layer, it is given the next highest sequencenumber, and the upper edge of the window is advanced by one.

    When an acknowledgement comes in, the lower edge is advanced by one.

    The size of the sender's window is a dynamical one.

    The receiver maintains a receiving window with consecutive sequence numbers correspondingto frames it is permitted to accept.

    When a frame whose sequence number is equal to the lower edge of the window is received, it ispassed to the network layer, an acknowledgement is generated, and the window is rotated by one.

    The receiver's window always remains at its initial size.

  • Figure: A sliding window of size 1, with a 3-bit sequence number. (a) Initially. (b) After the firstframe has been sent. (c) After the first frame has been received. (d) After the first

    acknowledgement has been received.

    ALGORITHM:

    1. Set the window size.

    2. sender window

    Read the data to be transmitted and store it in the window.

    Initially the sender window contains window size-1 frames.

    The frames are sent out and left boundary of the window moves inward, Shrinking the size of thewindow.

    2.4 After receiving the acknowledgment the window is expanded to the number of framesacknowledged.

    3. Receiver Window

    3.1 Initially the receiver window contains window size-1 spaces for receiving the frames.

    3.2 As n frame reaches the receiver window its size gets reduced to n.

    3.3 After sending the acknowledgement the window size gets expanded to n.

  • PROGRAM:

    #include

    #include

    int sen_window[30],

    rec_window[30],n=0;

    int ack_no=-1,old_ack=0,count=0;

    void send();

    void sender();

    char sen_data[20];

    void main()

    {

    int ch;

    printf("Menu\n");

    printf("1.send\n");

    printf("2.exit\n");

    printf("enter your choice\n");

    scanf("%d",&ch);switch(ch)

    {

    case 1: send();

    break;

    case 2: exit(0);

    }

    }

    void send()

    {

  • int ch,i;

    printf("Enter the data \n");

    scanf("%s",sen_data);

    for(i=0;iack_no)

    { count++;

    }

  • old_ack=ack_no;

    ack_no=(count*7)+ack_no;

    sender();

    goto n;

    }

    }

    void sender()

    {

    int i;

    printf("The window in sender is \n");

    for(i=n;i

  • {printf("%c",sen_data[i]);

    }

    printf("\n");

    }

    Input/output:

    Menu

    1.send

    2.exit

    enter your choice

    1

    Enter the data

    111111

    do u want to send data from source 1/0

    1

    The window in sender is

    123456

    The window in receiver is

    0123456

    1

    do u want to send data from source 1/0

    0

    do u want to send acknowledgement 1/0

    1

  • Enter frame no

    2

    The window in sender is

    123456012

    111111

    The window in receiver is

    3456012

    Result:

    Thus the program to simulate sliding window protocol was written, executed and the results wereverified.

    Viva Voce:

    11 What are the key benefits of layered network? Ans: Main benefits of layered network are given below:

    i) Complex systems can be broken down into understandable subsystems.

    ii) Any facility implemented in one layer can be made visible to all other layers.

    iii) Services offered at a particular level may share the services of lower level.

    iv) Each layer may be analyzed and tested independently.

    v) Layers can be simplified, extended or deleted at any time.

    vi) Increase the interoperability and compatibility of various components build by differentvendors.

    2. How two adjacent layers communicate in a layered network? (Or what do you meanby Service Access Point?)

    Ans: In layered network, each layer has various entities and entities of layer i provide serviceto the entities of layer i+1. The services can be accessed through service access

    Point (SAP), which has some address through which the layer i+1 will access the servicesprovided by layer i.

  • 3. What are the key functions of data link layer?

    Ans: Data link layer transfers data in a structured and reliable manner so that the serviceprovided by the physical layer is utilized by data link layer. Main function of data link layer isframing and media access control.

    4. What do you mean by Protocol?

    Ans: In the context of data networking, a protocol is a formal set of rules and conventions thatgoverns how computers exchange information over a network medium. A protocolimplements the functions of one or more of the OSI layers.

    5. Compare circuit switched and packet-switched networks.

    A comparison of circuit switched and packet-switched networks.

  • Experiment No 4

    AIM: Write a program to implement Hamming Code using C

    THEORY:

    Achieve lower bound of r

    The codeword is numbered consecutively starting from left end as 1.

    The bits of powers of 2 (1,2,4,8,) are check bits; the rest (3,5,7, ) are filled with m data bits.

    A check bit forces the parity of some collection of bits, including itself, to be even (or odd)

    A bit is checked by just those check bits occurring in its expansion (e.g., bit 11 is checked by bits1,2, and 8)

    Checking algorithm

    Initialize counter = 0

    Examine all check bits

    If check bit k is error, add k into the counter.

    After all check bits are checked, the counter contains the number of the incorrect bit.

    PROGRAM:

    #include

    #include

    void chk_bin(int val);

    void main()

    {

    int bin;

    printf("\nEnter Any Binary Digit");

    scanf("%d",&bin);

  • chk_bin(bin);

    }

    void chk_bin(int val)

    {

    int p1,p2,p3,len,i=3;

    int data[10];

    data[0]=0;

    data[1]=0;

    data[2]=0;

    data[3]=0;

    while(val>0)

    {

    len=val%10;

    if(len==0 || len==1)

    {data[i]=len;

    i--;

    }

    else

    {printf("Entered Number is not in Binary Form");

    sleep(1);

    exit(1);

    }

    val=val/10;

    }

  • p1=data[0]^data[1]^data[3];

    p2=data[0]^data[2]^data[3];

    p3=data[1]^data[2]^data[3];

    printf("\n Encoded 7-Bit is");

    printf("\n%d%d%d%d%d%d%d",p1,p2,data[0],p3,data[1],data[2],data[3]);

    }

    Output:

    Enter Any Binary Digit

    1010

    Encoded 7-Bit is

    1011010

    Result: thus we execute the program for hamming code

    Viva Voce

    1.Why do you need error detection?

    Ans: As the signal is transmitted through a media, the signal gets corrupted because of noise anddistortion. In other words, the media is not reliable. To achieve a reliable communication throughthis unreliable media, there is need for detecting the error in the signal so that suitablemechanism can be devised to take corrective actions.

    2. Explain different types of Errors?

    Ans: The errors can be divided into two types: Single-bit error and Burst error.

    Single-bit Error The term single-bit error means that only one bit of given data unit (such as a byte, character, ordata unit) is changed from 1 to 0 or from 0 to 1.

    Burst Error The term burst error means that two or more bits in the data unit have changed from 0 to 1 orvice-versa. Note that burst error doesnt necessary means that error occurs in consecutive bits.

    3. What is the purpose of hamming code?

  • A hamming code can be designed to correct burst errors of certain lengths. So the simple strategyused by the hamming code to correct single bit errors must be redesigned to be applicable formultiple bit correction.

    4. What are the three modes of operations of HDLC?

    Ans: These three modes of operations are:

    1 Normal Response Mode (NRM): The primary station initiates transfers to the secondarystation. The secondary station can only transmit a response when, and only when, it isinstructed to do so by the primary station

    2 Asynchronous Response Mode (ARM): The primary station doesn't initiate transfers tothe secondary station. In fact, the secondary station does not have to wait to receiveexplicit permission from the primary station to transfer any frames. The frames may bemore than just acknowledgment frames.

    3 Asynchronous Balanced Mode (ABM): This mode uses combined stations. There is noneed for permission on the part of any station in this mode. This is because combinedstations do not require any sort of instructions to perform any task on the link.

  • Experiment No 5

    AIM: Implementation of Shortest Path Algorithm (Dijkstra's ALGORITHM)in C

    THEORY:

    A shortest path routing is a graph of the subnet with each node of the graph, representing a routeand each one of graph representing a communication line. To choose a route between a givenpair of routes, the algorithm first finds the shortest path between them on the graph. In Dijkstraalgorithm, each node is labeled with its distance from source node along the best-known path.Initially, no paths are known, so all paths are labeled with infinity. As algorithm proceeds andpaths are found, the label may change, reflecting better paths, when it is discovered that a labelrepresents a shortest path from source to that node. It is made permanent and never changedthereafter.

    ALGORITHM:

    Step 1. Source node is initialized and can be indicated as filled circle.

    Step 2. Initial path cost to neighboring nodes (adjacent nodes) or link cost is computed and thesenodes are relabeled considering source node.

    Step 3. Examine all adjacent nodes and find smallest label, make it permanent.

    Step 4. The smallest label is now working node, then Step 2 and Step 3 are repeated till thedestination node is reached.

    EXAMPLE:

  • (a)

    To find shortest path from A to D., we start by making node A as permanent. Then find each nodeadjacent to A, re-labeling each one with the distance to A. Whenever a node is rebelled, we labelit with node so that it reconstructs the final path later. After examining each of nodes adjacent toA, we examine all the tentatively labeled nodes in the whole graph and make the one with thesmallest label permanent as shown in fig. (b) This one becomes the new working node.

    Now at B, examine all the nodes adjacent to it. If the sum of the label on B and distance from Bto the node being considered is less than label at that node, we have shortest path so that node islabeled. After all nodes adjacent to the working node have been impacted and tentative tableschanged, the entire graph is searched for the tentatively labeled node with the smallest value.This node is made permanent and becomes the working node for the next round.

    PROGRAM:#include

    void dij(int,int [20][20],int [20],int [20],int);

    void main()

    {

    int i,j,n,visited[20],source,cost[20][20],d[20];

    printf("Enter no. of vertices: ");

    scanf("%d",&n);

    printf("Enter the cost adjacency matrix\n");

    for(i=1;i

  • {for(j=1;j
  • min=999;

    for(i=1;i

  • Enter the weight of the path between node 1 and 3: 3Enter the weight of the path between node 1 and 4: 4Enter the weight of the path between node 1 and 5: 5

    Enter the weight of the path between node 2 and 3: 5Enter the weight of the path between node 2 and 4: 2Enter the weight of the path between node 2 and 5: 3

    Enter the weight of the path between node 3 and 4: 1Enter the weight of the path between node 3 and 5: 4

    Enter the weight of the path between node 4 and 5: 5

    Enter The Source:2

    Enter The target 4CEShortest Path: 2

    RESULT: Thus we studied the DIJKSRTRA's Shortest Path Algorithm

    Viva Voce

    1. What routing is important in a computer network?

    Ans: In a packet switched network, there are number of nodes and different stations arecommunicating through these nodes. A packet is introduced in the network, which has to bedelivered at a destination station. The path to be followed by the packet is decided by the routingalgorithm. Routing tries to find out the least-cost or the optimized path between the source andthe destination stations. If routing is not done properly, congestion may take place.

    2. What are the primary conditions that affect routing?

    Ans: The primary conditions that affect routing are

    Failure (Link / Node failure) Network congestion

    3. What is flooding? Why flooding technique is not commonly used for routing?

    Ans: Flooding is one type of non-adaptive routing technique where no network information isused. In case of flooding as each node receives a packet, it is re-transmitted or forwarded to allthe links connected to the node (except the link through which the packet has arrived).

  • Flooding is not commonly used for routing for the following reasons:

    Flooding leads to unbounded number of packets May lead to congestion in the network A number of copies of the same packet is delivered at the destination node

    4. Differentiate between Link State and Distance Vector routing algorithms.

    Ans: Link-state algorithms (also known as shortest path first algorithms) flood routinginformation to all nodes in the internetwork. Each router, however, sends only the portion of therouting table that describes the state of its own links. In link-state algorithms, each router builds apicture of the entire network in its routing tables.

    Distance vector algorithms (also known as Bellman-Ford algorithms) call for each router tosend all or some portion of its routing table, but only to its neighbors. In essence, link-statealgorithms send small updates everywhere, while distance vector algorithms send larger updatesonly to neighboring routers. Distance vector algorithms know only about their neighbors.

  • Experiment No 6

    AIM: Write a Program to Implement Distance Vector Algorithm

    THEORY:

    Distance Vector Routing, a dynamic algorithm , operates by having each router maintain a table (i.e vector) giving the best known distance to each destination and which line to use to get there. These tables are updated by exchanging information with the neighbor's.

    In Distance vector routing each router maintains a routing table indexed by and containing anentry for each router in the subnet. It contains two parts, The preferred outgoing line for thatdestination and an estimate of time and distance on the metric used might be the delay in msec.

    Once every T msec each router sends to each neighbors a list of its estimated delays to each destination. It also receives a similar list from each neighbor.

    Imagine that one such list has arrived to one router from neighbor X with Xi being X's estimationof time delay to reach router i. If the router knows that the delay to X is 'm' msec, it also knowsthat it can reach router i via X in (Xi+m) msec. This updated information and the process ofupdation is as illustrated.

  • (b) Input From A,I,H and K

    Figure shows the delay vectors received from the neighbor's of router J. A claims to have a 12 msec delay to B, a 25 msec delay to C, a 40 msec delay to f etc.

    Suppose that J has measured an estimated delay to its neighbors A, I,H and K as 8,10,12,and 6 msec respectively.

    c) New Routing table for J

    PROGRAM:

    #include

    #include

    struct node

    {

  • unsigned dist[20];unsigned from[20];

    }rt[10];

    int main()

    {

    int costmat[20][20];

    int nodes,i,j,k,count=0;

    printf("\nEnter the number of nodes : ");

    scanf("%d",&nodes);//Enter the nodes

    printf("\nEnter the cost matrix :\n");

    for(i=0;i

  • {//We calculate the minimum distance

    rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];

    rt[i].from[j]=k;

    count++;

    }

    }while(count!=0);

    for(i=0;i

  • node 2 via 2 Distance 2

    node 3 via 3 Distance 3

    For router 2

    node 1 via 1 Distance 2

    node 2 via 2 Distance 0

    node 3 via 3 Distance 1

    For router 3

    node 1 via 1 Distance 3

    node 2 via 2 Distance 1

    node 3 via 3 Distance 0

  • Experiment No 7

    AIM: Implementation of Leaky Bucket Algorithm in C

    THEORY:

    The leaky-bucket implementation is used to control the rate at which traffic is sent to the network.A leaky bucket provides a mechanism by which bursty traffic can be shaped to present a steadystream of traffic to the network

    The leaky bucket algorithm uses two parameters to control traffic flow:

    Average rate: The average number of cells per second that "leak" from the hole in thebottom of the bucket and enter the network.

    Burst rate: The rate at which cells are allowed to accumulate in the bucket, expressed incells per second. For example, if the average burst rate is 10 cells per second, a burstof 10 seconds allows 100 cells to accumulate in the bucket.

    The leaky bucket algorithm also uses two state variables:

    Current time: The current wall clock time.

    Virtual time: A measure of how much data has accumulated in the bucket, expressed inseconds.

  • For example, if the average rate is 10 cells per second and 100 cells have accumulated inthe bucket, then the virtual time is 10 seconds ahead of the current time.

    ALGORITHM:

    The algorithm can be conceptually understood as follows:

    Consider a bucket with a hole in the bottom. If packets arrive, they are placed into the bucket. If the bucket is full, packets are

    discarded.

    Packets in the bucket are sent at a constant rate, equivalent to the size of the hole in the bucket

    PROGRAM:

    #include

    int rand(int a)

    { int rn=(random()%10)%a;

    return rn==0?1:rn; }

    int main()

    { int packet_sz[5],i,clk,b_size,o_rate,p_sz_rm=0,p_sz,p_time;

    for(i=0;i

  • printf("\n\nIncomming packet size (%d) is Greater than bucket capacity-PACKET REJECTED",packet_sz[i]);

    else

    printf("\n\nBucket capacity exceeded-REJECTED!!");

    else

    { p_sz_rm+=packet_sz[i];

    printf("\n\nIncomming Packet size: %d",packet_sz[i]);

    printf("\nBytes remaining to Transmit: %d",p_sz_rm);

    p_time = rand(4)*10;

    printf("\nTime left for transmission: %d units",p_time);

    for(clk=10; clk

  • Enter the rate of outflow

    Result: Thus we studied Leaky bucket algorithm

    Viva Voce:-

    What is congestion? Why congestion occurs?

    Ans : In a packet switching network, packets are introduced in the nodes (i.e. offered load), andthe nodes in-turn forward the packets (i.e. throughput) into the network. When the offered loadcrosses certain limit, then there is a sharp fall in the throughput. This phenomenon is known ascongestion. In every node of a packet switching network, queues (or buffers) are maintained toreceive and transmit packets (store/forward network). Due to busty nature of the network trafficthere may be situations where there is overflow of the queues. As a result there will be re-transmission of several packets, which further increases the network traffic. This finally leads tocongestion.

    1. What are the two basic mechanisms of congestion control?

    Ans : The two basic mechanisms of congestion control are:

    One is preventive, where precautions are taken so that congestion can not occur.

    Another is recovery from congestion, when congestion has already taken place

    2. How congestion control is performed by leaky bucket algorithm?

    Ans : In leaky bucket algorithm, a buffering mechanism is introduced between the host computer and the network in order to regulate the flow of traffic. Busty traffic are generated by the host computer and introduced in the network by leaky bucket mechanism in the following manner

    Packets are introduced in the network in one per tick

    In case of buffer overflow packets are discarded

    3. In what way token bucket algorithm is superior to leaky bucket algorithm?

    Ans : The leaky bucket algorithm controls the rate at which the packets are introduced in thenetwork, but it is very conservative in nature. Some flexibility is introduced in token bucketalgorithm. In token bucket algorithm tokens are generated at each tick (up to certain limit). Foran incoming packet to be transmitted it must capture a token and the transmission takes place atthe same rate. Hence some of the busty packets are transmitted at the same rate if tokens areavailable and thus introduces some amount of flexibility in the system. This also improves theperformance.

  • Experiment No-08

    AIM: Write a Program to Implement Link State Routing

    THEORY:

    Distance vector routing was used in the ARPANET until 1979, when it was replaced by link staterouting.

    The idea behind link state routing consists of five parts:

    Discover its neighbors and learn their network addresses. Measure the delay or cost to each of its neighbors.

    Construct a packet telling all it has just learned.

    Send this packet to all other routers.

    Compute the shortest path to every other router.

    Learning about the neighbors

    When a router is booted, it sends a special HELLO packet on each point-to-point line.

    The router on the other end is expected to send back a reply telling who it is (using a globally unique name).

    When two or more routers are connected by a LAN, the LAN can be modeled as a node, as shown in Fig. .

    Figure: (a) Nine routers and a LAN. (b) A graph model of (a).

    Measuring line cost

  • To determine the cost for a line, a router sends a special ECHO packet over the line that the otherside is required to send back immediately.

    By measuring the round-trip time and dividing it by two, the sending router can get a reasonable estimate of the delay.

    Should the load be taken into account when measuring the delay ?

    Figure: A subnet in which the East and West parts are connected by two lines.

    Building link state packets

    State packets may be built periodically, or when some significant event occurs, such as a line or neighbor going down or coming back up again.

    Figure: (a) A subnet. (b) The link state packets for this subnet.

    Distributing the link state packets

    The basic algorithm:

  • Each state packet contains a sequence number that is incremented for each new packet sent.

    Routers keep track of all the (source router, sequence) pairs they see.

    When a new link state packet comes in, it is checked against the list of packets already seen.

    1. If it is new, it is forwarded on all lines except the one it arrived on (i.e., flooding).

    2. If it is a duplicate, it is discarded.

    3. If a packet with a sequence number lower than the highest one seen so far ever arrives, it is rejected as being obsolete.

    PROGRAM:

    #include

    main()

    {int n,a[10][10],i,j,k;

    printf("\n ENTER THE NO.OF NODES: ");

    scanf("%d",&n);

    printf("\n ENTER THE MATRIX ELEMENTS: ");

    for(i=0;i

  • for(j=0;j
  • Experiment No-09

    AIM: Write a Program to Implement MONO ALPHABETIC CIPHER

    Algorithm.

    THEORY:

    Cryptography: Cryptography is the art or science encompassing the principles and methods of transforming message into one that is unintelligible, and retransforming that to its original form.

    Plaintext: The original intelligible message.

    Cipher text: The transformed message.

    cipher: An algorithm for transforming and intelligible message into one that is unintelligible by transposition and/or substitution methods.

    Encryption: The process of converting plaintext to cipher text using a cipher and a key.

    Decryption: The process of converting cipher text back to plaintext using a cipher and a key.

    Cryptanalysis: Cryptanalysis is the practice of analyzing and breaking cryptography. It is important that the cryptographic algorithms one uses be resistant to cryptanalysis. Cryptography: The study of both cryptography and cryptanalysis

    Monoalphabetic cipher

    A monoalphabetic cipher maps from a plain alphabet to cipher alphabet. Here a single cipher alphabet is used per message. Plaintext characters are substituted by a different alphabet stream of characters shifted to the right or left by n positions

    E.g., ABCDEFGHIJKLMNOPQRSTUVWXYZ

    DEFGHIJKLMNOPQRSTUVWXYZABC

    Caesar cipher corresponds to n = 3

    The substitution cipher by shifting alphabets gives 26! > 4 x 1026 possibilities

    This might appear to be too many choices to try for an exhaustive attack

    This is a weak cipher because it would be easy to guess the pattern

  • Mono-alphabetic ciphers are vulnerable to cryptanalysis attack

    The shift pattern above could be replaced by random assignment of characters for each alphabet

    E.g., ABCDEFGHIJKLMNOPQRSTUVWXYZ

    PMJSQOLEYTVUAXIKCGBWDRNHZF

    #include

    #include

    void encrypt()

    {

    char *p,ch;

    int i=0,k1,k[20];

    fflush(stdin);

    puts("\n enter plain text:");

    while((ch=getchar())!='\n')

    if(isalpha(ch))

    p[i++]=ch;

    p[i]='\0';

    k1=strlen(p);

    printf("enter mono alphabetic key:");

    for(i=0;i

  • {char *c,ch;

    int i=0,k1,k[20];

    puts("enter cipher text:");

    fflush(stdin);

    while((ch=getchar())!='\n')

    if(isalpha(ch))

    c[i++]=ch;

    c[i]='\0';

    k1=strlen(c);

    printf("\n enter mono alphabetic key:");

    for(i=0;i

  • printf("\n 1.Encrypt()\n 2.Decrypt()\n 3.Exit\n Enter your choice:");

    scanf("%d",&i);

    switch(i)

    {

    case 1:

    encrypt();

    break;

    case 2:

    decrypt();

    break;

    default:

    return;

    }}}

    OUTPUT:

    1.Encrypt()

    2.Decrypt()

    3.Exit

    Enter your choice:1

    enter plain text:vishy

    enter mono alphabetic key:1 2 3 4 5

    Encrypted text:WKVLD

    1.Encrypt()

    2.Decrypt()

    3.Exit

  • Enter your choice:2

    enter cipher text:wkvld

    enter mono alphabetic key:1 2 3 4 5

    decrypted text:VISHD

    RESULT: Thus we studied the MONO ALPHABETIC CIPHER encryption/decryptiontechnique.

    Viva Voce

    What are the different categories of Fast Ethernet?

    Ans: IEEE has designed two categories of Fast Ethernet: 100Base-X and 100Base-T4. 100Base-X uses two cables between hub and the station while 100Base-T4 uses four. 100-Base-X itself isdivided into two: 100Base-TX and 100base-FX.

    State some advantages of Wireless LANs.

    Ans: Some of the advantages of wireless LANs are mentioned below:

    Mobility: An increasing number of LAN users are becoming mobile. These mobile users requirethat they are connected to the network regardless of where they are because they wantsimultaneous access to the network.

    Installation speed and simplicity: Wireless LANs are very easy to install. There is norequirement for wiring every workstation and every room.

    Installation flexibility: If a company moves to a new location, the wireless system is mucheasier to move than ripping up all of the cables that a wired system would have snakedthroughout the building. This also provides portability.

    Reduced cost of ownership: While the initial cost of wireless LAN can be higher than thecost of wired LAN hardware, but long term cost benefits are greater in dynamic environmentrequiring frequent moves and changes.

  • Scalability: Wireless LAN can be configured in a variety of topologies to meet the users needand can be easily scaled to cover a large area with thousands of users roaming within it.

    State few disadvantages of wireless LANs.

    Ans: Some of the limitations and challenges are mentioned below:

    Lower reliability due to susceptibility of radio transmission to noise and interference.

    Fluctuation of the strength of the received signal through multiple paths causing fading.

    Vulnerable to eavesdropping leading to security problem.

    Limited data rate because of the use of spread spectrum transmission techniques enforced to ISM band users.

  • Experiment No 10AIM: To write a java program to implement the File Transfer Protocol.

    THEORY:

    FTP or file transfer protocol is a commonly used protocol for exchanging files over any networkthat supports the TCP/IP protocol ( such as the Internet or an intranet ). There are two computersinvolved in an FTP transfer: a server and a client.The FTP server, running FTP server software, listens on the network for connection requestsfrom other computers. The client computer, running FTP client software, initiates a connection tothe server. Once connected, the client can do a number of file manipulation operations such as uploadingfiles to the server, download files from the server, rename or delete files on the server and so on.FTP uses 2 TCP channels , port 20 is the data channel and port 21 is the command channel.

    FTP conducts all file transfer in foreground , instead of in background. By using TCP , FTPeliminates the need to worry about reliability. In the basic file transfer protocol , the serveraccepts three commands from the client.

    1) GET filename :Indicates that the existing file is to be transferred by the server to the client. It also supportsMGET command that allows to receive multiple files from the server.

    2) PUT filename:Indicated the specified file is to be transferred from the client to the server. It also supportsMPUT command to put multiple files on the server.3) BYE:Indicates that the client is closing the connection and exiting. The program implemented hereallows the client application to get the requested file from the server.

    ALGORITHM

    CLIENT1. Start the program.2. Create the client packet.3. After transferring the packet statement is displayed.4. Stop the program.

    SERVER1. Start the program.2. Create the server socket.3. Call the I/O stream.4. Print the file has been sent.5. Send the intimation to the client.6. Stop the program.

  • PROGRAM

    CLIENTimport java.io.*;import java.net.*;public class ftpclient{public static void main(String args[])throws Exception{Socket s=null;DataInputStream si=null;s=new Socket("LocalHost",5555);si=new DataInputStream(s.getInputStream());DataInputStream inp=new DataInputStream(System.in);DataOutputStream so=new DataOutputStream(s.getOutputStream());String str;System.out.println("\n Enter file name(path)");str=inp.readLine();so.writeBytes(str);so.writeBytes("\n");FileOutputStream fo=new FileOutputStream("sss.txt");int str1;while((str1=si.read())!=-1)fo.write((char)str1);System.out.println("\n file received successfully");si.close();}}

    SERVERimport java.io.*;import java.net.*;public class ftpserver{public static void main(String args[])throws Exception{Socket s=null;ServerSocket ss=null;DataOutputStream sso=null;DataInputStream ssi=null;ss=new ServerSocket(5555);s=ss.accept();sso=new DataOutputStream(s.getOutputStream());ssi=new DataInputStream(s.getInputStream());String s1;s1=ssi.readLine();FileInputStream fo=new FileInputStream(s1);

  • int str;while((str=fo.read())!=-1)sso.writeBytes(""+(char)+str);System.out.println("file has been sent successfully");sso.close();s.close();}}

    OUTPUTFTP CLIENTEnter file name(Path)m.txtFile received successfully.FTP SERVERFile has been sent successfully.

    RESULT:Thus the implementation of FTP client and server has been executed and output has been verifiedsuccessfully.

  • Experiment No-11

    AIM : To write a java program to implement the concept of Simple Mail Transfer Protocol.

    ALGORITHM:SERVER1. Start the program.2. Create the server packet3. Call the I/O stream.4. print the mail has been sent & send intimation.CLIENT1. Start the program.2. Create the client packet.3. After transferring packet statement is displayed.4. Stop the program.

    PROGRAM:

    SMTP CLIENTimport java.io.*;import java.net.*;class smtpclient1{public static void main(String a[]) throws Exception{Socket s=new Socket("127.0.0.1",9999);DataInputStream dis=new DataInputStream(s.getInputStream());DataInputStream in=new DataInputStream(System.in);PrintStream ps=new PrintStream(s.getOutputStream());ps.println("Ready");System.out.println(dis.readLine());String strFrom=in.readLine();ps.println(strFrom);System.out.println(dis.readLine());String strTo=in.readLine();ps.println(strTo);System.out.println(dis.readLine());String strSub=in.readLine();ps.println(strSub);System.out.println(dis.readLine());while(true){String msg=in.readLine();ps.println(msg);

  • if(msg.equals("quit")){System.out.println("msg is delerived to server and client quits");break;}}}}

    SMTP SERVERimport java.io.*;import java.net.*;class smtpserver1{public static void main(String args[])throws Exception{ServerSocket ss=new ServerSocket(9999);Socket s=ss.accept();ServiceClient(s);}public static void ServiceClient(Socket s)throws Exception{DataInputStream dis=null;PrintStream ps=null;dis=new DataInputStream(s.getInputStream());ps=new PrintStream(s.getOutputStream());FileWriter f=new FileWriter("testmail.eml");String tel=dis.readLine();if(tel.equals("Ready"))System.out.println("Ready signal received from client");ps.println("enter the from address");String from=dis.readLine();f.write("From:"+from+"\n");ps.println("enter the to address");String to=dis.readLine();f.write("to:"+to+"\n");ps.println("enter the subject");String sub=dis.readLine();f.write("subject"+sub+"\n");ps.println("enter the message");String msg=dis.readLine();f.write("\n Message:"+msg+"\n");f.close();}}

    RESULT: Thus the implementation of SMTP client and server has been implemented,executed and output is verified successfully.

  • Viva Voce:

    What is the relationship between TCP/IP and Internet?

    Ans: Internet is a network of different types of network. TCP/IP is a set of rules and proceduresthat govern the exchange of messages between hosts linked to different networks. TCP/IP createsan environment as if all hosts are connected to a single logical network.

    1.Explain how virtual connection is defined in ATM?

    Ans: ATM is based on packet switching by setting up a virtual circuit. Several nodes areconnected with the hosts and various switches. It sets up a logical path, not a permanent path. Atable is setup in each station in the path and information is entered in these tables. Once a virtualpath is created, there is an entry about the root through data communication takes place. Againanother table (information also provided) will provide information about the virtual circuit.Routing takes place based on these tables.

    2. Explain few benefits of ATM.

    Ans: The high-level benefits delivered through ATM services can be summarized as follows:

    Dynamic bandwidth for bursty traffic meeting application needs and delivering high utilization of networking resources; most applications are or can be viewed as inherently bursty, for example voice is bursty, as both parties are neither speaking at once nor all the time; video is bursty, as the amount of motion and required resolution varies over time.

    Smaller header with respect to the data to make the efficient use of bandwidth.

    Can handle Mixed network traffic very efficiently: The variety of packet sizes make traffic unpredictable. All network equipments should incorporate elaborate software systems to manage the various sizes of packets. ATM handles these problems efficiently with the fixed size cell.

    Cell network: All data is loaded into identical cells that can be transmitted with completepredictability and uniformity. Class-of-service support for multimedia traffic allowing applications with varying throughput and latency requirements to be met on a single network. Scalability in speed and network size supporting link speeds of T1/E1 to OC12 (622 Mbps).

    3. What is the difference between UNI and NNI?

    Ans: ATM switches support two primary types of interfaces: UNI and NNI. The UNI (User-Network Interface) connects ATM end systems (such as hosts and routers) to an ATM switch.

  • The NNI (Network-Network Interface) connects two ATM switches. Depending on whether theswitch is owned and located at the customer's premises or is publicly owned and operated by thetelephone company, UNI and NNI can be further subdivided into public and private UNIs andNNIs.

    4. What do you mean by LAN emulation?

    Ans: LAN Emulation: LAN Emulation (LANE) is a standard defined by the ATM Forum thatgives to stations attached via ATM the same capabilities that they normally obtain from legacyLANs, such as Ethernet and Token Ring. As the name suggests, the function of the LANEprotocol is to emulate a LAN on top of an ATM network. Specifically, the LANE protocoldefines mechanisms for emulating either an IEEE 802.3 Ethernet or an 802.5 Token Ring LAN.

  • Experiment No-12

    Aim : Study of NS2(Network Simulator)I)Basics of NS2II) Simulation with 2 nodes

    A) Creating a Simple Topology

    B) Getting Traces

    C) Using NAMIII) A Simple Network Topology and Simulation Scenario

    NS2 INTRODUCTION:

    Features of NS2:

    Protocols: TCP, UDP, HTTP, Routing algorithms, MAC etc.

    Traffic Models: CBR, VBR, Web etc Error Models: Uniform, bursty etc Misc: Radio propagation, Mobility models , Energy Models Topology Generation tools Visualization tools (NAM), Tracing

    NS is an object oriented discrete event simulator Simulator maintains list of events and executes one event after another. Single thread of control: no locking or race conditions. Back end is C++ event scheduler.

    Protocols mostlyFast to run, more control

    Front end is oTCLCreating scenarios, extensions to C++ protocolsfast to write and change

    NodesSet properties like queue length, location, Protocols, routing algorithms

    LinksSet types of link i.e. Simplex, duplex, wireless, satellite Set bandwidth, latency etc.

    TCL Syntax:

  • Variables: Arrays: Printing: Arithmetic Expression: Control Structures: Procedures:

    Syntax:

    set x 1set y $xset a(0) 1puts $a(0) \nset z = [expr $y + 5]if {$z == 6} then { puts Correct!}for {set i =0} {$i < 5} {incr i }{puts $i * $i equals [expr $i * $i]}proc sum {a b} {return [expr $a + $b]}

    NS programming Structure

    Create the event scheduler Turn on tracing Create network topology Create transport connections Generate traffic Insert errors

    Creating Event Scheduler

    Create event scheduler: set ns [new simulator] Schedule an event: $ns at

    event is any legitimate ns/tcl function

    Start Scheduler$ns at 5.0 finish$ns runproc finish {} {global ns nfclose $nfexec nam out.nam &exit 0

  • }Tracing All packet trace Variable trace$ns traceall[open out.tr w] + 0.51 0 1 cbr 500 00.0 1.0 0 20.510 1 cbr 500 00.0 1.0 0 2r 0.514 0 1 cbr 500 00.0 1.0 0 0set par [open output/param.tr w]$tcp attach $par$tcp trace cwnd_$tcp trace maxseq_$tcp trace rtt_

    Tracing and Animation

    Network Animator

    set nf [open out.nam w]$ns namtraceall$nfproc finish {} {global ns nfclose $nfexec nam out.nam &exit 0}

    Creating topology

    Two nodes connected by a link Creating nodes Creating link between nodes

    $ns $n0 $n1 set n0 [$ns node]set n1 [$ns node]$ns duplexlink

  • $n0 $n1 1Mb 10ms DropTail

    Sending data Create UDP agent Create CBR traffic source for feeding into UDP agent Create traffic sinkset udp0 [new Agent/UDP]$ns attachagent$n0 $udp0set cbr0 [new Application/Traffic/CBR]$cbr0 set packetSize_ 500$cbr0 set interval_ 0.005$cbr0 attachagent$udp0set null0 [new Agent/Null]$ns attachagent$n1 $null0

    Sending data Connect two agents Start and stop of data$ns connect $udp0 $null0$ns at 0.5 $cbr0 start$ns at 4.5 $cbr0 stop

  • Creating TCP Connections Create TCP agent and attach it to the node Create a Null Agent and attach it to the node Connect the agentsset tcp0 [new Agent/TCP]$ns attachagent$n0 $tcp0set null0 [new Agent/TCPSink]$ns attachagent$n1 $null0$ns connect $tcp0 $null0

    Traffic on top of TCP

    FTPTelnetset ftp [new Application/FTP]$ftp attachagent$tcp0set telnet [new Application/Telnet]$telnet attachagent$tcp0

    Introducing Errors

    Creating Error ModuleInserting Error Moduleset err [new ErrorModel]$err unit pkt_$err set rate_ 0.01$err ranvar [new RandomVariable/Uniform]$err droptarget[new Agent/Null]$ns lossmodel $err $n0 $n1

  • Examples UDP Script Tracing (wired,wireless,tcp) TCP without Loss TCP with Loss

    Simulation with 2 nodes

    Getting Started with an example:

    Creating a Simple Topology Getting Traces Using NAM

    Simple Example with two Nodes

    #create a new simulator object

    set ns [new Simulator]

    #open the nam trace file

    set nf [open out.nam w]

    $ns namtrace-all $nf

    #define a 'finish' procedure

    proc finish {} {

    global ns nf

    $ns flush-trace

    #close the trace file

    close $nf

    #execute nam on the trace file

    exec nam out.nam &

    exit 0

  • }set ns [new Simulator]: generates an NS simulator object instance, and assigns it to variable ns (italics is used for variables and values in this section). What this line does is the following:

    Create a scheduler (default is calendar scheduler)

    The "Simulator" object has member functions that do the following:

    Create compound objects such as nodes and links (described later)

    Connect network component objects created (ex. attach-agent)

    Set network component parameters (mostly for compound objects)

    Create connections between agents (ex. make connection between a "tcp" and "sink")

    Now, We are going to extend the example now: we are going to attach a udp agent to n1 and a sink at n2. (agents are abstractions of sockets that are present in unix)

    We are going to use udp to send constant bit-rate traffic what this means is that the rate is constant and packet size is constant (we will set these parameters)

    #create a udp agent and attach it to node n0

    set udp0 [new Agent/UDP]

    $ns attach-agent $n0 $udp0

    #Create a CBR traffic source and attach it to udp0

    set cbr0 [new Application/Traffic/CBR]

    $cbr0 set packetSize_ 500

    $cbr0 set interval_ 0.005

    $cbr0 attach-agent $udp0

    #create a Null agent(a traffic sink) and attach it to node n1

    set null0 [new Agent/Null]

    $ns attach-agent $n1 $null0

    #Connect the traffic source to the sink

  • $ns connect $udp0 $null0

    #Schedule events for CBR traffic

    $ns at 0.5 "$cbr0 start"

    $ns at 4.5 "$cbr0 stop"

    #call the finish procedure after 5 secs of simulated time

    $ns at 5.0 "finish"

    #run the simulation

    $ns run

    $ns attach-agent node agent: The attach-agent member function attaches an agent object created to a node object. Actually, what this function does is call the attach member function of specified node, which attaches the given agent to itself. Therefore, a user can do the same thing by, for example, $n0 attach $tcp. Similarly, each agent object has a member function attach-agentthat attaches a traffic source object to itself.

    $ns connect agent1 agent2: After two agents that will communicate with each other are created, the next thing is to establish a logical network connection between them. This line establishes a network connection by setting the destination address to each others' network and port address pair.

    III) A Simple Network Topology and Simulation Scenario

  • This network consists of 4 nodes (n0, n1, n2, n3) as shown in above figure. The duplex linksbetween n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10 ms of delay. The duplexlink between n2 and n3 has 1.7 Mbps of bandwidth and 20 ms of delay. Each node uses aDropTail queue, of which the maximum size is 10.

    A "tcp" agent is attached to n0, and a connection is established to a tcp "sink" agent attached ton3. As default, the maximum size of a packet that a "tcp" agent can generate is 1KByte. A tcp"sink" agent generates and sends ACK packets to the sender (tcp agent) and frees the receivedpackets. A "udp" agent that is attached to n1 is connected to a "null" agent attached to n3. A"null" agent just frees the packets received.

    A "ftp" and a "cbr" traffic generator are attached to "tcp" and "udp" agents respectively, and the"cbr" is configured to generate 1 KByte packets at the rate of 1 Mbps. The "cbr" is set to start at0.1 sec and stop at 4.5 sec, and "ftp" is set to start at 1.0 sec and stop at 4.0 sec.

    The code is as follows:

    #Create a simulator object

    set ns [new Simulator]

  • #Define different colors for data flows (for NAM)

    $ns color 1 Blue

    $ns color 2 Red

    #Open the NAM trace file

    set nf [open out.nam w]

    $ns namtrace-all $nf

    #Define a 'finish' procedure

    proc finish {} {

    global ns nf

    $ns flush-trace

    #Close the NAM trace file

    close $nf

    #Execute NAM on the trace file

    exec nam out.nam &

    exit 0

    }

    #Create four nodes

    set n0 [$ns node]

    set n1 [$ns node]

    set n2 [$ns node]

    set n3 [$ns node]

    #Create links between the nodes

    $ns duplex-link $n0 $n2 2Mb 10ms DropTail

    $ns duplex-link $n1 $n2 2Mb 10ms DropTail

    $ns duplex-link $n2 $n3 1.7Mb 20ms DropTail

  • #Set Queue Size of link (n2-n3) to 10

    $ns queue-limit $n2 $n3 10

    #Give node position (for NAM)

    $ns duplex-link-op $n0 $n2 orient right-down

    $ns duplex-link-op $n1 $n2 orient right-up

    $ns duplex-link-op $n2 $n3 orient right

    #Monitor the queue for link (n2-n3). (for NAM)

    $ns duplex-link-op $n2 $n3 queuePos 0.5

    #Setup a TCP connection

    set tcp [new Agent/TCP]

    $tcp set class_ 2

    $ns attach-agent $n0 $tcp

    set sink [new Agent/TCPSink]

    $ns attach-agent $n3 $sink

    $ns connect $tcp $sink

    $tcp set fid_ 1

    #Setup a FTP over TCP connection

    set ftp [new Application/FTP]

    $ftp attach-agent $tcp

    $ftp set type_ FTP

    #Setup a UDP connection

    set udp [new Agent/UDP]

    $ns attach-agent $n1 $udp

    set null [new Agent/Null]

    $ns attach-agent $n3 $null

  • $ns connect $udp $null

    $udp set fid_ 2

    #Setup a CBR over UDP connection

    set cbr [new Application/Traffic/CBR]

    $cbr attach-agent $udp

    $cbr set type_ CBR

    $cbr set packet_size_ 1000

    $cbr set rate_ 1mb

    $cbr set random_ false

    #Schedule events for the CBR and FTP agents

    $ns at 0.1 "$cbr start"

    $ns at 1.0 "$ftp start"

    $ns at 4.0 "$ftp stop"

    $ns at 4.5 "$cbr stop"

    #Detach tcp and sink agents (not really necessary)

    $ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"

    #Call the finish procedure after 5 seconds of simulation time

    $ns at 5.0 "finish"

    #Print CBR packet size and interval

    puts "CBR packet size = [$cbr set packet_size_]"

    puts "CBR interval = [$cbr set interval_]"

    #Run the simulation

    $ns run

    Explanation:

  • The following is the explanation of the script above. In general, an NS script starts with making aSimulator object instance.

    set ns [new Simulator]: generates an NS simulator object instance, and assigns it tovariable ns (italics is used for variables and values in this section). What this line does isthe following:

    o Initialize the packet format (ignore this for now)

    o Create a scheduler (default is calendar scheduler)

    o Select the default address format (ignore this for now)

    The "Simulator" object has member functions that do the following:

    o Create compound objects such as nodes and links (described later)o Connect network component objects created (ex. attach-agent)

    o Set network component parameters (mostly for compound objects)

    o Create connections between agents (ex. make connection between a "tcp" and "sink")

    o Specify NAM display options

    o Etc.

    Most of member functions are for simulation setup (referred to as plumbing functions in the Overview section) and scheduling, however some of them are for the NAM display. The "Simulator" object member function implementations are located in the "ns 2/tcl/lib/ns-lib.tcl" file.

    $ns color fid color: is to set color of the packets for a flow specified by the flow id (fid).This member function of "Simulator" object is for the NAM display, and has no effect onthe actual simulation.

    $ns namtrace-all file-descriptor: This member function tells the simulator to recordsimulation traces in NAM input format. It also gives the file name that the trace will bewritten to later by the command $ns flush-trace. Similarly, the member function trace-all is for recording the simulation trace in a general format.

    proc finish {}: is called after this simulation is over by the command $ns at 5.0 "finish".In this function, post-simulation processes are specified.

    set n0 [$ns node]: The member function node creates a node. A node in NS is compoundobject made of address and port classifiers (described in a later section). Users can createa node by separately creating an address and a port classifier objects and connecting themtogether. However, this member function of Simulator object makes the job easier. To seehow a node is created, look at the files: "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-

  • node.tcl".

    $ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex links ofspecified bandwidth and delay, and connects the two specified nodes. In NS, the outputqueue of a node is implemented as a part of a link, therefore users should specify thequeue-type when creating links. In the above simulation script, DropTail queue is used. Ifthe reader wants to use a RED queue, simply replace the word DropTail with RED. TheNS implementation of a link is shown in a later section. Like a node, a link is acompound object, and users can create its sub-objects and connect them and the nodes.Link source codes can be found in "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl"files. One thing to note is that you can insert error modules in a link component tosimulate a lossy link (actually users can make and insert any network objects). Refer tothe NS documentation to find out how to do this.

    $ns queue-limit node1 node2 number: This line sets the queue limit of the two simplexlinks that connect node1 and node2 to the number specified. At this point, the authors donot know how many of these kinds of member functions of Simulator objects areavailable and what they are. Please take a look at "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl", or NS documentation for more information.

    $ns duplex-link-op node1 node2 ...: The next couple of lines are used for the NAMdisplay. To see the effects of these lines, users can comment these lines out and try thesimulation.

    Now that the basic network setup is done, the next thing to do is to setup traffic agents such asTCP and UDP, traffic sources such as FTP and CBR, and attach them to nodes and agentsrespectively.

    set tcp [new Agent/TCP]: This line shows how to create a TCP agent. But in general,users can create any agent or traffic sources in this way. Agents and traffic sources are infact basic objects (not compound objects), mostly implemented in C++ and linked toOTcl. Therefore, there are no specific Simulator object member functions that createthese object instances. To create agents or traffic sources, a user should know the classnames these objects (Agent/TCP, Agnet/TCPSink, Application/FTP and so on). Thisinformation can be found in the NS documentation or partly in this documentation. Butone shortcut is to look at the "ns-2/tcl/libs/ns-default.tcl" file. This file contains thedefault configurable parameter value settings for available network objects. Therefore, itworks as a good indicator of what kind of network objects are available in NS and whatare the configurable parameters.

    $ns attach-agent node agent: The attach-agent member function attaches an agent objectcreated to a node object. Actually, what this function does is call the attach memberfunction of specified node, which attaches the given agent to itself. Therefore, a user cando the same thing by, for example, $n0 attach $tcp. Similarly, each agent object has amember function attach-agent that attaches a traffic source object to itself.

  • $ns connect agent1 agent2: After two agents that will communicate with each other arecreated, the next thing is to establish a logical network connection between them. Thisline establishes a network connection by setting the destination address to each others'network and port address pair.

    Assuming that all the network configuration is done, the next thing to do is write a simulationscenario (i.e. simulation scheduling). The Simulator object has many scheduling memberfunctions. However, the one that is mostly used is the following:

    $ns at time "string": This member function of a Simulator object makes the scheduler(scheduler_ is the variable that points the scheduler object created by [new Scheduler]command at the beginning of the script) to schedule the execution of the specified stringat given simulation time. For example, $ns at 0.1 "$cbr start" will make the schedulercall a start member function of the CBR traffic source object, which starts the CBR totransmit data. In NS, usually a traffic source does not transmit actual data, but it notifiesthe underlying agent that it has some amount of data to transmit, and the agent, justknowing how much of the data to transfer, creates packets and sends them.

    After all network configuration, scheduling and post-simulation procedure specifications aredone, the only thing left is to run the simulation. This is done by $ns run.

    Write a Program to Implement Link State RoutingThe leaky bucket algorithm uses two parameters to control traffic flow: Average rate: The average number of cells per second that "leak" from the hole in the bottom of the bucket and enter the network. Burst rate: The rate at which cells are allowed to accumulate in the bucket, expressed in cells per second. For example, if the average burst rate is 10 cells per second, a burst of 10 seconds allows 100 cells to accumulate in the bucket.The leaky bucket algorithm also uses two state variables: Current time: The current wall clock time. Virtual time: A measure of how much data has accumulated in the bucket, expressed in seconds.For example, if the average rate is 10 cells per second and 100 cells have accumulated in the bucket, then the virtual time is 10 seconds ahead of the current time.ALGORITHM: