0% found this document useful (0 votes)
54 views

Lab Manual in CN Lab 2021

The document describes implementing Dijkstra's algorithm to find the shortest path between nodes in a network. It includes: 1) Dijkstra's algorithm uses a distance vector table to store the distance from each node to its neighbors, and updates the distances each time a shorter path is found. 2) The C program initializes all distances to infinity, sets the source node distance to 0, and iterates to find the shortest path to each unvisited node. 3) It uses arrays to store costs, distances, predecessors and visited nodes, and finds the unvisited node with the minimum distance on each iteration to build up the shortest path tree.

Uploaded by

PRIYANGA SEKAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Lab Manual in CN Lab 2021

The document describes implementing Dijkstra's algorithm to find the shortest path between nodes in a network. It includes: 1) Dijkstra's algorithm uses a distance vector table to store the distance from each node to its neighbors, and updates the distances each time a shorter path is found. 2) The C program initializes all distances to infinity, sets the source node distance to 0, and iterates to find the shortest path to each unvisited node. 3) It uses arrays to store costs, distances, predecessors and visited nodes, and finds the unvisited node with the minimum distance on each iteration to build up the shortest path tree.

Uploaded by

PRIYANGA SEKAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Ex.no 1.

IMPLEMENT THE DATA LINK LAYER FRAMING METHODS,

Aim:
To implement the data link layer framing methods.
1) Bit stuffing
ii) Character stuffing.

Required software:
Turbo C
Theory:
The framing method gets around the problem of
resynchronization after an error by having each frame start with the
ASCII character sequence DLE STX and the sequence DLE ETX. If the
destination ever losses the track of the frame boundaries all it has to do is
look for DLE STX or DLE ETX characters to figure out. The data link
layer on the receiving end removes the DLE before the data are given to
the network layer. This technique is called character stuffing.

Program Algorithm:
Begin
Step 1: Initialize I and j as 0
Step 2: Declare n and pos as integer and a[20],b[50],ch as character
Step 3: read the string a
Step 4: find the length of the string n, i.e n-strlen(a)
Step 5: read the position, pos
Step 6: if pos > n then
Step 7: print invalid position and read again the position, pos
Step 8: endif
Step 9: read the character, ch
Step 10: Initialize the array b, b[0…5] as ’d’, ’l’, ’e’, ’s’, ’t’,’x’ respectively
Step 11: j=6;
Step 12: Repeat step[(13to22) until i<n
Step 13: if i==pos-1 then
Step 14: initialize b array,b[j],b[j+1]…b[j+6] as‘d’, ‘l’, ‘e’ ,’ch, ’d’, ‘l’,‘e’
respectively
Step 15: increment j by 7, i.e j=j+7
Step 16: endif
Step 17: if a[i]==’d’ and a[i+1]==’l’ and a[i+2]==’e’ then
Step 18: initialize array b, b[13…15]=’d’, ‘l’, ‘e’ respectively
Step 19: increment j by 3, i.e j=j+3

Page 1
Step 20: endif
Step 21: b[j]=a[i]
Step 22: increment I and j;
Step 23: initialize b array,b[j],b[j+1]…b[j+6] as‘d’, ‘l’,‘e’,’e’,‘t’, ‘x’,‘\0’
respectively
Step 24: print frame after stuffing
Step 25: print b
End

1a. BIT STUFFING PROGRAM

#include<stdio.h> int
main()
{
int a[15];
int i, j ,k,n,c=0,pos=0;
printf("\n Enter the number of bits: ");
scanf("%d",&n);
printf("\n Enter the bits: ");
for(i=0;i<n;i++) scanf("%d",&a[i]);
for(i=0;i<n;i++);
{
if(a[i]==1)
{
c++;
if(c==5)
{
pos=i+1;
c=0;
for(j=n;j>=pos;j--)
{
k=j+1;

Page 2
a[k]=a[j];
}
a[pos]=0;
n=n+1;
}
}
else
c=0;
}
printf("\n DATA AFTER STUFFING \n");
for(i=0;i<n;i++) {
printf("%d",a[i]);
}
}

Output:

Enter the number of bits: 12


Enter the bits: 1 0 1 1 1 1 1 1 1 0 1 1 DATA
AFTER STUFFING 1011111011011

1b. CHARACTER STUFFING PROGRAM

#include<stdio.h>
#include<string.h> void main()
{
int i=0,j=0,n,pos; char
a[20],b[50],ch;
printf("Enter the Characters: ");
scanf("%s",&a); printf("\nOrginal Data:%s",a);
n=strlen(a);
b[0]='d';
b[1]='l';
b[2]='e';
b[3]='s';
b[4]='t';
b[5]='x'; j=6;
while(i<n)
{

if( a[i]=='d' && a[i+1]=='l' && a[i+2]=='e')


{
b[j]='d';
b[j+1]='l';
b[j+2]='e';
j=j+3;

Page 3
}
b[j]=a[i];
i++;
j++;
}
b[j]='d';
b[j+1]='l';
b[j+2]='e';
b[j+3]='e';
b[j+4]='t';
b[j+5]='x';
b[j+6]='\0';
printf("\nTransmitted Data: %s\n",b); printf("Received Data:
%s",a);
}

Page 4
Output-1:
Enter the Characters: abcdefabcd Orginal Data:
abcdefabcd
Transmitted Data: dlestxabcdefabcddleetx Received Data:
abcdefabcd

Output-2:

Enter the Characters: abcdabcde Orginal Data:


abcdabcde
Transmitted Data: dlestxabcdabcdedleetx Received Data:
abcdabcde

Result:

Thus the implementation of Bit stuff and character stuff are verified in this C
programme.

Page 5
1. Write a program for distance vector algorithm to find
suitable path for transmission.
Aim:
Thus the Distance vector algorithm to find path for
transmission.
Apparatus Required:
Turbo C
Theory:
A distance-vector routing protocol is one of the foremost
instructions of routing protocols in pc conversation principle for packet-
switched networks. The hyperlink-nation protocol is the alternative foremost
class. The Bellman-Ford set of rules is applied in a distance-vector routing
protocol to calculate paths.
A distance-vector routing protocol calls for that a router
notify its buddies on every occasion a community's topology adjustments or,
in a few cases, on every occasion a alternate is detected. Distance-vector
routing protocols have much less message overhead and computational
complexity than hyperlink-nation protocols, which require a router to inform
all community nodes of adjustments to the topology.
Routers are marketed as "vectors of distance and route"
through Distance Vector. Direction is represented through the deal with of the
following hop and the go out interface, while Distance is represented through
metrics like hop count.IGRP, the Routing Information Protocol Versions 1
and a pair of, and the Routing Information Protocol Versions 1 and a pair of
are all distance-vector routing protocols. Since a distance-vector protocol
most effective takes under consideration hyperlink charges whilst calculating
routes, EGP and BGP aren't natural distance-vector routing protocols, while in
BGP, for instance, the neighborhood direction choice fee takes priority over
the hyperlink cost.
Algorithm:
 Algorithms Used in Distance Vector Routing .The Bellman-Ford
algorithm serves as the basis for distance vector routing
 This algorithm requires each node in the network to maintain a
distance vector table that stores the distance between itself and its
immediate neighbors in the link.

Page 6
 This algorithm can then be used to draw the following conclusions
about the network's routing algorithm:
 A routing table is used to share distance vectors between adjacent nodes
The latest network distance vector values are shared by each routing table
The distance vector over the nearest node is updated each time data from the
routing table is shared across the network.
Procedure:

Step 1: send packet to router


Step 2: Computer send the first packet to the nearest router
Step 3: Router receives packet
Step 4: Routers forward packets
Step 5:Final router forwards message.

#include<stdio.h> struct
node
{
unsigned dist[20]; unsigned from[20];
} rt[10];
void main()
{
int costmat[20][20],source,desti; 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]; rt[i].from[j]=j;
}

do
{
count=0; for(i=0;i<nodes;i++)
for(j=0;j<nodes;j++) if(i!=j)
for(k=0;k<nodes;k++)
if(rt[i].dist[j]>rt[i].dist[k]+rt[k].dist[j])
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j]; rt[i].from[j]=rt[i].from[k];
count++;
}
}
while(count!=0); for(i=0;i<nodes;i++)

Page 7
{
printf("\n\n State Value 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");
}

Output:
Enter the number of nodes : 4 Enter the
cost matrix :
0 2 999 1
2052
999 5 0 6
1260
State Value For Router 1

node1 via 1 Distance 0


node2 via 2 Distance 2
node3 via 2 Distance 7
node4 via 4 Distance 1 State

Value For Router 2

node1 via 1 Distance 2


node2 via 2 Distance 0
node3 via 3 Distance 5
node4 via 4 Distance 2 State

Value For Router 3

node1 via 2 Distance 7


node2 via 2 Distance 5
node3 via 3 Distance 0
node4 via 4 Distance 6

State Value For Router 4 node1 via 1

Distance 1
node2 via 2 Distance 2
node3 via 3 Distance 6
node4 via 4 Distance 0

Result:
Thus the distance vector algorithm to find out the path for transmission is verified.

Page 8
2. Implement Dijkstra’s algorithm to compute the shortest
routing path.

Aim:

To study about the implement Dijkstra’s algorithm to compute


the shortest routing path.

Apparatus required:
Turbo c
Procedure:

 Create a short path to store verticals that come in


the way of the shortest path tree.
 Initialize all distance values as INFINITE
 And assign distance values as 0 for source vertex
so that it is picked first.
 Loop until all verticals of the graph are in the
short path.

#include<stdio.h> #define
INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode); int main()


{
int G[MAX][MAX],i,j,n,u; printf("Enter no. of
vertices:"); scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n"); for(i=0;i<n;i++)
for(j=0;j<n;j++) scanf("%d",&G[i][j]); printf("\
nEnter the starting node:"); scanf("%d",&u);
dijkstra(G,n,u); return 0;
}

void dijkstra(int G[MAX][MAX],int n,int startnode)


{

int cost[MAX][MAX],distance[MAX],pred[MAX]; int


visited[MAX],count,mindistance,nextnode,i,j;
//pred[] stores the predecessor of each node
//count gives the number of nodes seen so far

Page 9
//create the cost matrix
for(i=0;i<n;i++) for(j=0;j<n;j++)
if(G[i][j]==0) cost[i]
[j]=INFINITY; else
cost[i][j]=G[i][j];
//initialize pred[],distance[] and visited[] for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i]; pred[i]=startnode;

Page
10
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1; count=1;
while(count<n-1)
{
mindistance=INFINITY;
//nextnode gives the node at minimum distance for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i]; nextnode=i;
}
//check if a better path exists through nextnode visited[nextnode]=1;
for(i=0;i<n;i++) if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i]; pred[i]=nextnode;
}
count++;
}

//print the path and distance of each node for(i=0;i<n;i++)


if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]); printf("\nPath=%d",i);
j=i; do
{
j=pred[j]; printf("<-%d",j);
}while(j!=startnode);
}
}

Page
11
Output:

Enter no. of vertices:5

Enter the adjacency matrix: 0 10 0 30


100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 10 60 0

Enter the starting node:0

Distance of node1=10 Path=1<-


0
Distance of node2=50 Path=2<-
3<-0
Distance of node3=30 Path=3<-
0
Distance of node4=60 Path=4<-
2<-3<-0

Result:
Thus the study about the implement Dijkstra’s algorithm
to compute the shortest routing path Verified.

1. Implementation of Stop and Wait Protocol and Sliding


Window Protocol
Aim:
Thus the implementation of stop and wait protocol and sliding
window proptocol.
Apparatus required:
Turbo C

5a. Stop and Wait Protocol

#include <stdio.h> int main()

Page
12
{
int i,f,frames[50];
printf("\n Enter number of frames to transmit: ");
scanf("%d",&f);
printf("\n Enter the %d frames: ",f);
for(i=1;i<=f;i++) scanf("%d",&frames[i]);

for(i=1;i<=f;i++)
{
if((random()%2)==1)
{
printf("%d\n",frames[i]);
printf("Acknowledgement of above frames sent is recived by sender\n\n");
}
else
{
sleep(3);
printf("negative acknowledgement resend %d frame\n",i); i=i-1;
sleep(1);
}
}
return 0;
}

Page
13
Output-1:

Enter number of frames to transmit: 6 Enter the 6 frames: 1

Acknowledgement of above frames sent is recived by sender negative acknowledgement resend 2


frame

Acknowledgement of above frames sent is recived by sender 5


Acknowledgement of above frames sent is recived by sender 7
Acknowledgement of above frames sent is recived by sender 8
Acknowledgement of above frames sent is recived by sender negative acknowledgement resend 6
frame
negative acknowledgement resend 6 frame 9
Acknowledgement of above frames sent is recived by sender

EXPT.NO 2.a NETWORK TOPOLOGY


DATE: BUS TOPOLOGY

AIM:
To create scenario and study the performance of token bus protocol through simulation.

HARDWARE / SOFTWARE REQUIREMENTS:

GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY


NS-2

THEORY:
Token bus is a LAN protocol operating in the MAC layer. Token bus is standardized as per IEEE 802.4. Token
bus can operate at speeds of 5Mbps, 10 Mbps and 20 Mbps. The operation of token bus is as follows: Unlike
token ring in token bus the ring topology is virtually created and maintained by the protocol. A node can receive
data even if it is not part of the virtual ring, a node joins the virtual ring only if it has data to transmit. In token
bus data is transmitted to the destination node only where as other control frames is hop to hop. After each data
transmission there is a solicit_successsor control frame transmitted which reduces the performance of the
protocol.

ALGORITHM:

1. Create a simulator object


2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam on trace
file.
4. Create five nodes that forms a network numbered from 0 to 4
5. Create duplex links between the nodes and add Orientation to the nodes for setting a LAN topology
6. Setup TCP Connection between n(1) and n(3)
7. Apply CBR Traffic over TCP.
8. Schedule events and run the program.

PROGRAM:

#Create 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
#Executenam on the trace
file exec nam out.nam &
exit 0
}
#Create five nodes
set n0[$nsnode] set n1 [$ns node]
set n2 [$ns node] set n3 [$ns node]
set n4 [$ns node]

#Create Lan between the nodes


set lan0 [$ns newLan "$n0 $n1 $n2 $n3 $n4" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd Channel]

#Create a TCP agent and attach it to node n0


set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $n1 $tcp0
#Create a TCP Sink agent (a traffic sink) for TCP and attach it to node n3
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
#Connect the traffic sources with the traffic sink
$ns connect $tcp0 $sink0

GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY


# Create a CBR traffic source and attach it to tcp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.01
$cbr0 attach-agent $tcp0

#Schedule events for the CBR agents


$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"

#Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Run the simulation


$ns run

OUTPUT:

RESULT:
Thus the Bus Topology was Simulated and studied.

GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY


EXPT.NO.2b NETWORK TOPOLOGY
DATE: RING TOPOLOGY

AIM:
To create scenario and study the performance of token ring protocols through simulation.

HARDWARE / SOFTWARE REQUIREMENTS:


NS-2

THEORY:
Token ring is a LAN protocol operating in the MAC layer. Token ring is standardized as per IEEE 802.5. Token
ring can operate at speeds of 4mbps and 16 mbps. The operation of token ring is as follows: When there is no
traffic on the network a simple 3-byte token circulates the ring. If the token is free (no reserved by a station of
higher priority as explained later) then the station may seize the token and start sending the data frame. As the
frame travels around the ring ach station examines the destination address and is either forwarded (if the
recipient is another node) or copied. After copying4 bits of the last byte is changed. This packet then continues
around the ring till it reaches the originating station. After the frame makes a round trip the sender receives the
frame and releases a new token onto the ring.

ALGORITHM:

1. Create a simulator object


2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam on trace
file.
4. Create five nodes that forms a network numbered from 0 to 4
5. Create duplex links between the nodes to form a Ring Topology.
6. Setup TCP Connection between n(1) and n(3)
7. Apply CBR Traffic over TCP
8. Schedule events and run the program.

PROGRAM:

#Create a 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
#Executenam on the trace
file exec nam out.nam &

GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY


exit0
}

#Create five nodes


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
#Create links between the nodes
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link $n4 $n5 1Mb 10ms DropTail
$ns duplex-link $n5 $n0 1Mb 10ms DropTail

#Create a TCP agent and attach it to node n0


set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $n1 $tcp0
#Create a TCP Sink agent (a traffic sink) for TCP and attach it to node n3
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
#Connect the traffic sources with the traffic sink
$ns connect $tcp0 $sink0

# Create a CBR traffic source and attach it to tcp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.01
$cbr0 attach-agent $tcp0

#Schedule events for the CBR agents


$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"

#Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Run the simulation


$ns run

OUTPUT:

GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY


RESULT:
Thus the Ring Topology was simulated and studied.

EXPT.NO.2.C
NETWORK TOPOLOGY
DATE: STAR TOPOLOGY
AIM:
To create scenario and study the performance of token ring protocols through simulation.

HARDWARE / SOFTWARE REQUIREMENTS:


NS-2

THEORY:
GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY
Star networks are one of the most common computer network topologies. In its simplest form, a star network
consists of one central switch, hub or computer, which acts as a conduit to transmit messages. This consists of a
central node, to which all other nodes are connected; this central node provides a common connection point for
all nodes through a hub. In star topology, every node (computer workstation or any other peripheral) is
connected to a central node called a hub or switch. The switch is the server and the peripherals are the clients.
Thus, the hub and leaf nodes, and the transmission lines between them, form a graph with the topology of a star.
If the central node is passive, the originating node must be able to tolerate the reception of an echo of its own
transmission, delayed by the two-way transmission time (i.e. to and from the central node) plus any delay
generated in the central node. An active star network has an active central node that usually has the means to
prevent echo-related problems.

The star topology reduces the damage caused by line failure by connecting all of the systems to a central node.
When applied to a bus-based network, this central hub rebroadcasts all transmissions received from any
peripheral node to all peripheral nodes on the network, sometimes including the originating node. All peripheral
nodes may thus communicate with all others by transmitting to, and receiving from, the central node only. The
failure of a transmission line linking any peripheral node to the central node will result in the isolation of that
peripheral node from all others, but the rest of the systems will be unaffected.

ALGORITHM:

1. Create a simulator object


2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam on trace
file.
4. Create six nodes that forms a network numbered from 0 to 5
5. Create duplex links between the nodes to form a STAR Topology
6. Setup TCP Connection between n(1) and n(3)
7. Apply CBR Traffic over TCP
8. Schedule events and run the program.

PROGRAM:

#Create a 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
#Executenam on the trace file exec nam
out.nam &
exit0

#Create six nodes set n0 [$ns


node] set n1 [$ns node] set n2
[$ns node] set n3 [$ns node]
GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY
set n4 [$ns node] set n5 [$ns
node]

#Change the shape of center node in a star topology


$n0 shape square
#Create links between the nodes
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n0 $n3 1Mb 10ms DropTail
$ns duplex-link $n0 $n4 1Mb 10ms DropTail
$ns duplex-link $n0 $n5 1Mb 10ms DropTail

#Create a TCP agent and attach it to node n0


set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $n1 $tcp0
#Create a TCP Sink agent (a traffic sink) for TCP and attach it to node n3
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
#Connect the traffic sources with the traffic sink
$ns connect $tcp0 $sink0
# Create a CBR traffic source and attach it to tcp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.01
$cbr0 attach-agent $tcp0
#Schedule events for the CBR agents
$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish" #Run the simulation
$ns run

OUTPUT:

GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY


RESULT:
Thus the star Topology was simulated and studied.

EXPT.NO.7 DATA ENCRYPTION AND DECRYPTION


DATE:

AIM:
To implement Data encryption and decryption

SOFTWARE REQUIREMENTS:
Turbo C software

THEORY:
In encryption, each letter position in the file text which is given in encrypt mode is changed according to the
ascending order of the key text. In decryption each letter position in the encrypted file text is changed
according to the ascending order of the key text.

ALGORITHM-ENCRYPTION
Get the text to be encrypted (plain text) and key text.
a. Find the length of the plain text.
b. For i=1 to length of plain text
c. Find the binary equivalent of ith character of plain text.
d. Find the binary equivalent of ith character of key text
e. Find the XOR of above two values.
The resulting value will be the encrypted format (cipher text) of the plain text.

ALGORITHM-DECRYPTION
Get the text to be decrypted (cipher text) and key text.
Find the length of the cipher text.
For i=1 to length of cipher text
a. Find the binary equivalent of ith character of cipher text.
b. Find the binary equivalent of ith character of key text
c. Find the XOR of above two values.
The resulting value will be the decrypted format (original plain text) of the cipher plain text.

PROGRAM
# include <stdio.h>
#include<conio.h>
void main ( )
{ static int s, i, k,n,c[100];
printf(“\n program 1: encryption and 2. decryption”);
scanf (“%d”, &s);
switch (s)
{ case 1: printf(“enter the key value:”);
scanf(“%d”, &k);
printf(“enter the length of text:”);
scanf(“%d”, &n);
printf(“enter the data to be encrypted:”);
for (i=0;i<=n;i++)
GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY
scanf(“%c”, &c[i]);
for (i=0;i<=n;i++)
{c[i]=c[i]+k;
if (c[i]>90)
c[i]=c[i]-26;}
printf(“encrypted data”);
for (i=1;i<=n;i++)
printf(“%c”, c[i]);
break;
case 2: printf(“enter the key value:”);
scanf(“%d”, &k);

printf(“enter the length of text:”);


scanf(“%d”, &n);
printf(“enter the data to be decrypted:”);
for (i=0;i<=n;i++)
scanf(“%c”, &c[i]);
for (i=0;i<=n;i++)
{c[i]=c[i]-k;
if (c[i]<65)
c[i]=c[i]+26;}
printf(“decrypted data”);
for (i=1;i<=n;i++)
printf(“%c”, c[i]);
break;
case 3: break;
getch ();
}
}

OUTPUT:

Program 1: encryption and 2. decryption

1. ENCRYPTION
enter the key value: 1
enter the length of text: 5
enter the data to be encrypted: HELLO
encrypted data : IFMMP

2. DECRYPTION
enter the key value: 1
enter the length of text: 5
enter the data to be decrypted: IFMMP
decrypted data : HELLO

RESULT:
Thus the Data Encryption and Decryption was studied.

EXPT.NO.8 IMPLEMENTATION OF ERROR DETECTION AND ERROR CORRECTION


DATE: TECHNIQUES

AIM:
To implement error detection and error correction techniques.
GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY
SOFTWARE REQUIREMENTS:
Turbo C

THEORY:
The upper layers work on some generalized view of network architecture and are not aware of actual hardware
data processing. Hence, the upper layers expect error-free transmission between the systems. Most of the
applications would not function expectedly if they receive erroneous data. Applications such as voice and
video may not be that affected and with some errors they may still function well. Data-link layer uses some
error control mechanism to ensure that frames (data bit streams) are transmitted with certain level of accuracy.
But to understand how errors is controlled, it is essential to know what types of errors may occur. CRC is a
different approach to detect if the received frame contains valid data. This technique involves binary division
of the data bits being sent. The divisor is generated using polynomials. The sender performs a division
operation on the bits being sent and calculates the remainder. Before sending the actual bits, the sender adds
the remainder at the end of the actual bits. Actual data bits plus the remainder is called a codeword. The sender
transmits data bits as codewords.

ALGORITHM:

1. Open Turbo c++ software and type the program for error detection
2. Get the input in the form of bits.
3. Append 16 zeros as redundancy bits.
4. Divide the appended data using a divisor polynomial.
5. The resulting data should be transmitted to the receiver.
6. At the receiver the received data is entered.
7. The same process is repeated at the receiver.
8. If the remainder is zero there is no error otherwise there is some error in the received bits
9. Run the program.

C PROGRAM
#include<stdio.h>
char m[50],g[50],r[50],q[50],temp[50];
void caltrans(int);
void crc(int);
void calram();
void shiftl();
int main()
{
int n,i=0;
char ch,flag=0;
printf("Enter the frame bits:");
while((ch=getc(stdin))!='\n')
m[i++]=ch;
n=i;
for(i=0;i<16;i++)
m[n++]='0';
m[n]='\0';
printf("Message after appending 16 zeros:%s",m);
for(i=0;i<=16;i++)
g[i]='0';
g[0]=g[4]=g[11]=g[16]='1';g[17]='\0';
printf("\ngenerator:%s\n",g);
crc(n);

printf("\n\nquotient:%s",q);
caltrans(n);
printf("\ntransmitted frame:%s",m);
GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY
printf("\nEnter transmitted frame:");
scanf("\n%s",m);
printf("CRC checking\n");
crc(n);
printf("\n\nlast remainder:%s",r);
for(i=0;i<16;i++)
if(r[i]!='0')
flag=1;
else
continue;
if(flag==1)
printf("Error during transmission");
else
printf("\n\nReceived freme is correct");
}
void crc(int n)
{
int i,j;
for(i=0;i<n;i++)
temp[i]=m[i];
for(i=0;i<16;i++)
r[i]=m[i];
printf("\nintermediate remainder\n");
for(i=0;i<n-16;i++)
{ if(r[0]=='
1')
{ q[i]='
1';
calram();
}
else
{ q[i]='
0';
shiftl();
}
r[16]=m[17+i];
r[17]='\0';
printf("\nremainder %d:%s",i+1,r);
for(j=0;j<=17;j++)
temp[j]=r[j];
}
q[n-16]='\0';
}
void calram()
{
int i,j;
for(i=1;i<=16;i++)
r[i-1]=((int)temp[i]-48)^((int)g[i]-48)+48;
}
void shiftl()
{
int i;
for(i=1;i<=16;i++)
r[i-1]=r[i];
}
void caltrans(int n)

{
int i,k=0;
GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY
for(i=n-16;i<n;i++)
m[i]=((int)m[i]-48)^((int)r[k++]-48)+48;
m[i]='\0';
}

OUTPUT:

Enter the Frame Bits:


1011
The msg after appending 16 zeros:
10110000000000000000
The Transmitted frame is:10111011000101101011
Enter the transmitted Frame
10111011000101101011
Received msg:10111011000101101011
The Remainder is:0000000000000000
Received frame is correct.

RESULT:
Thus the error detection and error correction is implemented successfully

EXPT.NO: 9
DATE: PERFORMANCE ANALYSIS OF CSMA/CA AND CSMA/CD PROTOCOLS

AIM:
To create scenario and study the performance of CSMA / CD protocol through simulation.

SOFTWARE REQUIREMENTS:
Ns-2

GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY


THEORY:
Ethernet is a LAN (Local area Network) protocol operating at the MAC (Medium Access Control) layer.
Ethernet has been standardized as per IEEE 802.3. The underlying protocol in Ethernet is known as the CSMA /
CD – Carrier Sense Multiple Access / Collision Detection. The working of the Ethernet protocol is as explained
below, A node which has data to transmit senses the channel. If the channel is idle then, the data is transmitted.
If the channel is busy then, the station defers transmission until the channel is sensed to be idle and then
immediately transmitted. If more than one node starts data transmission at the same time, the data collides. This
collision is heard by the transmitting nodes which enter into contention phase. The contending nodes resolve
contention using an algorithm called Truncated binary exponential back off.

ALGORITHM:

1. Create a simulator object


2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam on trace
file.
4. Create six nodes that forms a network numbered from 0 to 5
5. Create duplex links between the nodes and add Orientation to the nodes for setting a LAN topology
6. Setup TCP Connection between n(0) and n(4)
7. Apply FTP Traffic over TCP
8. Setup UDP Connection between n(1) and n(5)
9. Apply CBR Traffic over UDP.
10. Apply CSMA/CA and CSMA/CD mechanisms and study their performance
11. Schedule events and run the program.

PROGRAM:

CSMA/CA

set ns [new Simulator]


#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the Trace files
set file1 [open out.tr w]
set winfile [open WinFile w]
$ns trace-all $file1
#Open the NAM trace file
set file2 [open out.nam w]
$ns namtrace-all $file2
#Define a 'finish' procedure
proc finish {} {
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec nam out.nam &
exit 0

GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY


}
#Create six nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$n1 color red
$n1 shape box
#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Ca Channel]
Setup a TCP connection
set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
$tcp set window_ 8000
$tcp set packetSize_ 552
#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 $n5 $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_ 0.01mb
$cbr set random_ false
$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 124.0 "$ftp stop"
$ns at 124.5 "$cbr stop"
# next procedure gets two arguments: the name of the
# tcp source node, will be called here "tcp",
# and the name of output file.
proc plotWindow {tcpSource file} {
global ns
set time 0.1
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
set wnd [$tcpSource set window_]
puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file" }
$ns at 0.1 "plotWindow $tcp $winfile"

GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY


$ns at 5 "$ns trace-annotate \"packet drop\""
# PPP
$ns at 125.0 "finish"
$ns run

OUTPUT:

CSMA/CD

set ns [new Simulator]


#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the Trace files
set file1 [open out.tr w]
set winfile [open WinFile w]
$ns trace-all $file1
#Open the NAM trace file
set file2 [open out.nam w]
$ns namtrace-all $file2
#Define a 'finish' procedure
proc finish {} {
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec nam out.nam &
exit 0
}
#Create six nodes
set n0 [$ns node]
set n1 [$ns node]
GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$n1 color red
$n1 shape box

GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY


#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd Channel]
Setup a TCP connection
set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
$tcp set window_ 8000
$tcp set packetSize_ 552
#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 $n5 $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_ 0.01mb
$cbr set random_ false
$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 124.0 "$ftp stop"
$ns at 124.5 "$cbr stop"
# next procedure gets two arguments: the name of the
# tcp source node, will be called here "tcp",
# and the name of output file.
proc plotWindow {tcpSource file} {
global ns
set time 0.1
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
set wnd [$tcpSource set window_]
puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file" }
$ns at 0.1 "plotWindow $tcp $winfile"
$ns at 5 "$ns trace-annotate \"packet drop\""
# PPP
$ns at 125.0 "finish"
$ns run

GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY


OUTPUT:

RESULT:

Thus, the performance of CSMA / CD protocol was studied through simulation.

GRT INSTITUTE OF ENGINEERING AND TECHNOLOGY


IMPLEMENT Client Server model using FTP protocol

AIM:
To write a program for FTP client server.

ALGORITHM:
SERVER:
STEP 1: Start
STEP 2: Declare the variables for the socket
STEP 3: Specify the family, protocol, IP address and port number
STEP 4: Create a socket using socket() function
STEP 5: Bind the IP address and Port number
STEP 6: Listen and accept the client’s request for the connection
STEP 7: Establish the connection with the client
STEP 8: Close the socket
STEP 9: Stop
CLIENT:
STEP 1: Start
STEP 2: Declare the variables for the socket
STEP 3: Specify the family, protocol, IP address and port number
STEP 4: Create a socket using socket() function
STEP 5: Call the connect() function
STEP 6: Close the socket
STEP 7: Stop

SOURCE CODE:
SERVER:
#include<stdio.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#define SERV_TCP_PORT 5035
#define MAX 60
int i, j, tem;
char buff[4096], t;
FILE *f1;
int main(int afg, char *argv)
{
int sockfd, newsockfd, clength;
struct sockaddr_in serv_addr,cli_addr;
char t[MAX], str[MAX];
strcpy(t,"exit");
sockfd=socket(AF_INET, SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=INADDR_ANY;
serv_addr.sin_port=htons(SERV_TCP_PORT);
printf("\nBinded");
bind(sockfd,(struct sockaddr*)&serv_addr, sizeof(serv_addr));
printf("\nListening...");
listen(sockfd, 5);
clength=sizeof(cli_addr);
newsockfd=accept(sockfd,(struct sockaddr*) &cli_addr,&clength);
close(sockfd);
read(newsockfd, &str, MAX);

COMPUTER NETWORKS MANUAL


printf("\nClient message\n File Name : %s\n", str);
f1=fopen(str, "r");
while(fgets(buff, 4096, f1)!=NULL)
{
write(newsockfd, buff,MAX);
printf("\n");
}
fclose(f1);
printf("\nFile Transferred\n");
return 0;
}

CLIENT:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#define SERV_TCP_PORT 5035
#define MAX 60
int main(int arg,char*argv[])
{
int sockfd,n;
struct sockaddr_in serv_addr;
struct hostent*server;
char send[MAX],recvline[MAX],s[MAX],name[MAX];
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
serv_addr.sin_port=htons(SERV_TCP_PORT);
connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
printf("\nEnter the source file name : \n");
scanf("%s",send);
write(sockfd,send,MAX);
while((n=read(sockfd,recvline,MAX))!=0)
{
printf("%s",recvline);
}
close(sockfd);
return 0;
}

OUTPUT:
SERVER:

COMPUTER NETWORKS MANUAL


CLIENT:

COMPUTER NETWORKS MANUAL


RESULT:
Thus the program for FTP client server was executed and the output was verified

GO back-N protocols ans selective repeat protocols

Go back-N protocols:
#include<stdio.h>
int main()
{
int windowsize,sent=0,ack,i;
printf("enter window size\n");
scanf("%d",&windowsize);
while(1)
{
for( i = 0; i < windowsize; i++)
{
printf("Frame %d has been transmitted.\n",sent);
sent++;
if(sent == windowsize)
break;
}
printf("\nPlease enter the last Acknowledgement received.\n");
scanf("%d",&ack);

if(ack == windowsize)
break;
else
sent = ack;
}
return 0;
}
output:-

COMPUTER NETWORKS MANUAL


enter window size
8
Frame 0 has been transmitted.
Frame 1 has been transmitted.
Frame 2 has been transmitted.
Frame 3 has been transmitted.
Frame 4 has been transmitted.
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Frame 7 has been transmitted.

Please enter the last Acknowledgement received.


2
Frame 2 has been transmitted.
Frame 3 has been transmitted.
Frame 4 has been transmitted.
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Frame 7 has been transmitted.

Please enter the last Acknowledgement received.


8
--------------------------------

Selective repeat protocols:

Program

/* Program to demonstrate the working of ‘SELECTIVE REPEAT PROTOCOL’.


* This module acts as a client which establishes a connection with the server, sends the
windowsize, accepts the frames and then sends acknowledgement for each packet wihin
the given frame.
* The connection used is UDP and the window size is taken from the user(should be<=40)
* It uses two structures viz. ‘frame’ for accepting the frames send by the server and ‘ack’ for
sending the acknowledgement.
* Here the acknowledgement for each packet is accepted from the user. The user can enter -1
for negative acknowledgement or any other integer for positive acknowledgement.
* NOTE: This module can be compiled using the command ‘c++ selectiverepeat_server.cpp –
o b’ and executed using the command ‘./b’
-> Always compile and execute the server module first.
//inculsion.
#include<iostream>
#include<stdio.h>
#include<sys/types.h>
COMPUTER NETWORKS MANUAL
#include<netinet/in.h>
#include<netdb.h>

#define cls() printf(“33[H33[J”)


//structure definition for accepting the packets.
struct frame
{
int packet[40];
};
//structure definition for constructing the acknowledgement frame
struct ack
{
int acknowledge[40];
};

int main()
{
int clientsocket;
sockaddr_in serveraddr;
socklen_t len;
hostent * server;
frame f1;
int windowsize,totalpackets,totalframes,i=0,j=0,framesreceived=0,k,l,m,repacket[40];
ack acknowledgement;
char req[50];
clientsocket=socket(AF_INET,SOCK_DGRAM,0);
bzero((char*)&serveraddr,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(5018);
server=gethostbyname(“127.0.0.1”);
bcopy((char*)server->h_addr,(char*)&serveraddr.sin_addr.s_addr,sizeof(server->h_addr));
//establishing the connection.
printf(“\nSending request to the client.\n”);
sendto(clientsocket,”HI I AM CLIENT.”,sizeof(“HI I AM CLIENT.”),0,
(sockaddr*)&serveraddr,sizeof(serveraddr));
printf(“\nWaiting for reply.\n”);

COMPUTER NETWORKS MANUAL


recvfrom(clientsocket,req,sizeof(req),0,(sockaddr*)&serveraddr,&len);
printf(“\nThe server has send:\t%s\n”,req);
//accepting window size from the user.
printf(“\nEnter the window size:\t”);
scanf(“%d”,&windowsize);
//sending the window size.
printf(“\n\nSending the window size.\n”);
sendto(clientsocket,(char*)&windowsize,sizeof(windowsize),0,
(sockaddr*)&serveraddr,sizeof(serveraddr));
cls();
//collecting details from server.
printf(“\nWaiting for the server response.\n”);
recvfrom(clientsocket,(char*)&totalpackets,sizeof(totalpackets),0,(sockaddr*)&serveraddr,&len);
printf(“\nThe total packets are:\t%d\n”,totalpackets);
sendto(clientsocket,”RECEIVED.”,sizeof(“RECEIVED.”),0,
(sockaddr*)&serveraddr,sizeof(serveraddr));
recvfrom(clientsocket,(char*)&totalframes,sizeof(totalframes),0,(sockaddr*)&serveraddr,&len);
printf(“\nThe total frames/windows are:\t%d\n”,totalframes);
sendto(clientsocket,”RECEIVED.”,sizeof(“RECEIVED.”),0,
(sockaddr*)&serveraddr,sizeof(serveraddr));
//starting the process.
printf(“\nStarting the process of receiving.\n”);
j=0;
l=0;
while(l<totalpackets)
{ //initialising the receive buffer.
printf(“\nInitialising the receive buffer.\n”);
printf(“\nThe expected frame is %d with packets: “,framesreceived);
for(m=0;m<j;m++)
{ //readjusting for packets with negative acknowledgement.
printf(“%d “,repacket[m]);
}
while(j<windowsize && i<totalpackets)
{
printf(“%d “,i);
i++;

COMPUTER NETWORKS MANUAL


j++;
}

printf(“\n\nWaiting for the frame.\n”);


//accepting the frame.
recvfrom(clientsocket,(char*)&f1,sizeof(f1),0,(sockaddr*)&serveraddr,&len);
printf(“\nReceived frame %d\n\nEnter -1 to send negative acknowledgement for the following
packets.\n”,framesreceived);
//constructing the acknowledgement frame.
j=0;
m=0;
k=l;
while(m<windowsize && k<totalpackets)
{
printf(“\nPacket: %d\n”,f1.packet[m]);
//accepting acknowledgement from the user.
scanf(“%d”,&acknowledgement.acknowledge[m]);
if(acknowledgement.acknowledge[m]==-1)
{
repacket[j]=f1.packet[m];
j++;
}
else
{
l++;
}
m++;
k++;
}
framesreceived++;
//sending acknowledgement to the server.
sendto(clientsocket,(char*)&acknowledgement,sizeof(acknowledgement),0,
(sockaddr*)&serveraddr,sizeof(serveraddr));
cls();
}
printf(“\nAll frames received successfully.\n\nClosing connection with the server.\n”);

COMPUTER NETWORKS MANUAL


close(clientsocket);
}

OUTPUT:

COMPUTER NETWORKS MANUAL

You might also like