CN Lab Manual
CN Lab Manual
INSTITUTE
LAB MANUAL
( 2023–24 )
V Semester
21CS52 COMPUTER NETWORK LABORATORY
By,
Mrs. Chaitra Barki
Assistant Professor
TABLE OF CONTENTS
NS Programs
1. IntroductiontoNS2
2. X Graph
3. Awk and advanced
4. Three node point to point network
5. Transmission of Ping messages
6. Ethernet LAN using n-nodes with multiple traffic
7. Simple ESS with wireless LAN
Java Programs
8. CRC-CCITT
9. Bellman-Ford Algorithm
10. Congestion Control Using Leaky Bucket Algorithm
Viva-voice
References
Computer Network Laboratory [21CS52] 2023-24
Introduction to NS-2:
Widely known as NS2, is simply an event driven simulation tool.
Useful in studying the dynamic nature of communication networks.
Simulation of wired as well as wireless network functions and protocols (e.g.,
routing algorithms, TCP, UDP) can be done usingNS2.
In general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviors.
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!
puts std out{Hello,
World!} Hello, World!
Variables Command Substitution
seta5 set len [string lengthfoobar]
SimpleArithmetic
expr 7.2 / 4
Procedures
proc Diag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
return $c }
puts―Diagonalofa3,4righttriangleis[Diag34]‖ Output:
Diagonal of a 3, 4 right triangle is5.0
Loops
while{$i <$n}{ for {set i 0} {$i < $n} {incr i}{
... ...
} }
Wired TCL Script Components
Create the event scheduler
Open new files & turn on the tracing
Create the nodes
Setup the links
Configure the traffic type (e.g., TCP, UDP, etc)
Set the time of traffic generation (e.g., CBR, FTP)
Terminate the simulation
NS Simulator Preliminaries.
11. Initialization and termination aspects of the nssimulator.
12. Definition of network nodes, links, queues andtopology.
13. Definition of agents and ofapplications.
14. The nam visualizationtool.
15. Tracing and randomvariables.
Which is thus the first line in the tcl script? This line declares a new variable as using the set
it is an instance of the Simulator class, so an object the code[new Simulator] is indeed the
installation of the class Simulator using the reserved word new.
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
set tracefile1 [open out.tr w]
Theabovecreatesatracefilecalled―out.tr‖andanamvisualizationtracefilecalled
―out.nam‖. Within the tcl script, these files are not called explicitly by their names, but instead
bypointersthatare declaredaboveandcalled―tracefile1‖and―namfile‖respectively.
Remarkthattheybeginswitha#symbol.Thesecondlineopenthefile―out.tr‖ tobeusedfor
writing,declaredwiththeletter―w‖.Thethirdlineusesasimulatormethodcalledtrace-all that have
as parameter the name of the file where the traces willgo.
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‖.
Thetermination ofthe program isdoneusinga―finish‖ procedure.
#Define a „finish‟ procedure
Proc finish { } {
$ns flush-trace
Close $tracefile1
Close $namfile
Exit 0
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 traceson the respective files. The tcl
command―close”closesthetracefilesdefinedbeforeandexecexecutesthenamprogramfor
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 somethingfails.
At the end of ns program we should call the procedure ―finish‖ and specify at what
time the termination should occur. For example,
$ns at 125.0 “finish”
will be used to call ―finish‖ at time 125sec.Indeed,the at method of the simulator allowsus to
schedule events explicitly.
The simulation can then begin using the command
$ns run
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:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail
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.
Todefine adirectionallinkinsteadofabi-directionalone,we shouldreplace―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
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).
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:
#set Queue Size of link (n0-n2) to 20
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command
set sink [new Agent /TCPSink]
Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.
Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event should
occur. The initializing command set ns [new Simulator] creates an event scheduler, and
events are then scheduled using theformat:
$ns at <time><event>
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
$ns at 0.1 “$cbr start”
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 eventoccurs.
3. Gives the input node of the link at which the eventoccurs.
4. Gives the output node of the link at which the eventoccurs.
5. Gives the packet type (eg CBR orTCP)
6. Gives the packetsize
7. Someflags
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 NAMdisplay.
XGRAPH
The xgraph program draws a graph on an x-display given data read from either data
file or from standard input if no files are specified. It can display upto 64 independent data
sets using different colors and line styles for each set. It annotates the graph with a title, axis
labels, grid lines or tick marks, grid labels and a legend.
Syntax:
Xgraph [options] file-name
Awk- An Advanced
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
Part-A
ExperimentNo:1 Date:
THREE NODE POINT TO POINT NETWORK
Aim: 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.
proc finish { } {
global ns nf tf
$ns flush-trace # clears trace file contents
close $nf
close $tf
exec nam lab1.nam &
exit 0
}
set n0[$ns node] # creates 3nodes
set n2 [$ns node]
set n3 [$ns node]
AWK file:(Open a new editor using “vi command” and write awk file and save with “.awk”
extension)
#immediately after BEGIN should open braces „{„
BEGIN{ c=0;}
{
if($1= ="d")
{ c++;
printf("%s\t%s\n",$5,$11);
}
}
END{ printf("The number of packets dropped is %d\n",c); }
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab2.nam &
exit 0
}
$ns at 0.1 "$p1 send"
$ns at 0.2 "$p1 send"
$ns at 0.3 "$p1 send"
$ns at 0.4 "$p1 send"
$ns at 0.5 "$p1 send"
$ns at 0.6 "$p1 send"
$ns at 0.7 "$p1 send"
$ns at 0.8 "$p1 send"
$ns at 0.9 "$p1 send"
$ns at 1.0 "$p1 send"
AWK file:(Open a new editor using “gedit command” and write awk file and save with
“.awk” extension)
BEGIN{
drop=0;
Topology Output
Output
ExperimentNo:3 Date:
ETHERNET LAN USING N-NODES WITH MULTIPLE TRAFFIC
Aim: Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination
$ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/ DropTail Mac/802_3
$ns duplex-link $n4 $n5 1Mb 1ms DropTail
$tcp0 trace cwnd_ # must put underscore ( _ ) after cwnd and no space between them
$tcp2 trace cwnd_
proc finish { } {
global ns nf tf
$ns flush-trace
close $tf
close $nf
exec nam lab3.nam &
exit 0
}
$ns at 16 "finish"
$ns run
AWK file:(Open a new editor using “gedit command” and write awk file and save with
“.awk” extension)
BEGIN {
}
{
if($6=="cwnd_") #don‟tleavespaceafterwritingcwnd_
printf("%f\t%f\t\n",$1,$7); # you must put \n inprintf
}
END{
Topolgy:
Output:
ExperimentNo:4 Date:
SIMPLE ESS WITH WIRELESS LAN
Aim: Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and
determine the performance with respect to transmission of packets.
create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
$n0 set X_ 50
$n0 set Y_ 50
$n0 set Z_ 0
$n1 set X_ 100
$n1 set Y_ 100
$n1 set Z_ 0
$n2 set X_ 600
$n2 set Y_ 600
$n2 set Z_ 0
AWK file:(Open a new editor using “gedit command” and write awk file and save with
“.awk” extension)
BEGIN{
count1=0
count2=0
pack1=0
pack2=0
time1=0
time2=0
}
{
if($1= ="r"&& $3= ="_1_" && $4= ="AGT")
{
count1++
pack1=pack1+$8
time1=$2
}
if($1= ="r" && $3= ="_2_" && $4= ="AGT")
Department of CSE, BTI Page 25
Computer Network Laboratory [21CS52] 2023-24
{
count2++
pack2=pack2+$8
time2=$2
}
}
END{
printf("The Throughput from n0 to n1: %f Mbps \n‖, ((count1*pack1*8)/(time1*1000000)));
printf("The Throughput from n1 to n2: %f Mbps", ((count2*pack2*8)/(time2*1000000)));
}
ExperimentNo:1 Date:
Error Detecting Code Using CRC-CCITT (16-bit)
Aim: Write a Program for ERROR detecting code using CRC-CCITT (16bit).
Whenever digital data is stored or interfaced, data corruption might occur. Since the
beginning of computer science, developers have been thinking of ways to deal with this type
of problem. For serial data they came up with the solution to attach a parity bit to each sent
byte. This simple detection mechanism works if an odd number of bits in a byte changes, but
an even number of false bits in one byte will not be detected by the parity check. To
overcome this problem developers have searched for mathematical sound mechanisms to
detect multiple false bits. The CRC calculation or cyclic redundancy check was the result of
this. Nowadays CRC calculations are used in all types of communications. All packets sent
over a network connection are checked with a CRC. Also each data block on your hard disk
has a CRC value attached to it. Modern computer world cannot do without these CRC
calculations. So let's see why they are so widely used. The answer is simple; they are
powerful, detect many types of errors and are extremely fast to calculate especially when
dedicated hardware chips areused.
The idea behind CRC calculation is to look at the data as one large binary number.
This number is divided by a certain value and the remainder of the calculation is called the
CRC. Dividing in the CRC calculation at first looks to cost a lot of computing power, but it
can be performed very quickly if we use a method similar to the one learned at school. We
will as an example calculate the remainder for the character 'm'—which is 1101101 in binary
notation—by dividing it by 19 or 10011. Please note that 19 is an odd number. This is
necessary as we will see further on. Please refer to your schoolbooks as the binary calculation
method here is not very different from the decimal methodyou learned whenyou were
young. It might only look a little bit strange. Also notations differ between countries, but the
method is similar.
With decimal calculations you can quickly check that 109 divided by 19 gives a
quotient of 5 with 14 as the remainder. But what we also see in the scheme is that every bit
extra to check only costs one binary comparison and in 50% of the cases one binary
subtraction. You can easily increase the number of bits of the test data string—for example to
56 bits if we use our example value "Lammert"—and the result can be calculated with 56
binary comparisons and an average of 28 binary subtractions. This can be implemented in
hardware directly with only very few transistors involved. Also software algorithms can be
very efficient.
All of the CRC formulas you will encounter are simply checksum algorithms based
on modulo-2 binary division where we ignore carry bits and in effect the subtraction will be
equal to an exclusive or operation. Though some differences exist in the specifics across
different CRC formulas, the basic mathematical process is always thesame:
The message bits are appended with c zero bits; this augmented message is the
dividend
A predetermined c+1-bit binary sequence, called the generator polynomial, is the
divisor
The checksum is the c-bit remainder that results from the division operation
Table 1 lists some of the most commonly used generator polynomials for 16- and32-bit
CRCs. Remember that the width of the divisor is always one bit wider than the remainder.
So, for example, you’d use a 17-bit generator polynomial whenever a 16-bit checksum is
required.
Table 1: International Standard CRC Polynomials
CRC-CCITT CRC-16 CRC-32
Checksum
16 bits 16 bits 32 bits
Width
Generator
10001000000100001 11000000000000101 100000100110000010001110110110111
Polynomial
Error detection with CRC
Consider a message represented by the polynomial M(x)
802.3:
x32+x26+x23+x22 +x16+x12+x11+x10 +x8+x7+x5+x4+x2+x+1
o Used in: Ethernet, PPProotion
Source Code:
import java.util.*;
class crc
{ void div(int a[],intk)
{ intgp[]={1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1};
int count=0;
for(int i=0;i<k;i++)
{
if(a[i]==gp[0])
{
for(int j=i;j<17+i;j++)
{
a[j]=a[j]^gp[count++];
}
count=0;
}
}
}
public static void main(String args[])
{
int a[]=new int[100];
int b[]=new int[100];
int len,k;
crc ob=new crc();
System.out.println("Enter the length of Data Frame:");
Scanner sc=new Scanner(System.in);
len=sc.nextInt();
int flag=0;
System.out.println("Enter the Message:");
for(int i=0;i<len;i++)
{ a[i]=sc.nextInt();
}
for(int i=0;i<16;i++)
{ a[len++]=0;
}
k=len-16;
for(int i=0;i<len;i++)
{ b[i]=a[i];
}
ob.div(a,k);
for(int i=0;i<len;i++)
a[i]=a[i]^b[i];
System.out.println("Data to be transmitted: ");
for(int i=0;i<len;i++)
{
if(a[i]!=0)
{
flag=1;
break;
}
}
if(flag==1)
System.out.println("error in data");
else
System.out.println("no error");
}
}
Output:
Enter the length of Data Frame: 4
Enter the Message: 1 0 1 1
Data to be transmitted: 1 0 1 1 1 0 1 1 0 0 0 1 0 1 1 0 1 0 1 1
Enter the Reveived Data: 1 0 1 1 1 0 1 1 0 0 0 0 0 1 1 0 1 0 1 1
ERROR in Recived Data
**********************************************************
ExperimentNo:2 Date:
Bellman-ford Algorithm
Aim: Write a program to find the shortest path between vertices using bellman-ford
algorithm.
Distance Vector Algorithm is a decentralized routing algorithm that requires that each
router simply inform its neighbors of its routing table. For each network path, the receiving
routers pick the neighbor advertising the lowest cost, then add this entry into its routing table
for re-advertisement. To find the shortest path, Distance Vector Algorithm is based on one of
two basic algorithms: the Bellman-Ford and the Dijkstra algorithms.
Routers that use this algorithm have to maintain the distance tables (which is a one-
dimension array -- "a vector"), which tell the distances and shortest path to sending packets to
each node in the network. The information in the distance table is always upd by exchanging
information with the neighboring nodes. The number of data in the table equals to that of all
nodes in networks (excluded itself). The columns of table represent the directly attached
neighbors whereas the rows represent all destinations in the network. Each data contains the
path for sending packets to each destination in the network and distance/or time to transmit
on that path (we call this as "cost"). The measurements in this algorithm are the number of
hops, latency, the number of outgoing packets,etc.\
The Bellman–Ford algorithm is an algorithm that computes shortest paths from a single
source vertex to all of the other vertices in a weighted digraph. It is slower than Dijkstra's
algorithm for the same problem, but more versatile, as it is capable of handling graphs in which
some of the edge weights are negative numbers. Negative edge weights are found in various
applications of graphs, hence the usefulness of this algorithm. If a graph contains a "negative
cycle" (i.e. a cycle whose edges sum to a negative value) that is reachable from the source, then
there is no cheapest path: any path that has a point on the negative cycle can be made cheaper by
one more walk around the negative cycle. In such a case, the Bellman–Ford algorithm can detect
negative cycles and report their existence
Implementation Algorithm:
1. send my routing table to all my neighbors whenever my link tablechanges
2. when I get a routing table from a neighbor on port P with link metricM:
a. add L to each of the neighbor'smetrics
b. for each entry (D, P', M') in the updated neighbor'stable:
Source Code:
import java.util.Scanner;
public class BellmanFord
{ private int D[];
private intnum_ver;
public static final int MAX_VALUE = 999;
public BellmanFord(int n)
{ this.n=n;
D = new int[n+1];
}
public void shortest(int s,int A[][])
{ for (inti=1;i<=n;i++)
{ D[i]=MAX_VALUE;
} D[s] = 0;
for(int k=1;k<=n-1;k++)
{ for(inti=1;i<=n;i++)
{ for(intj=1;j<=n;j++)
{ if(A[i][j]!=MAX_VALUE)
{ if(D[j]>D[i]+A[i][j])
D[j]=D[i]+A[i][j];
}
}
}
}
for(int i=1;i<=n;i++)
{ for(intj=1;j<=n;j++)
{ if(A[i][j]!=MAX_VALUE)
{ if(D[j]>D[i]+A[i][j])
{
System.out.println("The Graph contains negative egde cycle");
return;
} }
}
}
for(int i=1;i<=n;i++)
{
System.out.println("Distance of source " + s + " to "+ i + " is " + D[i]);
}
}
public static void main(String[ ] args)
{ intn=0,s;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of vertices");
Implementation Algorithm:
Steps:
1. Read The Data ForPackets
2. Read The QueueSize
3. Divide the Data intoPackets
4. Assign the random Propagation delays for each packets to input into the bucket
(input_packet).
5. wlile((Clock++<5*total_packets)and
(out_packets<total_paclets))
a. if (clock ==input_packet)
i. insert intoQueue
b. if (clock % 5 == 0)
i. Remove paclet fromQueue
6. End
Source Code:
import java.util.*;
public class leaky
{
static int min(int x,int y)
{
if(x<y)
return x;
else
return y;
}
public static void main(String[] args)
{ int drop=0,mini,nsec,cap,count=0,i,process;
int inp[]=newint[25];
Scanner sc=new Scanner(System.in);
Output:
VIVA QUESTIONS
1. What are functions of differentlayers?
2. Differentiate between TCP/IP Layers and OSILayers
3. Why header isrequired?
4. What is the use of adding header and trailer toframes?
5. What isencapsulation?
6. Why fragmentationrequires?
7. What isMTU?
8. Which layer imposesMTU?
9. Differentiate between flow control and congestioncontrol.
10. Differentiate between Point-to-Point Connection and End-to-Endconnections.
11. What are protocols running in differentlayers?
12. What is ProtocolStack?
13. Differentiate between TCP andUDP.
14. Differentiate between Connectionless and connection orientedconnection.
15. Why frame sorting isrequired?
16. What is meant bysubnet?
17. What is meant byGateway?
18. What is an IP address?
19. What is MACaddress?
20. Why IP address is required when we have MACaddress?
21. What is meant byport?
22. What are ephemerical port number and well known portnumbers?
23. What is asocket?
24. What are the parameters ofsocket()?
25. Describe bind(), listen(), accept(),connect(), send() andrecv().
26. What are system calls? Mention few ofthem.
27. What is IPC? Name threetechniques.
28. Explain mkfifo(), open(), close() with parameters.
29. What is meant by filedescriptor?
30. What is meant by trafficshaping?
31. How do you classify congestion controlalgorithms?
32. Differentiate between Leaky bucket and Tokenbucket.
REFERENCE