Computer Networks Lab Manual-17ECL68
Computer Networks Lab Manual-17ECL68
B.E. VI Semester
Prepared by
Prof. K.EZHILARASAN
&
Prof. SOWNDESWARI S
Choose suitable tools to model a network and understand the protocols at various OSI
reference levels.
Design a suitable network and simulate using a Network simulator tool.
Simulate the networking concepts and protocols using C/C++ programming.
Model the networks for different configurations and analyze the results.
LABORATORY EXPERIMENTS
PART-A: Simulation experiments using NS2/ NS3/ OPNET/ NCTUNS/ NetSim / QualNet /
Packet Tracer or any other equivalent tool.
1. Implement a point to pint network with four nodes and duplex links between them.
Analyze the network performance by setting the queue size and varying the bandwidth.
2. Implement a four node point to point network with links n0-n2, n1-n2 and n2-n3. Apply
TCP agent between n0-n3 and UDP between n1-n3. Apply relevant applications over
TCP and UDP agents changing the parameter and determine the number of packets sent
by TCP/UDP.
3. Implement Ethernet LAN using n (6-10) nodes. Compare the throughput by changing the
error rate and data rate.
4. Implement Ethernet LAN using n nodes and assign multiple traffic to the nodes and
obtain congestion window for different sources/ destinations.
5. Implement ESS with transmission nodes in Wireless LAN and obtain the performance
parameters.
6. Implementation of Link state routing algorithm.
1. Write a program for a HLDC frame to perform the following. i) Bit stuffing ii) Character
stuffing.
2. Write a program for distance vector algorithm to find suitable path for transmission.
3. Implement Dijkstra’s algorithm to compute the shortest routing path.
4. For the given data, use CRC-CCITT polynomial to obtain CRC code. Verify the program
for the cases: i) Without error ii) With error.
5. Implementation of Stop and Wait Protocol and Sliding Window Protocol.
6. Write a program for congestion control using leaky bucket algorithm.
Course outcomes: On the completion of this laboratory course, the students will be able to:
Design and Simulate Network elements with various protocols and standards.
Use the network simulator tools for learning and practice of networking algorithms.
Demonstrate the working of various protocols and algorithms using C programming.
Engineering Knowledge.
Problem Analysis.
Design/Development of solutions.
OSI MODEL
layers.1 When virtually linked with the same layer on another host, these layers are called
peers.2 Although not directly connected to each other, these peers virtually communicate with
one another using a protocol represented by an arrow. As has already been mentioned, the actual
communication needs to propagate down the stack and use the above layering concept.
Suppose an application process running on Layer 4 of the source generates data or messages
destined for the destination. The communication starts by passing a generated message M down
to Layer 3, where the data are segmented into two chunks (M1 and M2), and control information
called header (H3) specific to Layer 3 is appended to M1 and M2. The control information are,
for example, sequence numbers, packet sizes, and error checking information. These information
are understandable and used only by the peering layer on the destination to recover the data (M).
The resulting data (e.g., H3+M1) is handed to the next lower layer, where some protocol-specific
control information are again added to the message. This process continues until the message
reaches the lowest layer, where transmission of information is actually performed over a physical
medium. Note that, along the line of these processes, it might be necessary to further segment the
data from upper layers into smaller segments for various purposes. When the message reaches
the destination, the reverse process takes place. That is, as the message is moving up the stack,
its headers are ripped off layer by layer. If necessary, several messages are put together before
being passed to the upper layer. The process continues until the original message (M) is
recovered at Layer 4.
The OSI (Open Systems Interconnection) model was the first reference model developed by ISO
(International Standards Organization) to provide a standard framework in order to describe the
protocol stacks in a computer network. Its consists of seven layers where each layer is intended
to perform a well-defined function. These are physical layer, data link layer, network layer,
transport layer, session layer, presentation layer, and application layer. The OSI model only
specifies what each layer should do; it does not specify the exact services and protocols to be
used in each layer. Although not implemented in current systems, the OSI model philosophy
(i.e., the layering concept) lays a strong foundation for further development in computer
networking.
The TCP (Transmission Control Protocol)/IP (Internet Protocol) reference model, which is based
on the two primary protocols, namely, TCP and IP, is used in the current Internet. These
protocols have proven very powerful, and as a result, have experienced widespread use and
implementation in the existing computer networks. It was developed for ARPANET, a research
network sponsored by the U.S. Department of Defense, which is considered as the grandparent
of all computer networks. In the TCP/IP model, the protocol stack consists of five layers –
physical, data link, network, transport, and application – each of which is responsible for certain
services as will be discussed shortly. Note that the application layer in the TCP/IP model can be
considered as the combination of session, presentation, and application layers of the OSI model.
Application Layer
The application layer sits on top of the stack, and uses services from the transport layer
(discussed below). This layer supports several higher-level protocols such as HTTP (Hypertext
Transfer Protocol) for World Wide Web applications, SMTP (Simple Mail Transfer Protocol) for
electronic mail, TELNET for remote virtual terminal, DNS (Domain Name Service) for mapping
comprehensible host names to their network addresses, and FTP (File Transfer Protocol) for file
transfer.
Transport Layer
The objective of a transport layer is to transport the messages from the application layer of the
source host to that of the destination host. To accomplish this goal, two well-known protocols,
namely, TCP and UDP (User Datagram Protocol), are defined in this layer. While TCP is
responsible for a reliable and connection-oriented communication between the two hosts, UDP
supports an unreliable connectionless transport. TCP is ideal for applications that prefer accuracy
over prompt delivery and the reverse is true for UDP. Generally, control information related to
low control and error control need to be embedded into the messages. Also, before adding any
header, fragmentation is usually performed to break a long message into segments. For this
reason, the protocol data units in this layer are normally called segments.
Network Layer
This layer provides routing services to the transport layer. Network layer is designed to deliver
the data units, usually called packets, along the paths they are meant to traverse from a source
host to a destination host. Again, to facilitate routing, headers containing information such as
source and destination network addresses are added to the transport protocol data units to
formulates network-layer data unit.
Link Layer
The packets are generally routed through several communication links and nodes before they
actually reach the destination node. To successfully route these packets all the way to the
destination, a mechanism is required for node to-node delivery across each of the communication
links. A link layer protocol is responsible for data delivery across a communication link.
A link layer protocol has three main responsibilities. First, flow control regulates the
transmission speed in a communication link. Secondly, error control ensures the integrity of data
transmission. Thirdly, flow multiplexing/demultiplexing combines multiple data flows into and
extracts data flows from a communication link. Choices of link layer protocols may vary from
host to host and network to network. Examples of widely-used link layer protocols/technologies
include Ethernet, Point-to-Point Protocol (PPP), IEEE 802.11 (i.e., WiFi), and Asynchronous
The physical layer deals with the transmission of data bits across a communication link. Its
primary goal is to ensure that the transmission parameters (e.g., transmission power, modulation
scheme) are set appropriately to achieve the required transmission performance (e.g., to achieve
the target bit error rate performance). Finally, we point out that the five layers discussed above
are common to the OSI layer. As has already been mentioned, the OSI model contains two other
layers sitting on top of the transport layer, namely, session and presentation layers. The session
layer simply allows users on different computers to create communication sessions among
themselves. The presentation layer basically takes care of different data presentations existing
across the network. For example, a unified network management system gathers data with
different format from different computers and converts their format into a uniform format.
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 using NS2.
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 etc...
• 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 stdout{Hello, World!}
Hello, World!
Variables Command Substitution
set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]
Simple Arithmetic
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
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
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and applications.
4. The nam visualization tool.
5. Tracing and random variables.
Initialization and Termination of TCL Script in NS-2
An ns simulation starts with the command
It is the first line in the tcl script. This line declares a new variable as using the set command, you
can call this variable as you wish, In general people declares it as ns because 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]
The above creates a 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 begin 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
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 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,
$ns at 125.0 “finish”
It will be used to call “finish” at time 125sec. This simulator allows us 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.
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).
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$ns
queue-limit $n0 $n2 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.
#Setup a UDP connection
set udp [new Agent/UDP]
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.
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 the format:
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 identifier. 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.
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
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:
awk option ‘selection_criteria {action}’ file(s)
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 their 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 BEGIN and END sections are optional and take the form
BEGIN {action}
END {action}
These two sections, when present, are delimited by the body of the awk program. You
can use them to print a suitable heading at the beginning and the average salary at the end.
BUILT-IN VARIABLES
Awk has several built-in variables. They are all assigned automatically, though it is also
possible for a user to reassign some of them. You have already used NR, which signifies the
record number of the current line. We’ll now have a brief look at some of the other variable.
The FS Variable: as stated elsewhere, awk uses a contiguous string of spaces as the default field
delimiter. FS redefines this field separator, which in the sample database happens to be the |.
When used at all, it must occur in the BEGIN section so that the body of the program knows its
value before it starts processing:
BEGIN {FS=”|”}
This is an alternative to the –F option which does the same thing.
The OFS Variable: when you used the print statement with comma-separated arguments, each
argument was separated from the other by a space. This is awk’s default output field separator,
and can reassigned using the variable OFS in the BEGIN section:
BEGIN { OFS=”~” }
When you reassign this variable with a ~ (tilde), awk will use this character for delimiting the
print arguments. This is a useful variable for creating lines with delimited fields.
The NF variable: NF comes in quite handy for cleaning up a database of lines that don’t contain
the right number of fields. By using it on a file, say emp.lst, you can locate those lines not having
6 fields, and which have crept in due to faulty data entry:
$awk ‘BEGIN {FS = “|”}
NF! =6 {
Print “Record No “, NR, “has”, “fields”}’ empx.lst
NS-2 Simulation:
Simulation using NS2 consists of three main steps. First, the simulation design is probably the
most important step. Here, we need to clearly specify the objectives and assumptions of the
simulation. Secondly, configuring and running simulation implements the concept designed in
the first step. This step also includes configuring the simulation scenario and running simulation.
The final step in a simulation is to collect the simulation result and trace the simulation if
necessary.
PART-A
Simulation
experiments
using NS2
1. Implement a point to pint network with four nodes and duplex links between them.
Analyze the network performance by setting the queue size and varying the bandwidth.
#===================================
# Simulation parameters setup
#===================================
set val(stop) 10.0; # time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#===================================
# Nodes Definition
#===================================
#Create 4 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#===================================
# Links Definition
#===================================
#===================================
# Agents Definition
#===================================
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink2 [new Agent/TCPSink]
$ns attach-agent $n3 $sink2
$ns connect $tcp0 $sink2
$tcp0 set packetSize_ 1500
#===================================
# Applications Definition
#===================================
#Setup a FTP Application over TCP connection
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns at 1.0 "$ftp0 start"
$ns at 2.0 "$ftp0 stop"
#===================================
# Termination
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam lab1.nam &
exit 0
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run
Awk Script:
BEGIN{
tcppack=0
tcppack1=0
}
{
if($1=="r"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
tcppack++;
}
if($1=="d"&&$3=="2"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
tcppack1++;
}
}
END{
printf("\n total number of data packets received at Node 3: %d\n",
tcppack++);
printf("\n total number of packets dropped at Node 2: %d\n", tcppack1++);
}
Output:
2. Implement a four node point to point network with links n0-n2, n1-n2 and n2-n3. Apply
TCP agent between n0-n3 and UDP between n1-n3. Apply relevant applications over
TCP and UDP agents changing the parameter and determine the number of packets sent
by TCP/UDP.
#===================================
# Simulation parameters setup
#===================================
set val(stop) 10.0; # time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#===================================
# Nodes Definition
#===================================
#Create 4 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#===================================
# Links Definition
#===================================
#Createlinks between nodes
$ns duplex-link $n0 $n2 200.0Mb 10ms DropTail
$ns queue-limit $n0 $n2 50
$ns duplex-link $n2 $n3 200.0Mb 10ms DropTail
$ns queue-limit $n2 $n3 50
$ns duplex-link $n1 $n2 200.0Mb 10ms DropTail
$ns queue-limit $n1 $n2 50
#===================================
# Agents Definition
#===================================
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink3 [new Agent/TCPSink]
$ns attach-agent $n3 $sink3
$ns connect $tcp0 $sink3
$tcp0 set packetSize_ 1000
$tcp0 set interval_ 0.1
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam lab2.nam &
exit 0
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run
Awk Script:
BEGIN{
tcppack=0
tcppack1=0
}
{
if($1=="r"&&$4=="2"&&$5=="tcp"&&$6=="340")
{
tcppack++;
}
if($1=="r"&&$4=="2"&&$5=="cbr"&&$6=="300")
{
tcppack1++;
}
}
END{
printf("\n total number of TCP data packets sent between Node 0 and Node
2: %d\n", tcppack++);
printf("\n total number of UDP data packets sent between Node 1 and Node
2: %d\n", tcppack1++);
}
Output:
Results:
3. Implement Ethernet LAN using n (6-10) nodes. Compare the throughput by changing the
error rate and data rate.
$ns make-lan "$n0 $n1 $n2 $n3" 100Mb 300ms LL Queue/DropTail Mac/802_3
$ns make-lan "$n4 $n5 $n6 $n7" 100Mb 300ms LL Queue/DropTail Mac/802_3
# set error rate. Here ErrorModel is a class and it is single word and
space should not be given between Error and Model
# lossmodel is a command and it is single word. Space should not be given
between loss and model
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab3.nam &
exit 0
}
$ns at 0.1 "$cbr start"
$ns at 3.0 "finish"
$ns run
Awk Script:
BEGIN{
tcppack=0
tcppack1=0
}
{
if($1=="r"&&$4=="7"&&$5=="cbr"&&$6=="1000")
{
tcppack++;
}
}
END{
printf("\n total number of data packets at Node 7: %d\n", tcppack++);
Output:
Results:
4. Implement Ethernet LAN using n nodes and assign multiple traffic to the nodes and
obtain congestion window for different sources/ destinations.
//setup initialization//
set ns [new Simulator]
set tf [open lab4.tr w]
$ns trace-all $tf
set nf [open lab4.nam w]
$ns namtrace-all $nf
//Process Termination//
proc finish { } {
global nf tf ns
$ns flush-trace
exec nam lab7.nam &
close $nf
close $tf
exit 0
}
$ns at 0.1 "$ftp0 start"
$ns at 1.5 "$ftp0 stop"
$ns at 2 "$ftp0 start"
$ns at 3 "$ftp0 stop"
$ns at 0.2 "$ftp2 start"
$ns at 2 "$ftp2 stop"
$ns at 2.5 "$ftp2 start"
$ns at 4 "$ftp2 stop"
$ns at 5.0 "finish"
$ns run
Awk Script:
BEGIN{
tcppack=0
tcppack1=0
}
{
if($1=="r"&&$4=="7"&&$5=="cbr"&&$6=="1000")
{
tcppack++;
}
}
END{
printf("\n total number of data packets at Node 7: %d\n", tcppack++);
Output:
5. Implement ESS with transmission nodes in Wireless LAN and obtain the performance
parameters.
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
Output:
#===================================
# Simulation parameters setup
#===================================
set val(stop) 10.0; # time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#===================================
# Nodes Definition
#===================================
#Create 5 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
#===================================
# Links Definition
#===================================
#Createlinks between nodes
$ns duplex-link $n0 $n1 100.0Mb 10ms DropTail
$ns queue-limit $n0 $n1 50
$ns duplex-link $n0 $n2 100.0Mb 10ms DropTail
#===================================
# Agents Definition
#===================================
#Setup a UDP connection
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
set null1 [new Agent/Null]
$ns attach-agent $n4 $null1
$ns connect $udp0 $null1
$udp0 set packetSize_ 1500
#===================================
# Applications Definition
#===================================
#Setup a CBR Application over UDP connection
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
$cbr0 set packetSize_ 1000
$cbr0 set rate_ 1.0Mb
$cbr0 set random_ null
$ns at 1.0 "$cbr0 start"
$ns at 5.0 "$cbr0 stop"
$ns rtproto LS
#===================================
# Termination
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam lab6.nam &
exit 0
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run
Output:
PART-B:
Implement the
following in
C/C++.
1. Write a program for a HLDC frame to perform the following. i) Bit stuffing ii)
Character stuffing.
Theory
Security and Error detection are the most prominent features that are to be provided by any
application which transfers data from one end to the other end. One of such a mechanism in
tracking errors which may add up to the original data during transfer is known as Stuffing. It
is of two types namely Bit Stuffing and the other Character Stuffing. Coming to the Bit
Stuffing, 01111110 is appended within the original data while transfer of it. The following
program describes how it is stuffed at the sender end and de-stuffed at the receiver end.
Algorithm:
1. Start
2. Initialize the array for transmitted stream with the special bit pattern 0111 1110which
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
i) Bit stuffing:
#include<stdio.h>
#include<string.h>
int main()
{
char data[50],stuff[50],dstuff[50];
int i,j,count,length;
printf("enter the data\n");
scanf("%s",data);
length=strlen(data);
count=0,j=0;
for (i=0;i<length;i++)
{
if(data[i]=='1')
{
count++;
}
else
{
count=0;
}
stuff[j]=data[i];
j++;
if(count==5 && data[i+1]=='1')
{
stuff[j]='0';
j++;
count=0;
}
}
stuff[j]='\0';
printf("stuffed data at intermediate site is \n 01111110 %s 01111110 \n",stuff);
///destuffing
length=strlen(stuff);
count=0;j=0;
for(i=0;i<length;i++)
{
if(stuff[i]=='1')
{
count++;
}
else
{
count=0;
}
dstuff[j]=stuff[i];
j++;
dstuff[j]='\0';
printf("\n\ndestuffed data : %s",dstuff);
Output:
Theory
The Character Stuffing, DLESTX and DLEETX are used to denote start and end of character
data with some constraints imposed on repetition of characters as shown in the program below
clearly.
b[0]='d';
b[1]='l';
b[2]='e';
b[3]='s';
b[4]='t';
b[5]='x';
j=6;
while(i<n)
{
if(i==pos-1)
{
b[j]='d';
b[j+1]='l';
b[j+2]='e';
b[j+3]=ch;
b[j+4]='d';
b[j+5]='l';
b[j+6]='e';
j=j+7;
}
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;
}
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("\nframe after stuffing:\n");
printf("%s",b);
getch();
}
Output:
enter string
SAMBHRAM
enter position
5
enter the character
frame after stuffing:
dlestxSAMBdle
dleHRAMdleetx
2. Write a program for distance vector algorithm to find suitable path for
transmission.
Each node constructs a one-dimensional array containing the "distances"(costs) to all other nodes
and distributes that vector to its immediate neighbors.
1. The starting assumption for distance-vector routing is that each node knows the cost of
the link to each of its directly connected neighbors.
2. A link that is down is assigned an infinite cost.
Note that each node only knows the information in one row of the table.
1. Every node sends a message to its directly connected neighbors containing its personal
list of distance. ( for example, A sends its information to its neighbors B,C,E, and F. )
2. If any of the recipients of the information from A find that A is advertising a path shorter
than the one they currently know about, they update their list to give the new path length
and note that they should send packets for that destination through A. ( node B learns
from A that node E can be reached at a cost of 1; B also knows it can reach A at a cost of
1, so it adds these to get the cost of reaching E by means of A. B records that it can reach
E at a cost of 2 by going through A.)
3. After every node has exchanged a few updates with its directly connected neighbors, all
nodes will know the least-cost path to all the other nodes.
4. In addition to updating their list of distances when they receive updates, the nodes need to
keep track of which node told them about the path that they used to calculate the cost, so
that they can create their forwarding table. ( for example, B knows that it was A who said
" I can reach E in one hop" and so B puts an entry in its table that says " To reach E, use
the link to A.)
#include<stdio.h>
#include<stdlib.h>
struct node
{
int dist[15];
int from[15];
};
int main()
{
int a[15][15],n=0,i,j,k,count;
struct node s[10];
printf("enter number of nodes\n");
scanf("%d",&n);
printf("enter matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
Dept. of ECE, SaIT, Bengaluru Page 50
COMPUTER NETWORKS LABORATORY 2019
Output:
0112112
1012223
1101222
2210321
1223023
1222201
2321310
Src : 1 > Dest : 1 Next node : 1 Distance : 0
Src : 1 > Dest : 2 Next node : 2 Distance : 1
Src : 1 > Dest : 3 Next node : 3 Distance : 1
Src : 1 > Dest : 4 Next node : 4 Distance : 2
Src : 1 > Dest : 5 Next node : 5 Distance : 1
Src : 1 > Dest : 6 Next node : 6 Distance : 1
Src : 1 > Dest : 7 Next node : 7 Distance : 2
Theory:
Dijkstra’s Shortest Path Algorithm is a popular algorithm for finding the shortest path between
different nodes in a graph. Often used in routing, this algorithm is implemented as a subroutine
in other graph algorithm. Dijkstra’s algorithm finds the solution for the single source shortest
path problems only when all the edge-weights are non-negative on a weighted, directed graph. In
other words, the graph is weighted and directed with the first two integers being the number of
vertices and edges that must be followed by pairs of vertices having an edge between them.In the
source code for Dijkstra’s algorithm in C, the inputs are asked as source, target and the weight of
the path between two nodes. Before going through the source code for Dijkstra’s algorithm in C,
here’s a look at the algorithm itself and a pseudo code based on the algorithm.
Alogorithm:
Let’s fix a node as the initial node; this will be the node at which we are starting. Let the
distance of node “Y” be the distance from the initial node to “Y”. Now, in Dijkstra’s algorithm,
some initial distance values are assigned, and these values are improved step by step. The
algorithm procedure is given below:
1. A tentative distance value is assigned to every node; this value is set to zero for the initial
node, and to infinity for all other nodes.
2. All nodes unvisited are marked, and the initial node is set as current. An unvisited set ( a
set of all the unvisited nodes) consisting of all the nodes is created.
3. For the current/initial node, take into account all the unvisited nearby nodes, and
calculate their tentative distances. Make a comparison of the current assigned value and
the newly calculated tentative distance; assign the smaller value. For example: if the
current/initial node X was marked with a distance of 4, and the edge connecting it with a
nearby neighbor node Y has length 1, then the distance through X to Y will be 4 + 1 = 5. If
Y was previously assigned a value greater than 5, then change it to 5. Otherwise, keep the
value as it is.
4. A visited node is never to be checked again. So, after finishing above steps with all the
neighbors of the current node, make that node as visited and remove is from the unvisited
set.
5. Stop the algorithm if, when planning a route between two specific nodes, the destination
node has been marked visited.
6. Also, stop the algorithm if, when planning a complete traversal, the smallest tentative
distance among the nodes in the unvisited set is infinity. This case is a result of no
connection between the initial node and the remaining unvisited nodes.
7. Find the unvisited node assigned with the smallest tentative distance value, and this will
be the new “current mode”. Go back to step 3, and continue.
Example:
Steps
Any edge that starts and ends at the same vertex is a loop.
Step 2: Remove all parallel edges between two vertex except the one with least
weight
In this graph, vertex A and C are connected by two parallel edges having weight 10 and 12
respectively. So, we will remove 12 and keep 10.
We are now ready to find the shortest path from vertex A to vertex D.
After solving this we will have the following result. (See the above video for the steps)
Result
Code
Note! In the given code we are representing Vertices using decimal numbers.
So,
vertex A is denoted by digit 0.
vertex B is denoted by digit 1.
vertex C is denoted by digit 2.
vertex D is denoted by digit 3.
Program:
#include <stdio.h>
#include <stdlib.h>
/**
* contant to represent infinity
* it is assumed that no edge in the vertex will have weight equal
* to this value.
*/
#define INF 9999
#define V 4
int i = 0;
for (i = 0; i < markedVerticesIdx; i++) {
if (v == markedVertices[i]) {
return 1;
}
}
return 0;
}
// this function will find shortest path between source and destination vertex//
//variables
int i, r, c,
tmpC,
min,
currVertex,
edgeWt = 0,
destValue = 0,
markedValue = 0,
wtTableR = 0,
markedVerticesIdx = 0;
int weightTable[V][V];
for (r = 0; r < V; r++)
{
for (c = 0; c < V; c++)
{
weightTable[r][c] = INF;
}
}
weightTable[wtTableR++][src] = 0;
/*** find the weight from the current vertex to all the other vertices that are directly
connected and not yet marked */
edgeWt = graph[currVertex][c];
destValue = weightTable[wtTableR - 1][c];
markedValue = weightTable[wtTableR][currVertex];
weightTable[wtTableR][c] = min;
min = INF;
for (c = 0; c < V; c++) {
markedVertices[markedVerticesIdx++] = tmpC;
currVertex = tmpC;
wtTableR++;
c = dest;
shortestPathVertices[shortestPathVerticesIdx++] = c;
markedValue = weightTable[wtTableR - 1][dest];
for (r = wtTableR - 2; r >= 0; r--)
{
if (weightTable[r][c] != markedValue)
{
c = markedVertices[r];
markedValue = weightTable[r][c];
shortestPathVertices[shortestPathVerticesIdx++] = c;
}
int main(void)
{
return 0;
}
Output:
4. For the given data, use CRC-CCITT polynomial to obtain CRC code. Verify the
program for the cases: i) Without error ii) With error.
Theory:
Cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks
and storage devices to detect accidental changes to raw data. Blocks of data entering these
systems get a short check value attached, based on the remainder of a polynomial division of
their contents. On retrieval, the calculation is repeated and, in the event the check values do not
match, corrective action can be taken against data corruption. CRCs can be used for error
correction.
CRCs are so called because the check (data verification) value is a redundancy (it expands the
message without adding information) and the algorithm is based on cyclic codes. CRCs are
popular because they are simple to implement in binary hardware, easy to analyze
mathematically, and particularly good at detecting common errors caused by noise in
transmission channels
The basic idea is to treat the entire message as a (rather long) binary number, which both the
sender and receiver divide using the same divisor. The quotient is discarded, and the remainder is
sent as the CRC. If the message is received without error, the receiver's calculation will match
the sender's calculation, and the CRC's will agree.
Algorithm:
Example:
Let M be the message to be transmitted, the value is: 1010 0011 1010 1100
It is assumed that G is 11010
We call M' the message with the CRC
The CRC is M / G.
The CRC code is the result of the division M / G where to M are attached n bits null
(0) corresponding to the degree of G.
We assume that G = 11010this means that its grade is 4; this means G(bit)=4so
we attach 4null bits (0) to M.
Now M is:
M = 1010 0011 1010 11000000.
Below is an example on how to calculate the CRC.
If the receiver makes the division of M' with G and gets 0 (zero) it means that there were
no errors during transmission.
Below there is an example where the CRC is concatenated to message during Tx and Rx that
receive the message and recalculate the CRC (must be 0).
C Source Code:
#include<stdio.h>
int a[100], b[100], i, j, len, k, count = 0;
//Generator Polynomial:g(x)=x^16+x^12+x^5+1
int gp[] = { 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, };
int
main ()
{
void div ();
printf ("\nEnter the length of Data Frame :");
scanf ("%d", &len);
printf ("\nEnter the Message :");
for (i = 0; i < len; i++)
scanf ("%d", &a[i]);
div ();
void
div ()
{
for (i = 0; i < k; i++)
{
if (a[i] == gp[0])
{
for (j = i; j < 17 + i; j++)
a[j] = a[j] ^ gp[count++];
}
count = 0;
}
}
Output:
Theory:
Stop-and-wait protocol and Sliding window protocol are the methods evolved for handling the
flow control of the network data transfers. These methods mainly differentiated by the
techniques they follow such as stop-and-wait uses the concept of the acknowledging each data
unit before sending another data unit. Conversely, sliding window protocol allows the transition
of the several data units before sending an acknowledgement. Among the two protocols, the
sliding window protocol is more efficient than the stop-and-wait protocol.
Stop-and-Wait Protocol
In a communication, if the speed of transmitting data at the sender end is very much higher than
the speed of reception of data at the receiver end, how the network is going to deal with these
kinds of cases? It requires the working speed of sender and receiver should be unvarying. The
stop-and-wait protocol has emerged as a solution to this problem. In this protocol, the sender
sends a frame then waits for the acknowledgement. When the receiver sends an
acknowledgement to the sender, it proceeds further and sends another frame.
The transmission mode of the protocol is half duplex, as the sender transmits data to the receiver
at a time and receiver sends the acknowledgement when data is received.
The example of the stop-and-wait protocol is the RPC (Remote Procedure Call) because it
works in the similar pattern where the subroutine calls are implemented from the program in one
device to the library routines on another device. As most programs are single-threaded, which
make the sender wait for the reply before proceeding and sending other requests.
Like stop-and-wait protocol, sliding window protocol is also a method to implement the flow
control mechanism. It has eliminated the drawback of the stop-and-wait protocol where the
restricted amount of data can be transmitted in one direction at a time. The performance of the
sliding window protocol has improved by sending multiple frames bidirectional at the same time
(i.e., n>1, while stop-and-wait limits n to 1). In this scheme, the sender sends sequentially
numbered frames to the recipient in order to keep track of the frames, if the header size is n bit
the sequence can range from 0 to (2n-1).
The window here signifies a buffer utilized to store the data till the receiver does not read it, after
reading the content the buffer is emptied. It uses two types of windows, sending window and
receiving window which can range up to (2n-1). The sending window maintains the sequence
number relating to the transmitted frames, and it is controlled at the sender’s end. Similarly, the
receiver’s end also has a receiving window to keep track of the frames allowed to accept.
The TCP protocol works as the sliding window protocol and uses a buffer placed in the kernel
of the operating system.
Algorithm:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int i,j,noframes,x,x1=10,x2;
noframes=10;
i=1;
j=1;
printf("number of frames is %d ",noframes);
getch();
while(noframes>0)
{
printf("\nsending frames is %d",i);
x=rand()%10;
if(x%10==0)
{
for(x2=1;x2<2;x2++)
{
printf("\n waiting for %d seconds\n",x2);
sleep(x2);
}
printf("\n sending frames %d\n",i);
x=rand()%10;
}
printf("\n ack for frame %d\n",j);
noframes=noframes-1;
i++;
j++;
}
printf("\n end of stop and wait protocol\n");
Output:
number of frames is 10
sending frames is 1
ack for frame 1
sending frames is 2
ack for frame 2
sending frames is 3
Dept. of ECE, SaIT, Bengaluru Page 75
COMPUTER NETWORKS LABORATORY 2019
sending frames is 4
ack for frame 4
sending frames is 5
ack for frame 5
sending frames is 6
ack for frame 6
sending frames is 7
ack for frame 7
sending frames is 8
ack for frame 8
sending frames is 9
ack for frame 9
sending frames is 10
ack for frame 10
#include<stdio.h>
int
main ()
{
int w, i, f, frames[50];
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);
if (f % w != 0)
printf ("\nAcknowledgement of above frames sent is received by sender\n");
return 0;
}
Output:
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
Acknowledgement of above frames sent is received by sender
46
Acknowledgement of above frames sent is received by sender
Theory:
In the network layer, before the network can make Quality of service guarantees, it must know
what traffic is being guaranteed. One of the main causes of congestion is that traffic is often
bursty.
To understand this concept first we have to know little about traffic shaping. Traffic Shaping is
a mechanism to control the amount and the rate of the traffic sent to the network. Approach of
congestion management is called Traffic shaping. Traffic shaping helps to regulate rate of data
transmission and reduces congestion.
1. Leaky Bucket
2. Token Bucket
Suppose we have a bucket in which we are pouring water in a random order but we have to get
water in a fixed rate, for this we will make a hole at the bottom of the bucket. It will ensure that
water coming out is in a some fixed rate, and also if bucket will full we will stop pouring in it.
The input rate can vary, but the output rate remains constant. Similarly, in networking, a
technique called leaky bucket can smooth out bursty traffic. Bursty chunks are stored in the
bucket and sent out at an average rate.
In the figure, we assume that the network has committed a bandwidth of 3 Mbps for a host. The
use of the leaky bucket shapes the input traffic to make it conform to this commitment. In Figure
the host sends a burst of data at a rate of 12 Mbps for 2 s, for a total of 24 Mbits of data. The host
is silent for 5 s and then sends data at a rate of 2 Mbps for 3 s, for a total of 6 Mbits of data. In
all, the host has sent 30 Mbits of data in 10 s. The leaky bucket smooths the traffic by sending
out data at a rate of 3 Mbps during the same 10 s.
Without the leaky bucket, the beginning burst may have hurt the network by consuming more
bandwidth than is set aside for this host. We can also see that the leaky bucket may prevent
congestion.
A simple leaky bucket algorithm can be implemented using FIFO queue. A FIFO queue holds
the packets. If the traffic consists of fixed-size packets (e.g., cells in ATM networks), the process
removes a fixed number of packets from the queue at each tick of the clock. If the traffic consists
of variable-length packets, the fixed output rate must be based on the number of bytes or bits.
Algorithm:
1. Start
2. Set the bucket size or the buffer size.
3. Set the output rate.
4. Transmit the packets such that there is no overflow.
5. Repeat the process of transmission until all packets are transmitted. (Reject packets
where its size is greater than the bucket size)
6. Stop
Example:
Let n=1000
Packet=
Since n> front of Queue i.e. n>200
Therefore, n=1000-200=800
Packet size of 200 is sent to the network.
C Program:
#include<stdio.h>
#include<stdlib.h>
#define MIN(x,y) (x>y)?y:x
int main()
{
int orate,drop=0,cap,x,count=0,inp[10]={0},i=0,nsec,ch;
printf("\n enter bucket size : ");
scanf("%d",&cap);
else
{
drop=0;
count=0;
}
printf(" \t %d \t %d \n",drop,count);
}
return 0;
}
Output:
1 3 3 0 0
2 7 6 0 1
3 9 6 0 4
4 7 6 0 5
5 4 6 0 3
6 0 3 0 0
VIVA QUESTIONS
1. What is FIFO? How to implement Multiple FIFOs? Disadvantages of FIFO.
2. What is congestion? Explain leaky bucket and token bucket algorithm? What are its
disadvantages of each?
3. List other congestion control algorithm.
4. What are the disadvantages of RSA Algorithm?
5. What is the need for routing protocols? List some routing protocols. Which are common
routing algorithms used by routing protocols?
6. Disadvantages of Distance vector routing. Explain the method to overcome such
disadvantage.
7. What is CRC? What is the need for CRC? Which Layer it is implemented?
8. Can CRC be employed for error correction if so how.
9. Explain steps of error correction and error detection. What is encoding and decoding,
why it is required?
10. What is Hamming code? Can it be used for error detection and correction how?
11. What are linear block codes? Explain their advantages.
12. What is protocol? List some protocols. How to modify existing protocol?
13. Difference between TCP/IP and OSI Layer Model?
14. Difference between Router, Bridge, Gateway channel. In which layer it is used?
15. Difference between hub and switch. Which is more compatible and reliable?
16. Explain various Ethernet standards.
17. Difference between IP and MAC address.
18. In which layer ATM protocol is used? Explain the purpose.
19. In Which layer or protocol which converts IP to MAC Address.
20. Which are the different collision detection protocols?
21. Which are the different channelization protocol and explain their needs?
22. Explain term error rate, bandwidth, throughput transmission delay, BER, Interarrival
time. What is unit of bandwidth?