Вы находитесь на странице: 1из 76

Department of Computer Science & Engineering

Computer Networks Lab manual Academic Year 2014-15

Computer Networks Lab manual Academic Year 2014-15 Guru Nanak Institute of Engineering and Technology.

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

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

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 SUBJECT CODE

SEMESTER

STREAM

PROGRAMMERS

INSTRUCTOR

:

:

:

COMPUTER NETWORKS

BECSE309P

VI SEM CBS

: COMPUTER SCIENCE & ENGINEERING

:

:

PROF.MILIND TOTE PROF.ISHANT LAMBHATE

Head CSE

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

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

3

List of Lab Exercises Syllabus Programs (RTMNU)

6

4

Solutions for Programs

8

Result:

Signature of the faculty In-charge

INTRODUCTION ABOUT LAB

There 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.



Software’s 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 proper document in the computer lab. Students must use the equipment with care. Any damage is caused is punishable.

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

Students are supposed to occupy the machines allotted to them and are not supposed to talk or make 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 should take 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.

Name of Experiment

No.

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

8

Write 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 Transfer Protocol.

12

Aim : Study of NS2(Network Simulator) I)Basics of NS2 II) 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 codes with an arbitrary number of bits per character. At the start and end of each frame is a flag byte consisting of the special bit pattern 01111110 . Whenever the sender's data link layer encounters five consecutive 1s in the data, it automatically stuffs a zero bit into the outgoing bit stream. This technique is called bit stuffing.

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

Example : Original Bit Sequence: 0110111111111111111100

After stuffing bits at sender

ALGORITHM:

1. Start

0110111110111110111110100

2. Initialize the array for transmitted stream with the special bit pattern 0111 1110 which indicates

the 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 de−stuffing, copy the transmitted data to another array after detecting the stuffed bits

7. Display the received bit stream

8. Stop

PROGRAM: #include <iostream> //#include <conio.h> #include<stdio.h> using namespace std; int
PROGRAM:
#include <iostream>
//#include <conio.h>
#include<stdio.h>
using namespace std;
int main()
{
cout<<"Enter the number of bits in the data";
int n,j,i;
cin>>n;
cout<<"Enter the data one digit at a time in binary";
int data[20];
for(i=0;i<n;i++)
{
cin>>data[i];
}
int c=0;
for(i=0;i<n;i++)
{
if(data[i]==1) c++;
else c=0;
if(c==5)
{
n=n+1;
for(j=n;j>i;j--)
{data[j+1]=data[j]; } data[i+1]=0; c=0; } } cout<<"The transformed data is: "<<endl;
{data[j+1]=data[j];
}
data[i+1]=0;
c=0;
}
}
cout<<"The transformed data is: "<<endl;
for(i=0;i<n;i++)
{
cout<<data[i];
}
//getch();
}
OUTPUT:
Enter the number of bits in the data
10
Enter the data one digit at a time in binary
1
1
1
1
1
1
1
1

0

1

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 be appended 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 send before 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 any sequence of characters which indicates start and end of the frame. The problem may occur if the flag byte occurs in the data of the frame, to resolve the problem we stuff “ESC” string before each flag byte in the data. If the “ESC” occurs in middle of the data then another “ESC” byte is inserted before “ESC” byte in the data. At receiver side if the two esc sequences are seen then it removes one esc, if esc is followed with some data then it removes esc sequence and considers the remaining data

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<stdio.h>

#include<string.h>

//#include<conio.h>

void main()

{ int j,l,m,c,k; char a[50],b[50]; printf("Enter the string:"); scanf("%s",a);
{
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<m;)
{
if(a[j]=='d')
{
if(a[j+1]=='l')
{
if(a[j+2]=='e')
{
c=j+2;
for(l=0;l<3;l++)
{
for(k=m;k>c;k--)
{
a[k]=a[k-1];
}
m++;
a[m]='\0';
c+=1;
} a[j+3]='d'; a[j+4]='l'; a[j+5]='e'; a[m]='\0'; j+=5; }}} j++; } strcat(b,a);
}
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<m;)
{
if(a[j]=='d')
{
if(a[j+1]=='l')
{
if(a[j+2]=='e')
{
c=j;
for(l=0;l<3;l++)
{
for(k=c;k<m;k++) a[k]=a[k+1]; } c++; } j=c; } } j++; } printf("\n%s",a); //getch(); } At Sender:
for(k=c;k<m;k++)
a[k]=a[k+1];
}
c++;
}
j=c;
}
}
j++;
}
printf("\n%s",a);
//getch();
}
At Sender:
INPUT:
Enter String
GNIET
OUTPUT:
Stuffed data
DLESTXGNIETDLEETX
At receiver:
OUTPUT:
The message: GNIET
RESULT: Thus we studied the implementation of Character Stuffing at Data Link Layer

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, web page, or other resource, available from a different server. The proxy server evaluates the request according 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 service on behalf of the client. A proxy server may optionally alter the client's request or the server's response, 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 is commonly used to connect two similar or dissimilar LANs. The bridge operates in layer 2, that is data-link layer and that is why it is called level-2 relay Use of bridges offer a number of advantages, such as higher reliability, performance, security, convenience and larger geographic coverage. 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 faster processing 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 as briefly 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 0

up to some maximum () circularly.

A window is a list of consecutive sequence numbers. The size of a window is determined by two

pointers: the lower edge and the higher edge. The size can be fixed or dynamically extended and shrink .

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

Whenever a new packet arrives from the network layer, it is given the next highest sequence number, 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 corresponding

to frames it is permitted to accept.

When a frame whose sequence number is equal to the lower edge of the window is received, it is passed 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)

Figure: A sliding window of size 1, with a 3-bit sequence number. (a) Initially. (b) After the first frame 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 the window.

2.4 After receiving the acknowledgment the window is expanded to the number of frames

acknowledged.

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<stdio.h>

#include<stdlib.h>

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;i<=30;i++)

{

sen_window[i]=i%7;

rec_window[i]=i%7;

}

n:

printf("\n do u want to send data from source 1/0 \n");

scanf("%d",&ch);

if(ch==1)

{

n++;

sender();goto n;

}

printf("do u want to send acknowledgement 1/0 \n");

scanf("%d",&ch);

if(ch==1)

{

printf("Enter frame no \n");

scanf("%d",&ack_no);

if(old_ack>ack_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<=6+ack_no+1;i++)

{

printf("%d",sen_window[i]);

}printf("\n");

for(i=n;i<=6+ack_no+1;i++)

{

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

}

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

for(i=ack_no+1;i<=6+ack_no+1;i++)

{

printf("%d",rec_window[i]);

}

printf("\n");

for(i=ack_no+1;i<=(n-1);i++)

{ printf("%c",sen_data[i]); } printf("\n"); } Input/output: Menu 1.send 2.exit enter your choice
{
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 were verified.

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 different

vendors.

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

Ans: In layered network, each layer has various entities and entities of layer i provide service to 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 services provided 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 service provided by the physical layer is utilized by data link layer. Main function of data link layer is framing 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 that governs how computers exchange information over a network medium. A protocol implements 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.

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 bits

1,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<stdio.h>

#include<stdlib.h>

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;
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 and distortion. In other words, the media is not reliable. To achieve a reliable communication through this unreliable media, there is need for detecting the error in the signal so that suitable mechanism 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, or data 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 or vice-versa. Note that burst error doesn’t 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 strategy used by the hamming code to correct single bit errors must be redesigned to be applicable for multiple 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 secondary station. The secondary station can only transmit a response when, and only when, it is instructed to do so by the primary station

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

3 Asynchronous Balanced Mode (ABM): This mode uses combined stations. There is no need for permission on the part of any station in this mode. This is because combined stations 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 route and each one of graph representing a communication line. To choose a route between a given pair of routes, the algorithm first finds the shortest path between them on the graph. In Dijkstra algorithm, 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 and paths are found, the label may change, reflecting better paths, when it is discovered that a label represents a shortest path from source to that node. It is made permanent and never changed thereafter.

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 these nodes 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 the destination node is reached.

EXAMPLE:

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

(a)

To find shortest path from A to D., we start by making node A as permanent. Then find each node adjacent to A, re-labeling each one with the distance to A. Whenever a node is rebelled, we label it with node so that it reconstructs the final path later. After examining each of nodes adjacent to A, we examine all the tentatively labeled nodes in the whole graph and make the one with the smallest 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 B to the node being considered is less than label at that node, we have shortest path so that node is labeled. After all nodes adjacent to the working node have been impacted and tentative tables changed, 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.

permanent and becomes the working node for the next round. PROGRAM: #include<stdio.h> void dij(int,int

PROGRAM:

#include<stdio.h>

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<=n;i++)

{

for(j=1;j<=n;j++)

{

scanf("%d",&cost[i][j]);

}

}

printf("\nEnter the source node: ");

scanf("%d",&source);

dij(source,cost,visited,d,n);

for(i=1;i<=n;i++)

if(i!=source)

printf("\nShortest path from %d to %d is %d",source,i,d[i]);

}

void dij(int source,int cost[20][20],int visited[20],int d[20],int n)

{

int i,j,min,u,w;

for(i=1;i<=n;i++)

{

visited[i]=0;

d[i]=cost[source][i];

}

visited[source]=1;

d[source]=0;

for(j=2;j<=n;j++)

{

min=999;

for(i=1;i<=n;i++)

{

if(!visited[i]){

if(d[i]<min)

{

min=d[i];

u=i;

}

}

}

//for i

visited[u]=1;

for(w=1;w<=n;w++)

{

if(cost[u][w]!=999 && visited[w]==0)

{

if(d[w]>cost[u][w]+d[u])

d[w]=cost[u][w]+d[u];

}

}

}

}

//for w

// for j

INPUT/OUTPUT:

Shortest Path Algorithm(Dijkstra's ALGORITHM)

Enter the weight of the path between node 1 and 2: 2

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

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

Enter the weight of the path between node 3 and 4: 1 Enter 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 4 CE Shortest 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 are communicating through these nodes. A packet is introduced in the network, which has to be delivered at a destination station. The path to be followed by the packet is decided by the routing algorithm. Routing tries to find out the least-cost or the optimized path between the source and the 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 is used. In case of flooding as each node receives a packet, it is re-transmitted or forwarded to all the 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 routing information to all nodes in the internetwork. Each router, however, sends only the portion of the routing table that describes the state of its own links. In link-state algorithms, each router builds a picture of the entire network in its routing tables.

Distance vector algorithms (also known as Bellman-Ford algorithms) call for each router to send all or some portion of its routing table, but only to its neighbors. In essence, link-state algorithms send small updates everywhere, while distance vector algorithms send larger updates only 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 an entry for each router in the subnet. It contains two parts, The preferred outgoing line for that destination 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.

It also receives a similar list from each neighbor. Imagine that one such list has arrived

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

(b) Input From A,I,H and K Figure shows the delay vectors received from the neighbor's

(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.

neighbors A, I,H and K as 8,10,12,and 6 msec respectively. PROGRAM: #include<stdio.h>

PROGRAM:

#include<stdio.h>

#include<stdlib.h>

struct node

{

c) New Routing table for J

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<nodes;i++)

{

for(j=0;j<nodes;j++)

{

scanf("%d",&costmat[i][j]);

costmat[i][i]=0;

rt[i].dist[j]=costmat[i][j];//initialise the distance equal to cost matrix

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

}}

do

{count=0;

for(i=0;i<nodes;i++)//We choose arbitary vertex k and we calculate the direct distancefrom the node i to k using the cost matrix and add the distance from k to node j

for(j=0;j<nodes;j++)

for(k=0;k<nodes;k++)

if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])

{//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<nodes;i++)

{

printf("\n\n For router %d\n",i+1);

for(j=0;j<nodes;j++)

{

printf("\t\nnode %d via %d Distance %d ",j+1,rt[i].from[j]+1,rt[i].dist[j]);

}

}

printf("\n\n");

}

Input/Output:-

Enter the number of nodes :

3

Enter the cost matrix :

0

2

7

2 7

0 1

1 0

For router 1

node 1 via 1 Distance 0

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 steady stream of traffic to the network

shaped to present a steady stream of traffic to the network The leaky bucket algorithm uses

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

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<stdio.h>

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<5;++i)

packet_sz[i]=rand(6)*10;

for(i=0;i<5;++i)

printf("packet[%d]:%d bytes\t",i,packet_sz[i]);

printf("\nEnter the Output rate:");

scanf("%d",&o_rate);

printf("Enter the Bucket Size:");

scanf("%d",&b_size);

for(i=0; i<5; ++i)

{ if((packet_sz[i]+p_sz_rm) > b_size)

if(packet_sz[i] > b_size)

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<=p_time; clk+=10)

{ sleep(1);

if(p_sz_rm)

{ if(p_sz_rm <= o_rate)

printf("\n Packet of size %d Transmitted",p_sz_rm),p_sz_rm=0;

else

printf("\n Packet of size %d Transmitted",o_rate),p_sz_rm -= o_rate;

printf("----Bytes Remaining after Transmission:%d",p_sz_rm);

}

else

printf("\n No packets to transmit!!");

printf(" Time Left:%d",p_time-clk);

}}}}

Input/ Output:

Press any key to stop

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), and the nodes in-turn forward the packets (i.e. throughput) into the network. When the “offered load” crosses certain limit, then there is a sharp fall in the throughput. This phenomenon is known as congestion. In every node of a packet switching network, queues (or buffers) are maintained to receive and transmit packets (store/forward network). Due to busty nature of the network traffic there 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 to congestion.

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 the network, but it is very conservative in nature. Some flexibility is introduced in token bucket algorithm. In token bucket algorithm tokens are generated at each tick (up to certain limit). For an incoming packet to be transmitted it must capture a token and the transmission takes place at the same rate. Hence some of the busty packets are transmitted at the same rate if tokens are available and thus introduces some amount of flexibility in the system. This also improves the performance.

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 state routing.

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

by a LAN, the LAN can be modeled as a node, as shown in Figure: (a)
by a LAN, the LAN can be modeled as a node, as shown in Figure: (a)

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 other side 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 ?

the load be taken into account when measuring the delay ? Figure: A subnet in which

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.

as a line or neighbor going down or coming back up again. Figure: (a) A subnet.

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<stdio.h>

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<n;i++)

{

printf("\nENTER THE DISTANCE FOR NODE:%d\n",i+1);

for(j=0;j<n;j++)

{

scanf("%d",&a[i][j]);

}}

for(i=0;i<n;i++)

{

printf("THE LINK STATE PACKETS FOR NODE:%d\n",i+1);

printf("\n NODE\tDISTANCE\n");

for(j=0;j<n;j++)

{

if(a[i][j]!=0&&a[i][j]!=-1)

{

printf("%d\t%d\n",j+1,a[i][j]);

}}

printf("\n\n");

}}

Input/ Output:

ENTER THE NO.OF NODES: 2

ENTER THE MATRIX ELEMENTS:

ENTER THE DISTANCE FOR NODE:1

2

3

ENTER THE DISTANCE FOR NODE:2

3

4

THE LINK STATE PACKETS FOR NODE:1

NODE

DISTANCE

1

2

2

3

THE LINK STATE PACKETS FOR NODE:2

NODE

DISTANCE

1

3

2

4

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<stdio.h>

#include<string.h>

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<k1;i++)

scanf("%d",&k[i]);

printf("Encrypted text:");for(i=0;i<k1;i++)

if(isalpha(ch=p[i]))

printf("%c",(toupper(ch)+k[i]-'A')%26+'A');

}

void decrypt()

{

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<k1;i++)

{

scanf("%d",&k[i]);

printf("\n decrypted text:");

for(i=0;i<k1;i++)

if(isalpha(ch=c[i]))

printf("%c",(toupper(ch)+26-k[i]-'A')%26+'A');

}}

void main()

{

int i;

while(1)

{

printf("\n 1.Encrypt()\n 2.Decrypt()\n 3.Exit\n Enter your choice:"); scanf("%d",&i); switch(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/decryption

technique.

Viva Voce

CIPHER encryption/decryption technique. Viva Voce What are the different categories of Fast Ethernet? Ans:

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 is divided 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 require that they are connected to the network regardless of where they are because they want simultaneous access to the network.

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

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

Reduced cost of ownership: While the initial cost of wireless LAN can be higher than the

cost of wired LAN hardware, but long term cost benefits are greater in dynamic environment

requiring frequent moves and changes.

Scalability: Wireless LAN can be configured in a variety of topologies to meet the users need and 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 10 AIM: 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 network that supports the TCP/IP protocol ( such as the Internet or an intranet ). There are two computers involved in an FTP transfer: a server and a client. The FTP server, running FTP server software, listens on the network for connection requests from other computers. The client computer, running FTP client software, initiates a connection to the server. Once connected, the client can do a number of file manipulation operations such as uploading files 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 , FTP eliminates the need to worry about reliability. In the basic file transfer protocol , the server accepts 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 supports MGET 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 supports MPUT command to put multiple files on the server. 3) BYE:

Indicates that the client is closing the connection and exiting. The program implemented here allows the client application to get the requested file from the server.

ALGORITHM

CLIENT

1. Start the program.

2. Create the client packet.

3. After transferring the packet statement is displayed.

4. Stop the program.

SERVER

1. 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

CLIENT import 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();

}

}

SERVER

import 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();

}

}

OUTPUT

FTP CLIENT

Enter file name(Path) m.txt File received successfully.

FTP SERVER

File has been sent successfully.

RESULT:

Thus the implementation of FTP client and server has been executed and output has been verified successfully.

Experiment No-11

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

ALGORITHM:

SERVER

1. Start the program.

2. Create the server packet

3. Call the I/O stream.

4. print the mail has been sent & send intimation.

CLIENT

1. Start the program.

2. Create the client packet.

3. After transferring packet statement is displayed.

4. Stop the program.

PROGRAM:

SMTP CLIENT import 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 SERVER

import 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 procedures that govern the exchange of messages between hosts linked to different networks. TCP/IP creates an 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 are connected with the hosts and various switches. It sets up a logical path, not a permanent path. A table is setup in each station in the path and information is entered in these tables. Once a virtual path is created, there is an entry about the root through data communication takes place. Again another 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 complete predictability 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 OC–12 (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 the switch is owned and located at the customer's premises or is publicly owned and operated by the telephone company, UNI and NNI can be further subdivided into public and private UNIs and NNIs.

4. What do you mean by LAN emulation?

Ans: LAN Emulation: LAN Emulation (LANE) is a standard defined by the ATM Forum that gives to stations attached via ATM the same capabilities that they normally obtain from legacy LANs, such as Ethernet and Token Ring. As the name suggests, the function of the LANE protocol is to emulate a LAN on top of an ATM network. Specifically, the LANE protocol defines 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 NS2 II) Simulation with 2 nodes

A) Creating a Simple Topology

B) Getting Traces

C) Using NAM

III) 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 mostly Fast to run, more control

● Front end is oTCL Creating scenarios, extensions to C++ protocols fast to write and change

Nodes

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

Links Set 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 1 set y $x set a(0) 1 puts “$a(0) \n” set 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 <time> <event>

event is any legitimate ns/tcl function

● Start Scheduler $ns at 5.0 “finish” $ns run proc finish {} { global ns nf close $nf exec nam out.nam & exit 0

}

Tracing

● All packet trace

● Variable trace

$ns traceall [open out.tr w] <event> <time> <from> <to> <pkt> <size> <flowid> <src> <dst> <seqno> <aseqno>

+ 0.51 0 1 cbr 500 0

0.0 1.0 0 2

0.51

0 1 cbr 500 0

0.0 1.0 0 2

r 0.514 0 1 cbr 500 0

0.0 1.0 0 0

set 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 $nf proc finish {} { global ns nf close $nf exec nam out.nam & exit 0

}

Creating topology

● Two nodes connected by a link

● Creating nodes

● Creating link between nodes

– $ns <link_type> $n0 $n1 <bandwidth> <delay> <queuetype> set n0 [$ns node] set n1 [$ns node] $ns duplexlink

$n0 $n1 1Mb 10ms DropTail

$n0 $n1 1Mb 10ms DropTail Sending data ● Create UDP agent ● Create CBR traffic source

Sending data

● Create UDP agent

● Create CBR traffic source for feeding into UDP agent

● Create traffic sink set udp0 [new Agent/UDP] $ns attachagent $n0 $udp0 set cbr0 [new Application/Traffic/CBR] $cbr0 set packetSize_ 500 $cbr0 set interval_ 0.005 $cbr0 attachagent

$udp0

set 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

Creating TCP Connections

● Create TCP agent and attach it to the node

● Create a Null Agent and attach it to the node

● Connect the agents set tcp0 [new Agent/TCP] $ns attachagent $n0 $tcp0 set null0 [new Agent/TCPSink] $ns attachagent $n1 $null0 $ns connect $tcp0 $null0

Traffic on top of TCP

FTP Telnet set ftp [new Application/FTP] $ftp attachagent

$tcp0

set telnet [new Application/Telnet] $telnet attachagent

$tcp0

Introducing Errors

Creating Error Module Inserting Error Module set 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-agent that 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.

This network consists of 4 nodes (n0, n1, n2, n3) as shown in above figure. The duplex links between n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10 ms of delay. The duplex link between n2 and n3 has 1.7 Mbps of bandwidth and 20 ms of delay. Each node uses a DropTail 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 to n3. 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 received packets. 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 at 0.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 a Simulator object instance.

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:

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 on the actual simulation.

$ns namtrace-all file-descriptor: This member function tells the simulator to record simulation traces in NAM input format. It also gives the file name that the trace will be written 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 compound object made of address and port classifiers (described in a later section). Users can create a node by separately creating an address and a port classifier objects and connecting them together. However, this member function of Simulator object makes the job easier. To see how 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 of specified bandwidth and delay, and connects the two specified nodes. In NS, the output queue of a node is implemented as a part of a link, therefore users should specify the queue-type when creating links. In the above simulation script, DropTail queue is used. If the reader wants to use a RED queue, simply replace the word DropTail with RED. The NS implementation of a link is shown in a later section. Like a node, a link is a compound 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 to simulate a lossy link (actually users can make and insert any network objects). Refer to the NS documentation to find out how to do this.

$ns queue-limit node1 node2 number: This line sets the queue limit of the two simplex links that connect node1 and node2 to the number specified. At this point, the authors do not know how many of these kinds of member functions of Simulator objects are available 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.

: The next couple of lines are used for the NAM

$ns duplex-link-op node1 node2

display. To see the effects of these lines, users can comment these lines out and try the simulation.

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

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 in fact basic objects (not compound objects), mostly implemented in C++ and linked to OTcl. Therefore, there are no specific Simulator object member functions that create these object instances. To create agents or traffic sources, a user should know the class names these objects (Agent/TCP, Agnet/TCPSink, Application/FTP and so on). This information can be found in the NS documentation or partly in this documentation. But one shortcut is to look at the "ns-2/tcl/libs/ns-default.tcl" file. This file contains the default configurable parameter value settings for available network objects. Therefore, it works as a good indicator of what kind of network objects are available in NS and what are the configurable parameters.

$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-agent that 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.

Assuming that all the network configuration is done, the next thing to do is write a simulation scenario (i.e. simulation scheduling). The Simulator object has many scheduling member functions. 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 string at given simulation time. For example, $ns at 0.1 "$cbr start" will make the scheduler call a start member function of the CBR traffic source object, which starts the CBR to transmit data. In NS, usually a traffic source does not transmit actual data, but it notifies the underlying agent that it has some amount of data to transmit, and the agent, just knowing how much of the data to transfer, creates packets and sends them.

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