CN Lab Manual
CN Lab Manual
Experiments
NO
1 Implement three nodes point – to – point network with duplex links between them. Set the queue size, vary the
bandwidth and find the number of packets dropped.[B1]
2
Implement the data link layer framing methods such as character, character-stuffing and bit stuffing.
3
Write a program to compute CRC code for the polynomials CRC-12, CRC-16 and CRC CCIP
4 Develop a simple data link layer that performs the flow control using the sliding window protocol, and loss
recovery using the Go-Back-N mechanism.
5 Implement Dijsktra’s algorithm to compute the shortest path through a network
6
Implement data encryption and data decryption
7 Simulate the network with five nodes n0, n1, n2, n3, n4, forming a star topology. The node n4 is at the centre.
Node n0 is a TCP source, which transmits packets to node n3 (a TCP sink) through the node n4. Node n1 is
another traffic source, and sends UDP packets to node n2 through n4. The duration of the simulation time is 10
seconds.[B2]
8 Simulate to study transmission of packets over Ethernet LAN and determine the number of packets drop
destination.[B3]
Demonstration Experiments ( For CIE ) if any
9 Simulate the different types of internet traffic such as FTP and TELNET over a wired network and analyze the
packet drop and packet delivery ratio in the network.[B4]
Introduction to NS-2:
● Simulation of wired as well as wireless network functions and protocols (e.g., routing
● In general, NS2 provides users with a way of specifying such network protocols and
Tcl scripting
• Tcl is a general purpose scripting language. [Interpreter]
• Tcl runs on most of the platforms such as Unix, Windows, and Mac.
• The strength of Tcl is its simplicity.
• It is not necessary to declare a data type for variable prior to the usage.
Basics of TCL
Syntax: command arg1 arg2 arg3
⚪ Hello World!
expr 7.2 / 4
⚪ Procedures
proc Diag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
return $c }
puts “Diagonal of a 3, 4 right triangle is [Diag 3 4]”
Output: Diagonal of a 3, 4 right triangle is 5.0
⚪ Loops
In order to have output files with data on the simulation (trace files) or files used for
visualization (nam files), we need to create the files using “open” command:
#Open the Trace file
#Open the NAM trace file
The above creates a dta trace file called “out.tr” and a nam visualization trace file called
“out.nam”.Within the tcl script,these files are not called explicitly by their names,but instead by
pointers that are declared above and called “tracefile1” and “namfile” respectively.Remark that
they begins with a # symbol.The second line open the file “out.tr” to be used for writing,declared
with the letter “w”.The third line uses a simulator method called trace-all that have as parameter
the name of the file where the traces will go.
The last line tells the simulator to record all 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.In
our case,this will be the file pointed at by the pointer “$namfile”,i.e the file “out.tr”.
The termination of the program is done using a “finish” procedure.
#Define a ‘finish’ procedure
The word proc declares a procedure in this case called finish and without arguments. The
word global is used to tell that we are using variables declared outside the procedure. The
simulator method “flush-trace” will dump the traces on the respective files. The tcl command
“close” closes the trace files defined before and exec executes the nam program for visualization.
The command exit will ends the application and return the number 0 as status to the system. Zero
is the default for a clean exit. Other values can be used to say that is a exit because something
fails.
At the end of ns program we should call the procedure “finish” and specify at what time
the termination should occur. For example,
will be used to call “finish” at time 125sec.Indeed,the at method of the simulator allows us to
schedule events explicitly.
The simulation can then begin using the command
The node is created which is printed by the variable n0. When we shall refer to that node in the
script we shall thus write $n0.
Once we define several nodes, we can define the links that connect them. An example of
a definition of a link is:
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of
propagation delay and a capacity of 10Mb per sec for each direction.
To define a directional link instead of a bi-directional one, we should replace “duplex-
link” by “simplex-link”.
In NS, an output queue of a node is implemented as a part of each link whose input is that
node. The definition of the link then includes the way to handle overflow at that queue. In our
case, if the buffer capacity of the output queue is exceeded then the last packet to arrive is
dropped. Many alternative options exist, such as the RED (Random Early Discard) mechanism,
the FQ (Fair Queuing), the DRR (Deficit Round Robin), the stochastic Fair Queuing (SFQ) and
the CBQ (which including a priority and a round-robin scheduler).
Dept of ISE, CIT, Gubbi
In ns, an output queue of a node is implemented as a part of each link whose input is that
node. We should also define the buffer capacity of the queue related to each link. An example
would be:
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command
Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.
#Setup a UDP connection
#setup a CBR over UDP connection
The below shows the definition of a CBR application using a UDP agent
The command $ns attach-agent $n4 $sink defines the destination node. The command
$ns connect $tcp $sink finally makes the TCP connection between the source and destination
nodes.
TCP has many parameters with initial fixed defaults values that can be changed if mentioned
explicitly. For example, the default TCP packet size has a size of 1000bytes.This can be changed
to another value, say 552bytes, using the command $tcp set packetSize_ 552.
When we have several flows, we may wish to distinguish them so that we can identify
them with different colors in the visualization part. This is done by the command $tcp set fid_ 1
that assigns to the TCP connection a flow identification of “1”.We shall later give the flow
identification of “2” to the UDP connection.
The scheduler is started when running ns that is through the command $ns run.
The beginning and end of the FTP and CBR application can be done through the following
command
1. The first field is the event type. It is given by one of four possible symbols r, +, -, d which
correspond respectively to receive (at the output of the link), enqueued, dequeued and
dropped.
2. The second field gives the time at which the event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (eg CBR or TCP)
6. Gives the packet size
7. Some flags
8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script one
can further use this field for analysis purposes; it is also used when specifying stream color
for the NAM display.
9. This is the source address given in the form of “node.port”.
10. This is the destination address, given in the same form.
11. This is the network layer protocol’s packet sequence number. Even though UDP
implementations in a real network do not use sequence number, ns keeps track of UDP
packet sequence number for analysis purposes
12. The last field shows the Unique id of the packet.
awk is a programmable, pattern-matching, and processing tool available in UNIX. It
works equally well with text and numbers.
awk is not just a command, but a programming language too. In other words, awk utility
is a pattern scanning and processing language. It searches one or more files to see if they contain
lines that match specified patterns and then perform associated actions, such as writing the line to
the standard output or incrementing a counter each time it finds a match.
Syntax:
Here, selection_criteria filters input and select lines for the action component to act upon.
The selection_criteria is enclosed within single quotes and the action within the curly braces.
Both the selection_criteria and action forms an awk program.
Example: $ awk ‘/manager/ {print}’ emp.lst
Variables
Awk allows the user to use variables of there choice. You can now print a serial number,
using the variable kount, and apply it those directors drawing a salary exceeding 6700:
$ awk –F”|” ‘$3 == “director” && $6 > 6700 {
kount =kount+1
printf “ %3f %20s %-12s %d\n”, kount,$2,$3,$6 }’ empn.lst
THE –f OPTION: STORING awk PROGRAMS IN A FILE
You should holds large awk programs in separate file and provide them with the awk
extension for easier identification. Let’s first store the previous program in the file empawk.awk:
$ cat empawk.awk
Observe that this time we haven’t used quotes to enclose the awk program. You can now
use awk with the –f filename option to obtain the same output:
Q1. Implement three nodes point – to – point network with duplex links between them. Set the queue size, vary
the bandwidth and find the number of packets dropped.
1.tcl
set ns [new Simulator]
set nf [open /home/mca/sandhya/1.nam w]
$ns namtrace-all $nf
set tf [open /home/mca/sandhya/1.tr w]
$ns trace-all $tf
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam 1.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
# Letter S is capital
# open a nam trace file in write mode
# nf nam filename
# tf trace filename
# clears trace file contents
# # creates 3 nodes
$ns duplex-link $n0 $n1 200Mb 10ms DropTail # establishing links
$ns duplex-link $n1 $n2 100Kb 1000ms DropTail
$ns queue-limit $n0 $n1 10
set udp [new Agent/UDP]
$ns attach-agent $n0 $udp
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set packet_size_ 500
# attaching transport layer protocols
set null [new Agent/Null]
$ns attach-agent $n2 $null
$ns connect $udp $null
# creating sink(destination) node
# attaching application layer protocols
$ns at 0.1 “$cbr start”;
$ns at 1.0 “finish”;
$ns run
Output :
ns 1.tcl
1.awk
#awk file run in newterminal
BEGIN{
c=0;
}
{
if($1=="d")
{
c++;
printf("%s\t%s\n",$5,$11);
}
} END{
printf("The number of packets dropped =%d\n",c);
}
Implement the data link layer framing methods such as character, character-stuffing and
bit stuffing.
#include<stdio.h>
#include<string.h>
int main()
{
int a[20],b[30],i,j,k,count,n;
printf("Enter frame size (Example: 8):");
scanf("%d",&n);
printf("Enter the frame in the form of 0 and 1 :");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
i=0;
count=1;
j=0;
while(i<n)
{
if(a[i]==1)
{
b[j]=a[i];
for(k=i+1; a[k]==1 && k<n && count<5; k++)
{
j++;
b[j]=a[k];
count++;
if(count==5)
{
j++;
b[j]=0;
}
i=k;
}
}
else
{
b[j]=a[i];
}
i++;
j++;
}
printf("After Bit Stuffing :");
for(i=0; i<j; i++)
printf("%d",b[i]);
return 0;
}
int main()
{
char sdel[]="DELSTX",data[100]="",sdata[100]="";
int i=0,j=0;
printf("enter the message:");
scanf("%s",data);
// converting user input to uppercase
for(int k=0;data[k]!='\0';k++) {
if(data[k] >= 'a' && data[k] <= 'z'){
data[k] = data[k] - 32;
}
}
printf("original message: %s \n", data);
Experiment No 3
Q. Write a program to compute CRC code for the polynomials CRC-12, CRC-16 and CRC
CCIP.
Implement On A Data Set Of Characters The Three CRC Polynomials – CRC 12, CRC 16 And CRC CCIP.
Program Algorithm/Flowchart:
Begin
Step 1:Declare I, j , fr[8], dupfr[11], recfr[11], tlen, flag, gen[4], genl, frl, rem[4] as integer
Step 2: initialize frl=8 and genl=4
Step 3: initialize i=0
Step 4: Repeat step(5to7) until i<frl
Step 5: read fr[i]
Step 6: dupfr[i]=fr[i]
Step 7: increment i
Step 8: initialize i=0
Step 9: repeat step(10to11) until i<genl
Step 10: read gen[i]
Step 11: increment i
Step 12: tlen=frl+genl-1
Step 13: initialize i=frl
Step 14: Repeat step(15to16) until i<tlen
Step 15: dupfr[i]=0
Step 16: increment i
Step 17: call the function remainder(dupfr)
Step 18: initialize i=0
Step 19: repeat step(20 to 21) until j<genl
Step 20: recfr[i]=rem[j]
Step 21: increment I and j
Step 22: call the function remainder(dupfr)
Step 23: initialize flag=0 and i=0
Step 24: Repeat step(25to28) until i<4
Step 25: if rem[i]!=0 then
Step 26: increment flag
Step 27: end if
Step 28: increment i
Step 29: if flag=0 then
Step 25: print frame received correctly
Step 25: else
Step 25: print the received frame is wrong
End
Function: Remainder(int fr[])
Begin
Step 1: Declare k,k1,I,j as integer
Step 2: initialize k=0;
Step 3: repeat step(4 to 14) until k< frl
Step 4: if ((fr[k] == 1) then
Step 5: k1=k
Step 6: initialize i=0, j=k
Step 7: repeat step(8 to 9) until i< genl
Step 8: rem[i] =fr[j] exponential gen[i]
Step 9: increment I and j
Step 10: initialize I = 0
Step 11: repeat step(12to13) until I <genl
Step 12: fr[k1] = rem[i]
Step 13: increment k1 and i
Step 14: end if
End
Program Output:
Enter frame: MLRITM
Enter generator: frame received correctly
------------------
(program exited with code: 24)
Experiment No 4
Q. Develop a simple data link layer that performs the flow control using the sliding window protocol, and loss
recovery using the Go-Back-N mechanism.
#include<stdio.h>
int main()
{
int w,i,f,frames[50];
for(i=1;i<=f;i++)
scanf("%d",&frames[i]);
printf("\nWith sliding window protocol the frames will be sent in the following manner (assuming
no corruption of frames)\n\n");
printf("After sending %d frames at each stage sender waits for acknowledgement sent by the
receiver\n\n",w);
for(i=1;i<=f;i++)
{
if(i%w==0)
{
printf("%d\n",frames[i]);
printf("Acknowledgement of above frames sent is received by sender\n\n");
}
else
printf("%d ",frames[i]);
}
if(f%w!=0)
printf("\nAcknowledgement of above frames sent is received by sender\n");
return 0;
}
Output
Enter window size: 3
Enter 5 frames: 12 5 89 4 6
With sliding window protocol the frames will be sent in the following manner (assuming no corruption of
frames)
After sending 3 frames at each stage sender waits for acknowledgement sent by the receiver
12 5 89
46
Experiment No 5
Dijkstra’s Algorithm
1. Create cost matrix C[ ][ ] from adjacency matrix adj[ ][ ]. C[i][j] is the cost of going from
vertex i to vertex j. If there is no edge between vertices i and j then C[i][j] is infinity.
4. Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1 from the
source vertex 0.
for(i=1;i<n;i++)
distance[i]=cost[0][i];
Initially, distance of source vertex is taken as 0. i.e. distance[0]=0;
5. for(i=1;i<n;i++)
– Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark visited[w] as
1.
– Recalculate the shortest distance of remaining vertices from the source.
– Only, the vertices not marked as 1 in array visited[ ] should be considered for recalculation of
distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v],
distance[w]+cost[w][v])
Time Complexity
The program contains two nested loops each of which has a complexity of O(n). n is number of
vertices. So the complexity of algorithm is O(n2).
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;
}
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
//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;
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++;
}
OUTPUT:
mca@mca-OptiPlex-3090:~$ ./a.out
Enter no. of vertices:5
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
Experiment No 6
#include <stdio.h>
int main()
{
int i, x;
char str[100];
printf("\nPlease enter a string:\t");
gets(str);
printf("\nPlease choose following options:\n");
printf("1 = Encrypt the string.\n");
printf("2 = Decrypt the string.\n");
scanf("%d", &x);
//using switch case statements
switch(x)
{
case 1:
for(i = 0; (i < 100 && str[i] != '\0'); i++)
str[i] = str[i] + 3; //the key for encryption is 3 that is added to ASCII value
case 2:
for(i = 0; (i < 100 && str[i] != '\0'); i++)
str[i] = str[i] - 3; //the key for encryption is 3 that is subtracted to ASCII value
default:
printf("\nError\n");
}
return 0;
}
Output
#Encryption
#Decryption
Experiment No 7
Q .simulate the network with nodes n0,n1,n2,n3,n4, forming a star topology. The node n4 is at the
center. Node n0 is a TCP source, which transmits packets to node n3(a tcp sink) through the node n4,
node n1 is another traffic source, and sends UDP packets to node n2 through n4. The duration of the
simulation time is 10 seconds.
global ns nf
$ns flush-trace
close $nf
exit 0
$ns run
Output:
run ns 2b.tcl
2b.awk:-
BEGIN{
udp=0;
tcp=0;
udp++;
tcp++;
END{
output:-
Q. Simulate to study transmission of packets over Ethernet LAN and determine the
number of packets drop destination.
$ns make-lan "$n0 $n1 $n2 $n3 $n4" 1Mb 100ms LL Queue/DropTail Mac/802_3
proc finish { } {
global ns nftf
$ns flush-trace
close $tf
close $nf
exit 0
}
$ns at 16 "finish"
$ns run
OUTPUT :
3b.awk
BEGIN{
c=0;
if($1=="d")
{ c+
+;
}}
END{
Q .Simulate the different types of internet traffic such as FTP and TELNET over a wired
network and analyze the packet drop and packet delivery ratio in the network.
5.tcl
proc finish {}
{ global ns nfnd
$ns flush-trace
close $nf
close $nd
exit 0
$ns run
OUTPUT:
5b.awk
BEGIN{
ftpsend=0;
telnetsend=0;
ftpDrop=0;
telnetDrop=0;
telnetrecv=0;
ftprecv=0;
}
event=$1; src=$9;
dest=$10; pktype=$5;
ftpsend++;
ftprecv++;
telnetsend++;
telnetrecv++;
ftpDrop++;
}
if((event=="d") && (src=="1.0") && (dest=="3.0") &&pktype="tcp")
telnetDrop++;
END{
output:-
proc finish {} {
global ns nfnd
$ns flush-trace
close $nf
close $nd
exit 0
}
#Create six nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
#Create two ping agents and attach them to the nodes n0 and n2
#Schedule events
$ns run
OUTPUT
6b.awk
BEGIN{
drop=0;
if($1=="d")
drop++;
END{
}
output:-
mca@mca-HP-dx2480-MT-KL969AV:$ ns 6b.tcl
node 0received answer from 3 with round trip time 497.9 msec
node 3received answer from 0 with round trip time 736.7 msec
node 0received answer from 3 with round trip time 875.5 msec
node 3received answer from 0 with round trip time 895.7 msec
node 0received answer from 3 with round trip time 1253.1 msec
node 3received answer from 0 with round trip time 1273.3 msec
node 0received answer from 3 with round trip time 1691.9 msec