Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 75

S.T.S.K.

K’S

TONTADARYA COLLEGE OF ENGINEERING –


GADAG

CCN LAB MANUAL


15ECL68
Objectives and Outcomes of Network Laboratory
Objectives:

 To get some exposure to one of the most useful tools in Network research and development.

 Understand and design network topology using NS2.

 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 analyse the results.

Outcomes:

 Learn the basic idea about open source network simulator NS2 and how to download, install
and work with NS2 using TCL programming.

 Defining the different agents and their applications like TCP, FTP over TCP, UDP, CBR
and CBR over UDP etc.

 Identifying and solving the installation error of NS2.

 Understand the basic concepts of link layer properties including error-detection.

 Understand the basic concepts of application layer protocol design including client/server models.

 Working with a congestion control algorithm (Traffic shaping: Leaky bucket) and public-
key encryption system.

 Students get exposure to the real implementation of the computer network scenarios .
‘Instructions to the Candidates’

1. Students should come with thorough preparation for the experiment to be conducted.

2. Students will not be permitted to attend the laboratory unless they bring the practical record
fully completed in all respects pertaining to the experiment conducted in the previous class.

3. Practical record should be neatly maintained.

4. They should obtain the signature of the staff-in-charge in the observation book after completing
each experiment.

5. Theory regarding each experiment should be written in the practical record before procedure in
your own words.

6. Ask lab technician for assistance if you have any problem.

7. Save your class work, assignments in system.

8. Do not download or install software without the assistance of the laboratory technician.

9. Do not alter the configuration of the system.

10. Turnoff the systems after use.


Syllabus

NETWORKS LABORATORY

Sub Code: 15ECL68 IA Marks: 20


Hrs/ Week: 03 Exam Hours: 03
Total Hrs. 42 Exam Marks: 100
Sl.no Name of the Experiments Page no
Part A
1 Implement point-to-point network with 4-nodes and duplex links between them 25
analyze the network performance by setting the queue size and vary the bandwidth.
and find the number of packers dropped.
2 Implement a four node point-to-point network with the links as follows: n0 –n2, n1 – 29
n2 and n2 – n3. Apply TCP agent between n0 – n3 and UDP 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 an Ethernet LAN using N nodes (6-10). Change error rate and data rate 32
and compare throughput
4 Implement an Ethernet LAN using N nodes and set multiple traffic nodes and plot 36
congestion window for different source / destination
5 Simulate simple ESS and with transmitting nodes in wireless LAN and obtain the 40
performance parameter
6 Implement of link state routing algorithm 44
Part B
7 Write a program for the HDLC frame to perform the following 47
a) Bit stuffing 50
b) Byte stuffing
8 Write a program for distance vector algorithm to find the suitable path for 52
transmission
9 Implement Dijkstras algorithm to compute shortest routing path 55
10 for the given data use CRC –CCITT polynomial to obtain CRC code verify the 59
program for the cases
a) With error
b) Without error
11 Write a program for congestion control using leaky bucket algorithm 63
12 Implementation of stop and wait protocol and sliding window 66

The following experiments shall be conducted using NS2 simulators.


How To Install Ubuntu Along With Windows
Install Ubuntu in dual boot with Windows
Follow the steps below to install Ubuntu in dual boot with Windows:
Step 1: Create a live USB or disk
Download and create a live USB or DVD. In Windows, my favourite tool to create a live USB
is Universal USB Installer.
Step 2: Boot in to live USB
Plug the live USB or disk in to the computer and restart the computer. While booting the
computer press F10 or F12 function key (defers from computer to computer) to go to the boot menu.
Now, choose the option to boot from USB or Removable Media.
Step 3: Start the installation
It will take some time to boot in to the live USB or disk. Once booted, you will be immediately
provided with option to either try Ubuntu or install Ubuntu. Even if you choose to try, you can find the
option to install on the desktop:

First few screens are pretty straight forward. Just choose press continue:
Step 4: Prepare the partition
This is the most important part of the whole dual boot installation. Where to install Ubuntu?
Windows is already installed here, so, we’ll prepare a new partition for Ubuntu. In the Installation Type
window, choose Something Else:

As you can see, I have 3 NTFS and some ext4 partitions. If you don’t have ext4 partition, don’t
worry, we don’t need that. As you can see in the picture below, one of the NTFS partition consists of
Windows installation. This should be untouched if you want to keep your Windows installation safe.
I presume that you have more than one NTFS (or FAT 32) partitions (i.e. Drives in Windows
term) on your hard disk, with one of them consisting of Windows installation (usually C drive) . What
you need to do here is to delete a NTFS or existing ext4 partition and create some free space. This will
delete all the data in that partition and this is why I asked you to verify if you have Windows installed
in a different partition.
Click on the desired partition and press the – to delete the partition.
Step 5: Create root, swap and home
Once you have some free space on your hard drive, its time to install Ubuntu on it. Now, there
are several ways to do it. But I prefer to to have a Root, a Swap and a Home.
Create a root partition first. Choose the free space available and click on +.

Here, choose the size of root directory, choose ext4file system, and mount point as / (i.e. root):

Next step is to create swap partition. It is advised by many that Swap should be double of your
system’s RAM size. You can choose the swap size accordingly .
The next step is to create Home. Try to allocate the maximum size to Home because this is where
you’ll be downloading and keeping the files.

Once you have created Root, Swap and Home partitions, click on Install Now button.

Step 6: Follow the trivial instructions


If you successfully created the partitions as mentioned above, you have almost won the battle.
Rest is just some trivial steps to follow. You will be taken through a number of screens to select options
like keyboard layout, login credentials etc. You don’t have to be a genius to figure out what to do here
afterwards. I have attached screenshots for reference purpose here. Once the installation is over, you
will be presented with the option to keep trying live version or to restart the system.

And that’s it. On next boot, you will see the option of Ubuntu in the grub screen. And thus you
can enjoy the beautiful, beginner friendly and world’s most popular Linux distribution. I hope you
found this guide to dual boot Ubuntu 14.04 with Windows helpful. If you need, you can change the
boot order easily to make Windows your default OS. Since you have just installed Ubuntu 14.04, you
can check out things to do after installing Ubuntu 14.04.
Installing Network Simulator 2(NS2) on Ubuntu

Introduction

Network simulators are tools used to simulate discrete events in a network and which helps to
predict the behaviours of a computer network. Generally the simulated networks have entities like
links, switches, hubs, applications, etc. Once the simulation model is complete, it is executed to analyse
the performance. Administrators can then customize the simulator to suit their needs. Network
simulators typically come with support for the most popular protocols and networks in use today, such
as WLAN,UDP,TCP,IP, WAN, etc.

Most simulators that are available today are based on a GUI application like the NCTUNS while
some others incl. NS2 are CLI based. Simulating the network involves configuring the state elements like
links, switches, hubs, terminals, etc. and also the events like packet drop rate, delivery status and so on. The
most important output of the simulations are the trace files. Trace files log every packet, every event that
occurred in the simulation and are used for analysis. Network simulators can also provide other tools to
facilitate visual analysis of trends and potential trouble spots. Most of the simulation is performed in discrete
time intervals where events that are in the queue are processed one after the other in an order.
Since simulation is a complex task, we cannot guarantee that all the simulators can provide exact or
accurate results for all the different type of information. Examples of network simulators are: ns, NCTUNS,
NetSim, etc.ns2 is a name for series of discrete event network simulators like ns-1, ns-2 and ns-3. All of
them are discrete-event network simulators, primarily used in research and teaching. ns2 is free software,
publicly available under the GNU GPLv2 license for research, development, and use.
2 Download and Extract ns2
The package downloaded will be named "ns-allinone-2.35.tar.gz". Copy it to the home folder. Then
in a terminal use the following two commands to extract the contents of the package.:

cd ~/
tar -xvzf ns-allinone-2.35.tar.gz

All the files will be extracted into a folder called "ns-allinone-2.35".


3 Building the dependencies
Ns2 requires a few packages to be pre installed. It also requires the GCC- version 4.3 to work correctly.
So install all of them by using the following command:

sudo apt-get install build-essential autoconfautomakelibxmu-dev

One of the dependencies mentioned is the compiler GCC-4.3, which is no longer available, and thus
we have to install GCC-4.4 version. The version 4.4 is the oldest we can get. To do that, use the
follwoing command:

sudo apt-get install gcc-4.4


The image below shows the output of executing both the above commands. If you have all
the dependencies pre-installed, as I did, the output will look like the image below:

Once the installation is over , we have to make a change in the "ls.h" file. Use the following steps
to make the changes:

Navigate to the folder "linkstate", use the following command. Here it is assumed that the ns
folder extracted is in the home folder of your system.

cd ~/ns-allinone-2.35/ns-2.35/linkstate

Now open the file named "ls.h" and scroll to the 137th line. In that change the word "error" to "this-
>error". The image below shows the line 137 (highlighted in the image below) after making the
changes to the ls.hfile.To open the file use the following command:

geditls.h

Save that file and close it.


Now there is one more step that has to be done. We have to tell the ns which version of GCC will
be used. To do so, go to your ns folder and type the following command:

Sudogedit ns-allinone-2.34/otcl-1.13/Makefile.in

In the file, change Change CC= @CC@ to CC=gcc-4.4, as shown in the image below.

4 Installation

Now we are ready to install ns2. To do so we first require root privileges and then we can run the
install script. Use the following two commands:
sudosu cd ~/ns-allinone-2.35/./install

The following is a snap of these commands:

The image below shows how it looks upon successful execution

It took almost 6 minutes to build and install ns2 on my system. But before we run it, we need to add the build path to
the environment path.

5 Setting the Environment Path


The final step is to tell the system, where the files for ns2 are installed or present. To do that, we have
to set the environment path using the ".bashrc" file. In that file, we need to add a few lines at the
bottom. The things to be added are given below. But for the path indicated below, many of those lines
have "/home/akshay/ns -allinone- 2.35/ " , but that is where I have my extracted folder. Make sure
you replace them with your path. For example, if you have installed it in a folder "/home/abc", then
replace "/home/akshay/ns-allinone-2.35/otcl-1.14" with "/home/abc/ns-allinone-2.35/otcl-1.14".
Do this for all the required lines.

sudogedit ~/.bashrc

Lines to be added:
# LD_LIBRARY_PATH
OTCL_LIB=/home/akshay/ns-allinone-2.35/otcl-1.14
NS2_LIB=/home/akshay/ns-allinone-2.35/lib
X11_LIB=/usr/X11R6/lib
USR_LOCAL_LIB=/usr/local/lib
Computer Network Laboratory Manual

export LD _LIBRARY_PATH=$LD_LIBRARY_PATH:$OTCL_LIB:$NS2_LIB:$X11_LIB:$USR_LO
CAL_LIB
# TCL_LIBRARY
TCL_LIB=/home/akshay/ns-allinone-2.35/tcl8.5.10/
library USR_LIB=/usr/lib
export TCL_LIBRARY=$TCL_LIB:$USR_LIB
# PATH
XGRAPH=/home/akshay/ns-allinone-2.35/bin:/home/akshay/ns-allinone-2.35/tcl8.5.10/unix:/home/
aksh ay/ns-allinone-2.35/tk8.5.10/unix
#the above two lines beginning from xgraph and ending with unix should come on the same line
NS=/home/akshay/ns-allinone-2.35/ns-2.35/
NAM=/home/akshay/ns-allinone-2.35/nam-1.15/
PATH=$PATH:$XGRAPH:$NS:$NAM

Once the changes have been made, save the file and restart the system.
6 Running ns2

Once the system has restarted, open a terminal and start ns2 by using the following command:

ns

If the installation is correct then the terminal looks like the image below :
Experiment No: 1
Implement four nodes point – to – point network with duplex links between them. Set
the queue size, vary the bandwidth and find the number of packets dropped.
Theory:
Point to point
Point to Point networks contains exactly two hosts such as compute,switches, routers, or
servers connected back to back using a single piece of cable. Often, the receiving end of one
host is connected to sending end of the other and vice versa.If the hosts are connected point-to-
point logically, then may have multiple intermediate devices.But the end hosts are unaware of
underlying network and seeeach other as if they are connected directly

A duplex communication system is a point to point system composed of two connected


parties or devices that can communicate with one another in both directions. "Duplex" comes
from "duo" that means "double", and "plex" that means "structure" or "parts of"; thus, a duplex
system has two clearly defined data transmissions, with each path carrying information in only
one direction: A to B over one path, and B to A over the other. There are two types of duplex
communication systems: full-Duplex and half-Duplex.
In a full duplex system, both parties can communicate with each other simultaneously.
An example of a full-duplex device is a telephone the parties at both ends of a call can speak
and be heard by the other party simultaneously. The earphone reproduces the speech of the
remote party as the microphone transmits the speech of the local party, because there is a two-
way communication channel between them, or more strictly speaking, because there are two
communication paths/channels between them.
In a half-duplex system, there are still two clearly defined paths/channels, and each
party can communicate with the other but not simultaneously; the communication is one
direction at a time. An example of a half-duplex device is a walkie-talkie two-way radio that has
a “push to talk” button; when the local user wants to speak to the remote person they push this
button, which turns on the transmitter but turns off the receiver, so they cannot hear the remote
person. To listen to the other person they release the button, which turns on the receiver but
turns off the transmitter.
Duplex systems are employed in many communications networks, either to allow for a
communication "two-way street" between two connected parties or to provide a "reverse path"
for the monitoring and remote adjustment of equipment in the field.
Router forwards packets from one network to another network. When arrival rate of
packets is greater than the service (departure) rate, packets get buffered (queued). Once the
buffer (queue) is completely filled, all arriving packets will be dropped.

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.
6. Setup TCP Connection between n(1) and n(3)
7. Apply CBR Traffic over TCP.
8. Schedule events and run the program.

Program:
#==============================
# Simulation parameter Setup
#==============================
set val(stop) 10.0 Time of simulation end
#===============================
# Initialization
#===============================
Create simulator
set ns [new Simulator] /* Letter S is capital */
Open the NAM tracefile
set nf [open lab1.nam w] /* open a nam trace file in write mode */
$ns namtrace-all $nf /* nf – nam file */
set tf [open lab1.tr w] /* tf- trace file */
$ns trace-all $tf

proc finish { } { /* provide space b/w proc and finish and


all are in small case */

global ns nftf
$ns flush-trace /* clears trace file contents */
close $nf
close $tf
exec nam lab1.nam &
exit 0
}

set n0 [$ns node] /* creates 4 nodes */


set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

$ns duplex-link $n0 $n2 200Mb 10ms DropTail /*Letter M is capital


Mb*/ $ns duplex-link $n1 $n2 100Mb 5msDropTail /*D and T are
capital*/ $ns duplex-link $n2 $n3 1Mb 1000ms DropTail

$ns queue-limit $n0 $n2 10


$ns queue-limit $n1 $n2 10

set udp0 [new Agent/UDP] /* Letters A,U,D and P are capital */

$ns attach-agent $n0 $udp0


set cbr0 [new Application/Traffic/CBR] /* A,T,C,B and R are capital*/
/*S is capital, space after underscore*/

$cbr0 set packetSize_ 500


$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

set udp1 [new Agent/UDP]


$ns attach-agent $n1 $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1

set udp2 [new Agent/UDP]


$ns attach-agent $n2 $udp2

set cbr2 [new Application/Traffic/CBR]


$cbr2 attach-agent $udp2

set null0 [new Agent/Null] /* A and N are capital */


$ns attach-agent $n3 $null0

$ns connect $udp0 $null0


$ns connect $udp1 $null0

$ns at 0.1 "$cbr0 start"


$ns at 0.2 "$cbr1 start"
$ns at 1.0 "finish"

$ns run

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);
}
}
/*immediately after END should open braces ‘{‘
END {
printf("The number of packets dropped =%d\
n",c); }

Steps for execution:


 Open vi editor and type program. Program name should have the extension “ .tcl”
[root@localhost ~]# vi lab1.tcl
 Save the program by pressing “ESC key” first, followed by “Shift and :” key
simultaneously and type “wq” and press Enter key.
 Open vi editor and type awkprogram. Program name should have the extension “.awk”
[root@localhost ~]# vi lab1.awk
 Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
 Run the simulation program
[root@localhost~]# ns lab1.tcl
 Here “ns” indicates network simulator. We get the topology shown in the snapshot.
 Now press the play button in the simulation window and the simulation will begins.
 After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab1.awk lab1.tr
 To see the trace file contents open the file as ,
[root@localhost~]# vi lab1.tr
Trace file contains 12 columns:-
Event type, Event time, From Node, Source Node, Packet Type, Packet Size, Flags (indicated by ----
----), Flow ID, Source address, Destination address, Sequence ID, Packet ID
Output :
Experiment No: 2

FOUR NODE POINT TO POINT NETWORK


Aim: Implement a four node point to point network with the links connected as follows: n0 –
n2, n1 – n2 and n2 – n3. Apply TCP agent between n0 – n3 and UDP agent between n1 – n3.
Apply relevant applications over TCP and UDP agents changing the parameter and
determine the number of packets sent by TCP / UDP.

Theory:
TCP: TCP recovers data that is damaged, lost, duplicated, or delivered out of order by the
internet communication system. This is achieved by assigning a sequence number to each octet
transmitted, and requiring a positive acknowledgment (ACK) from the receiving TCP. If the
ACK is not received within a timeout interval, the data is retransmitted. At the receiver side
sequence number is used to eliminate the duplicates as well as to order the segments in correct
order since there is a chance of “out of order” reception. Therefore, in TCP no transmission
errors will affect the correct delivery of data.
UDP: UDP uses a simple transmission model with a minimum of protocol mechanism. It has
no handshaking dialogues, and thus exposes any unreliability of the underlying network
protocol to the user's program. As this is normally IP over unreliable media, there is no
guarantee of delivery, ordering or duplicate protection.
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
6. Setup TCP Connection and UDP connection
7. Apply CBR Traffic over TCP.
8. Schedule events and run the program.

Program:

set ns [new Simulator]


set nf [open lab2.nam w]
$ns namtrace-all $nf
set tf [open lab2.tr w]
$ns trace-all $tf
proc finish { } {
global ns nftf
$ns flush-trace
close $nf
close $tf
exec nam lab2.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
$ns duplex-link $n0 $n2 10Mb 1ms DropTail
$ns duplex-link $n1 $n2 10Mb 1ms DropTail
$ns duplex-link $n2 $n3 10Mb 1ms DropTail

set tcp0 [new Agent/TCP] # letters A,T,C,P are capital


$ns attach-agent $n0 $tcp0
set udp1 [new Agent/UDP] # letters A,U,D,P are capital
$ns attach-agent $n1 $udp1
set null0 [new Agent/Null]# letters A and N are capital
$ns attach-agent $n3 $null0
set sink0 [new Agent/TCPSink] # letters A,T,C,P,S are capital
$ns attach-agent $n3 $sink0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1
$ns connect $tcp0 $sink0
$ns connect $udp1 $null0
$ns at 0.1 "$cbr1 start"
$ns at 0.2 "$ftp0 start"
$ns at 0.5 "finish"
$ns run

AWK file:
(Open a new editor using “vi command” and write awk file and save with “.awk” extension)
BEGIN{
udp=0;
tcp=0;
}
{
if($1= = “r” && $5 = = “cbr”)
{
udp++;
}
else if($1 = = “r” && $5 = = “tcp”)
{
tcp++;
}
}
END{
printf(“Number of packets sent by TCP = %d\n”,
tcp); printf(“Number of packets sent by UDP=%d\
n”,udp); }
Steps for execution:
 Open vi editor and type program. Program name should have the extension “ .tcl”
[root@localhost ~]# vi lab1.tcl
 Save the program by pressing “ESC key” first, followed by “Shift and :” key
simultaneously and type “wq” and press Enter key.
 Open vi editor and type awkprogram. Program name should have the extension “.awk”
[root@localhost ~]# vi lab1.awk
 Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
 Run the simulation program
[root@localhost~]# ns lab1.tcl
 Here “ns” indicates network simulator. We get the topology shown in the snapshot.
 Now press the play button in the simulation window and the simulation will begins.
 After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab1.awk lab1.tr
 To see the trace file contents open the file as ,
[root@localhost~]# vi lab1.tr

Output :
Experiment No: 3
ETHERNET LAN USING N-NODES

Aim: Implement Ethernet LAN using, n (6-10) nodes, Compare the throughput. By changing
the error rate and data rate and compare

Theory:
Bit error rate (BER):
The bit error rate or bit error ratio is the number of bit errors divided by the total
number of transferred bits during a studied time interval i.e.
BER=Bit errors/Total number of bits
For example, a transmission might have a BER of 10-5 , meaning that on average, 1 out
of every of 100,000 bits transmitted exhibits an error. The BER is an indication of how often a
packet or other data unit has to be retransmitted because of an error. Unlike many other forms of
assessment, bit error rate, BER assesses the full end to end performance of a system including
the transmitter, receiver and the medium between the two. In this way, bit error rate, BER
enables the actual performance of a system in operation to be tested.
Packet Error Rate (PER):
The PER is the number of incorrectly received data packets divided by the total number
of received packets. A packet is declared incorrect if at least one bit is erroneous.
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:
set ns [new Simulator]
set tf [open lab5.tr w]
$ns trace-all $tf

set nf [open lab5.nam w]


$ns namtrace-all $nf

$ns color 0 blue


set n0 [$ns node]
$n0 color "red"
set n1 [$ns node]
$n1 color "red"
set n2 [$ns node]
$n2 color "red"
set n3 [$ns node]
$n3 color "red"
set n4 [$ns node]
$n4 color "magenta"
set n5 [$ns node]
$n5 color "magenta"
set n6 [$ns node]
$n6 color "magenta"
set n7 [$ns node]
$n7 color "magenta"

$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

$ns duplex-link $n3 $n4 100Mb 300ms DropTail


$ns duplex-link-op $n3 $n4 color "green"

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

set err [new ErrorModel]


$ns lossmodel $err $n3 $n4
$err set rate_ 0.1

/* error rate should be changed for each output like 0.1,0.3,0.5…. */

set udp [new Agent/UDP]


$ns attach-agent $n1 $udp
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set fid_ 0
$cbr set packetSize_ 1000
$cbr set interval_ 0.0001
set null [new Agent/Null]
$ns attach-agent $n7 $null
$ns connect $udp $null

proc finish { } {
global ns nftf
$ns flush-trace
close $nf
close $tf
exec nam lab5.nam &
exit 0
}

$ns at 0.1 "$cbr start"


$ns at 3.0 "finish"
$ns run

AWK file: (Open a new editor using “vi command” and write awk file and save with
“.awk” extension)

BEGIN{
pkt=0;
time=0;
}
{
if($1= ="r" && $3= ="9" && $4= ="7"){
pkt = pkt + $6;
time =$2;
}
}
END {
printf("throughput:%fMbps",(( pkt / time) * (8 / 1000000)));
}

Steps for execution:


 Open vi editor and type program. Program name should have the extension “ .tcl”
[root@localhost ~]# vi lab1.tcl
 Save the program by pressing “ESC key” first, followed by “Shift and :” key
simultaneously and type “wq” and press Enter key.
 Open vi editor and type awkprogram. Program name should have the extension “.awk”
[root@localhost ~]# vi lab1.awk
 Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
 Run the simulation program
[root@localhost~]# ns lab1.tcl
 Here “ns” indicates network simulator. We get the topology shown in the snapshot.
 Now press the play button in the simulation window and the simulation will begins.
 After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab1.awk lab1.tr
 To see the trace file contents open the file as ,
[root@localhost~]# vi lab1.t

Output:
Experiment No: 4

ETHERNET LAN USING N-NODES WITH MULTIPLE TRAFFIC

Aim: Implement Ethernet LAN using “n‟ nodes and assign multiple traffic to the nodes
and obtain congestion window for different source / destination

Theory:
Carrier Sense Multiple Access Collision Detection (CSMA/CD):
Working of the truncated binary back off algorithm In Ethernet networks, the CSMA/CD
is commonly used to schedule retransmissions after collisions. The retransmission is delayed by
an amount of time derived from the slot time and the number of attempts to retransmit.
After c collisions, a random number of slot times between 0 and 2c - 1 is chosen. For the
first collision, each sender will wait 0 or 1 slot times. After the second collision, the senders will
wait anywhere from 0 to 3 slot times (inclusive). After the third collision, the senders will wait
anywhere from 0 to 7 slot times (inclusive), and so forth. As the number of retransmission
attempts increases, the number of possibilities for delay increases exponentially.
The 'truncated' simply means that after a certain number of increases, the exponentiation
stops; i.e. the retransmission timeout reaches a ceiling, and thereafter does not increase any
further. For example, if the ceiling is set at i = 10 (as it is in the IEEE 802.3 CSMA/CD
standard), then the maximum delay is 1023 slot times. Because these delays cause other stations
that are sending to collide as well, there is a possibility that, on a busy network, hundreds of
people may be caught in a single collision set. Because of this possibility, after 16 attempts at
transmission, the process is aborted.
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:
set ns [new Simulator]
set tf [open pgm7.tr w]
$ns trace-all $tf
set nf [open pgm7.nam w]
$ns namtrace-all $nf

set n0 [$ns node]


$n0 color "magenta"
$n0 label "src1"
set n1 [$ns node]
set n2 [$ns node]
$n2 color "magenta"
$n2 label "src2"
set n3 [$ns node]
$n3 color "blue"
$n3 label "dest2"
set n4 [$ns node]
set n5 [$ns node]
$n5 color "blue"
$n5 label "dest1"

$ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/DropTail
Mac/802_3 /* should come in single line */
$ns duplex-link $n4 $n5 1Mb 1ms DropTail

set tcp0 [new Agent/TCP]


$ns attach-agent $n0 $tcp0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ftp0 set packetSize_ 500
$ftp0 set interval_ 0.0001
set sink5 [new Agent/TCPSink]

$ns attach-agent $n5 $sink5

$ns connect $tcp0 $sink5


set tcp2 [new Agent/TCP]
$ns attach-agent $n2 $tcp2
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
$ftp2 set packetSize_ 600
$ftp2 set interval_ 0.001
set sink3 [new Agent/TCPSink]

$ns attach-agent $n3 $sink3


$ns connect $tcp2 $sink3
set file1 [open file1.tr w]
$tcp0 attach $file1
set file2 [open file2.tr w]


$tcp2 attach $file2

$tcp0 trace cwnd_ /* must put underscore ( _ ) after cwnd and no space between them*/
$tcp2 trace cwnd_

proc finish { } {
global ns nftf
$ns flush-trace
close $tf
close $nf
exec nam lab3.nam &
exit 0
}
$ns at 0.1 "$ftp0 start"
$ns at 5 "$ftp0 stop"
$ns at 7 "$ftp0 start"
$ns at 0.2 "$ftp2 start"
$ns at 8 "$ftp2 stop"
$ns at 14 "$ftp0 stop"
$ns at 10 "$ftp2 start"
$ns at 15 "$ftp2 stop"
$ns at 16 "finish"
$ns run

AWK file (Open a new editor using “vi command” and write awk file and save with
“.awk” extension)

cwnd:- means congestion window

BEGIN {
}
{
if($6= ="cwnd_") /* don’t leave space after writing cwnd_ */
printf("%f\t%f\t\n",$1,$7); /* you must put \n in printf */
}
END {
}

Steps for execution:

1) Open editor and type program. Program name should have the extension “.tcl ”
2) Open editor and type awk program. Program name should have the extension “.awk ”
3) Run the simulation program
[root@localhost~]# ns lab4.tcl
 Here “ns” indicates network simulator. We get the topology shown in the snapshot.
 Now press the play button in the simulation window and the simulation will begins.
4) After simulation is completed run awk file to see the output ,

i.[root@localhost~]# awk –f lab3.awk file1.tr >a1


ii.[root@localhost~]# awk –f lab3.awk file2.tr >a2
iii.[root@localhost~]# xgraph a1 a2

5) Here we are using the congestion window trace files i.e. file1.tr and file2.tr and we are
redirecting the contents of those files to new files say a1 and a2 using outputredirection
operator (>).

6) To see the trace file contents open the file as ,

[root@localhost~]# vi lab3.tr
Experiment No: 5

SIMPLE ESS WITH WIRELESS LAN

Aim: Simulate simple ESS and with transmitting nodes in wireless LAN by simulation
and determine the performance with respect to transmission of packets.

Theory:
Wireless LAN is basically a LAN that transmits data over air, without any physical
connection between devices. The transmission medium is a form of electromagnetic radiation.
Wireless LAN is ratified by IEEE in the IEEE 802.11 standard. In most of the WLAN products
on the market based on the IEEE 802.11b technology the transmitter is designed as a Direct
Sequence Spread Spectrum Phase Shift Keying (DSSS PSK) modulator, which is capable of
handling data rates of up to 11 Mbps. The underlying algorithm used in Wireless LAN is known
as the CSMA/CA – Carrier Sense Multiple Access/Collision Avoidance algorithm.
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
6. Setup TCP Connection between n(1) and n(3)
7. Apply CBR Traffic over TCP.
8. Schedule events and run the program.

Program:
set val(chan) Channel/WirelessChannel
set val(prop) Propagation/TwoRayGround
set val(netif) Phy/WirelessPhy
set val(mac) Mac/802_11
set val(ifq) Queue/DropTail/PriQueue
set val(ll) LL
set val(ant) Antenna/OmniAntenna
set val(x) 670
set val(y) 670
set val(ifqlen) 50
set val(nn) 3
setval (rp) DSDV
set val(stop) 250
set val(traffic) cbr
set val(traffic) tcp

set ns [new Simulator]


set tf [open lab8.tr w]
$ns trace-all $tf
set topo [new Topography]
$topoload_flatgrid 1000 1000
set nf [open lab8.nam w]
$ns namtrace-all-wireless $nf 1000 1000

$ns node-config -adhocRouting DSDV \


-llType LL \
-macType Mac/802_11 \
-ifqType Queue/DropTail \
-ifqLen 50 \
-phyTypePhy/WirelessPhy \
-channelType Channel/WirelessChannel \
-prrootype Propagation/TwoRayGround \
-antType Antenna/OmniAntenna \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON

create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]

$n0 label "tcp0"


$n1 label "sink1/tcp1"
$n2 label "sink2"

$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

$ns at 0.1 "$n0 setdest 50 50 15"


$ns at 0.1 "$n1 setdest 100 100 25"
$ns at 0.1 "$n2 setdest 600 600 25"

set tcp0 [new Agent/TCP]


$ns attach-agent $n0 $tcp0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
set sink1 [new Agent/TCPSink]
$ns attach-agent $n1 $sink1
$ns connect $tcp0 $sink1

set tcp1 [new Agent/TCP]


$ns attach-agent $n1 $tcp1
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
set sink2 [new Agent/TCPSink]
$ns attach-agent $n2 $sink2
$ns connect $tcp1 $sink2

$ns at 5 "$ftp0 start"


$ns at 5 "$ftp1 start"

$ns at 100 "$n1 setdest 550 550 15"


$ns at 190 "$n1 setdest 70 70 15"
proc finish { } {
global ns nftf
$ns flush-trace
exec nam lab8.nam &
close $tf
exit 0
}
$ns at 250 "finish"
$ns run

AWK file: (Open a new editor using “vi 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")
{
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)));
}

Steps for execution:


 Open vi editor and type program. Program name should have the extension “ .tcl”
[root@localhost ~]# vi lab1.tcl
 Save the program by pressing “ESC key” first, followed by “Shift and :” key
simultaneously and type “wq” and press Enter key.
 Open vi editor and type awkprogram. Program name should have the extension “.awk”
[root@localhost ~]# vi lab1.awk
 Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
 Run the simulation program
[root@localhost~]# ns lab1.tcl
 Here “ns” indicates network simulator. We get the topology shown in the snapshot.
 Now press the play button in the simulation window and the simulation will begins.
 After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab1.awk lab1.tr
 To see the trace file contents open the file as ,
[root@localhost~]# vi lab1.tr
Experiment No: 6
Implementation of link State routing Algorithm.

Theory:
Link-state routing protocols are one of the two main classes of routing protocols used in
packet switching networks for computer communications, the other being distance-vector
routing protocols. Examples of link-state routing protocols include Open Shortest Path First
(OSPF) and Intermediate System to Intermediate System (IS-IS).
The link-state protocol is performed by every switching node in the network (i.e., nodes
that are prepared to forward packets; in the Internet, these are called routers). The basic concept
of link-state routing is that every node constructs a map of the connectivity to the network, in
the form of a graph, showing which nodes are connected to which other nodes. Each node then
independently calculates the next best logical path from it to every possible destination in the
network. Each collection of best paths will then form each node's routing table.
This contrasts with distance-vector routing protocols, which work by having each node share
its routing table with its neighbors, in a link-state protocol the only information passed between
nodes is connectivity related. Link-state algorithms are sometimes characterized informally as
each router, "telling the world about its neighbors.
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:

set ns [new Simulator]


set namfile [open s6.nam w]
$ns namtrace-all $namfile

set tracefile [open s6.tr w]


$ns trace-all $tracefile

proc finish {} {
global ns namfiletracefile
$ns flush-trace
close $namfile
close $tracefile
exec nam s6.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]

$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 $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n4 1Mb 10ms DropTail
$ns duplex-link $n2 $n4 1Mb 10ms DropTail
$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n0 $n3 orient down
$ns duplex-link-op $n1 $n2 orient left-down
$ns duplex-link-op $n1 $n4 orient down
$ns duplex-link-op $n2 $n4 orient right-down

set udp0 [new Agent/UDP]


$ns attach-agent $n0 $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n4 $null0
$ns connect $udp0 $null0

set udp1 [new Agent/UDP]


$ns attach-agent $n2 $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n4 $null0
$ns connect $udp1 $null0

$ns rtproto LS
$ns rtmodel-at 20.0 down $n1 $n4
$ns rtmodel-at 20.0 up $n1 $n4
$ns rtmodel-at 25.0 down $n2 $n4
$ns rtmodel-at 40.0 up $n2 $n4
$udp0 set class_ 1
$udp1 set class_ 2
$ns color 1 Red
$ns color 2 Green

$ns at 1.0 "$cbr0 start"


$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
$ns run

Steps for execution:


 Open vi editor and type program. Program name should have the extension “ .tcl”
[root@localhost ~]# vi lab1.tcl
 Save the program by pressing “ESC key” first, followed by “Shift and :” key
simultaneously and type “wq” and press Enter key.
 Open vi editor and type awkprogram. Program name should have the extension “.awk”
[root@localhost ~]# vi lab1.awk
 Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
 Run the simulation program
[root@localhost~]# ns lab1.tcl
 Here “ns” indicates network simulator. We get the topology shown in the snapshot.
 Now press the play button in the simulation window and the simulation will begins.
 After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab1.awk lab1.tr
 To see the trace file contents open the file as ,
[root@localhost~]# vi lab1.tr
Part B
Experiment No: 01
Aim:Write a program for a HLDC frame to perform the following.
A) Bit stuffing B) Byte Stuffing

Theory:Data link layer is responsible for something called Framing, which is the division of
stream of bits from network layer into manageable units (called frames). Each frame consists of
sender’s address and a destination address.The destination address defines where the packet is to
go and the sender’s address helps the recipient acknowledge the receipt.
Frames could be of fixed size or variable size. In fixed-size framing, there is no need for
defining the boundaries of the frames as the size itself can be used to define the end of the frame
and the beginning of the next frame. But, in variable-size framing, we need a way to define the
end of the frame and the beginning of the next frame.
To separate one frame from the next, an 8-bit (or 1-byte) flag is added at the beginning
and the end of a frame. But the problem with that is, any pattern used for the flag could also be
part of the information. So, there are two ways to overcome this problem:
1) Byte stuffing (or character stuffing)
2) Bit stuffing
Bit stuffing –
Mostly flag is a special 8-bit pattern “01111110” used to define the beginning and the end of the
frame. Problem with the flag is same as that was in case of byte stuffing. So, in this protocol what
we do is, if we encounter 0 and five consecutive 1 bits,an extra 0 is added after these bits. This
extra stuffed bit is removed from the data by the receiver.The extra bit is added after one 0
followed by five 1 bits regardless of the value of the next bit. Also, as sender side always knows
which sequence is data and which is flag it will only add this extra bit in the data sequence not in
the flag sequence.
Example:
Algorithm for Bit−Stuffing
1. Start
2. Initialize the array for transmitted stream with the special bit pattern 0111 1110
which indicates the beginning of the frame.
3. Get the bit stream to be transmitted in to the array.
4. Check for five consecutive ones and if they occur, stuff a bit 0
5. Display the data transmitted as it appears on the data line after appending 0111 1110 at the end
6. For de−stuffing, copy the transmitted data to another array after detecting the stuffed bits
7. Display the received bit stream
8. Stop

Program :

#include<stdio.h>
#include<string.h>
void main()
{

inti,j,count=0;
char str[100],dest[100]="";
//clrscr();
printf("enter the bit string: ");
gets(str);
for(i=0;i<strlen(str);)
{

count=0;
for (j=i;j<(i+5)&&str[j]!='\0';j++)
{
if(str[j]=='1')
{
count++;
}
}
if (count==5)
{
strcat(dest,"111110");
i=i+5;
}
else
{
char temp[2];
temp[0]=str[i];
temp[1]='\0';
strcat(dest,temp);
i++;
}
}
printf("after stuffing\n");
puts(dest);

}
Steps for execution:
 Open vi editor and type program. Program name should have the extension “ .c ”
[root@localhost ~]# vi lab1.c
 Save the program by pressing “ESC key” first, followed by “Shift and :” key
simultaneously and type “wq” and press Enter key.
 Run the simulation program
[root@localhost~]# cc lab1.c
[root@localhost~]# ./a.out

Output:
Byte Stuffing:
Theory:
A byte (usually escape character (ESC)), which has a predefined bit pattern is added to the data
section of the frame when there is a character with the same pattern as the flag. Whenever the
receiver encounters the ESC character, it removes from the data section and treats the next character
as data, not a flag.But problem arises when text contains one or more escape characters followed by
a flag. To solve this problem, the escape characters that are part of the text are marked by another
escape character i.e., if the escape character is part of the text,an extra one is
added to show that the second one is part of the text.
Example:

Algorithm for Character stuffing


1. Start
2. Append DLE STX at the beginning of the string
3. Check the data if character is present; if character DLE is present in the string
(example DOODLE) insert another DLE in the string (ex: DOODLEDLE)
4. Transmit DLE ETXat the end of the string
5. Display the string
6. Stop
Algorithm for Character De−stuffing
1. Start
2. Neglect initial DLE STX
3. If DLE is present in the text, ngelect it; if another DLE follows, copy the same to output.
4. Neglect the trailing DLE ETX
5. Stop
Program:

#include<stdio.h>
#include<string.h>
int main()
{

char str [50],dest[50]="";


int i;

printf("enter the character string: ");


gets(str);
printf("\n original data:\n");
puts(str);
strcat(dest,"dlestx");
for (i=0;i<strlen(str);)
{
if ((str[i]=='d'&&str[i+i]=='1'&&str[i+2]=='e'))
{
strcat(dest,"dledle");
i=i+3;
}
else
{
char temp[2];
temp[0]=str[i];
temp[1]='\0';
strcat (dest,temp);
i++;;
}
}
strcat(dest,"dleetx");
printf("\nstuffed data: \n");
puts(dest);

getchar();
}
Steps for execution:
 Open vi editor and type program. Program name should have the extension “ .c ”
[root@localhost ~]# vi lab1.c
 Save the program by pressing “ESC key” first, followed by “Shift and :” key
simultaneously and type “wq” and press Enter key.
 Run the simulation program
[root@localhost~]# cc lab1.c
[root@localhost~]# ./a.out

Output:
Experiment No: 02
Aim:Write a program for distance vector algorithm to find the suitable path
for transmission
Theory:
Distance Vector Routing is one of the routing algorithms used in a Wide Area Network for
computing shortest path between source and destination. The router is one of the main devices used
in a wide area network. The main task of the router is routing. It forms the routing table and
delivers the packets depending upon the routes in the table – either directly or via an intermediate
device (perhaps another router). Each router initially has information about its all neighbors (i.e., it
is directly connected). After a period of time, each router exchanges its routing table among its
neighbors. After certain number of exchanges, all routers will have the full routing information
about the area of the network. After each table exchange, router re-computes the shortest path
between the routers. The algorithm used for this routing is called Distance Vector Routing.
Algorithm:
Repeat the following steps until there is no change in the routing table for all routers.
1) Take the Next Router routing table and its neighbor routing table.
2) Add the router entry that is not in your own routing table, but exists in any one of the
3) Other routing tables. If the new router entry exists in more than one neighbor, then find the
minimum cost among them. The minimum cost value details are taken as a new entry: such as
source router, intermediate router, destination router and cost value, etc.
4) Update the source router routing table cost value if both the destination router and
theintermediate router field value have the same value as any one of the neighbors‟ routing
entry.
5) Update the source router‟s routing table entry with the new advertised one if the
intermediate router value in the source table is not same, but the cost value is greater than
the its neighbor‟s entry.
6) Write the next stage of routing table into the file.
Program:
#include<stdio.h>
struct node
{
unsigned dist[20];
unsigned from[20];
}
rt[10];
int main()
{
Int costmat[20][20];
intnodes,i,j,k,count=0;
printf("\n Enter the number of nodes : ");
scanf("%d",&nodes);
printf("\n Enter 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++)
for(k=0;k<nodes;k++)
if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
}
}
while (count!=0);
for(i=0;i<nodes;i++)
{
printf("\n\nFor 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");

}
Steps for execution:
 Open vi editor and type program. Program name should have the extension “ .c ”
[root@localhost ~]# vi lab1.c
 Save the program by pressing “ESC key” first, followed by “Shift and :” key
simultaneously and type “wq” and press Enter key.
7) Run the simulation program
[root@localhost~]# cc lab1.c
[root@localhost~]# ./a.out

Output:
Experiment No: 03
Aim: Implement Dijkstras algorithm to compute the shortest path.
Theory:
Given a graph and a source vertex in the graph, find shortest paths from source to all
vertices in the given graph.
Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like
Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We maintain two
sets, one set contains vertices included in shortest path tree, and other set includes vertices not
yet included in shortest path tree. At every step of the algorithm, we find a vertex which is in the
other set (set of not yet included) and has a minimum distance from the source.
Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a
single source vertex to all other vertices in the given graph
Algorithm
1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest
path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this
set is empty.
2) Assign a distance value to all vertices in the input graph. Initialize all distance values
as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first.
3) While sptSet doesn’t include all vertices
a) Pick a vertex u which is not there in sptSet and has minimum distance value.
b) Include u to sptSet.
c) Update distance value of all adjacent vertices of u. To update the distance values,
iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u
(from source) and weight of edge u-v, is less than the distance value of v, then update the
distance value of v
Let us understand with the following example:

The set sptSet is initially empty and distances assigned to vertices are {0, INF, INF, INF,
INF, INF, INF, INF} where INF indicates infinite. Now pick the vertex with minimum distance
value. The vertex 0 is picked, include it in sptSet. So sptSet becomes {0}. After including 0 to
sptSet, update distance values of its adjacent vertices. Adjacent vertices of 0 are 1 and 7. The
distance values of 1 and 7 are updated as 4 and 8. Following subgraph shows vertices and their
distance values, only the vertices with finite distance values are shown. The vertices included
in SPT are shown in green colour.
Pick the vertex with minimum distance value and not already included in SPT (not in
sptSET). The vertex 1 is picked and added to sptSet. So sptSet now becomes {0, 1}. Update the
distance values of adjacent vertices of 1. The distance value of vertex 2 becomes 12.

Pick the vertex with minimum distance value and not already included in SPT (not in
sptSET). Vertex 7 is picked. So sptSet now becomes {0, 1, 7}. Update the distance values of
adjacent vertices of 7. The distance value of vertex 6 and 8 becomes finite (15 and 9
respectively).

Pick the vertex with minimum distance value and not already included in SPT (not in
sptSET). Vertex 6 is picked. So sptSet now becomes {0, 1, 7, 6}. Update the distance values of
adjacent vertices of 6. The distance value of vertex 5 and 8 are updated.

We repeat the above steps until sptSet doesn’t include all vertices of given graph.
Finally, we get the following Shortest Path Tree (SPT).
58
Program:
#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 //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++;
}

//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);
}
}

Steps for execution:


 Open vi editor and type program. Program name should have the extension “ .c ”
[root@localhost ~]# vi lab1.c
 Save the program by pressing “ESC key” first, followed by “Shift and :” key
simultaneously and type “wq” and press Enter key.
8) Run the simulation program
[root@localhost~]# cc lab1.c
[root@localhost~]# ./a.out

Output:
Experiment: 04
Aim: For the given data, use CRC-CCITT polynomial to obtain CRC code.
Verify the program for the cases
a) Without error
b) With error

Theory:
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 are used.
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 method you learned when you 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 the same:
9) The message bits are appended with c zero bits; this augmented message is the dividend
10) A predetermined c+1-bit binary sequence, called the generator polynomial, is the divisor
11) The checksum is the c-bit remainder that results from the division operation

Error detection with CRC


Consider a message represented by the polynomial M(x)
Consider a generating polynomial G(x) This is used to generate a CRC = C(x) to be appended
to M(x). Note this G(x) is prime.
Algorithm:
1. Multiply M(x) by highest power in G(x). i.e. Add So much zeros to M(x).

2. Divide the result by G(x). The remainder = C(x). Special case: This won't work if bit-string
=all zeros. We don't allow such an M(x).But M(x) bit-string = 1 will work, for example. Can
divide 1101 into 1000.
3. If: x div y gives remainder c that means: x = n y + c Hence (x-c) = n y (x-c) div y
gives remainder 0 Here (x-c) = (x+c) Hence (x+c) div y gives remainder 0
4. Transmit: T(x) = M(x) + C(x)
5. Receiver end: Receive T(x). Divide by G(x), should have remainder 0.

Program :
#include<stdio.h>
#include<string.h>
#define N strlen(g)

char t[128],cs[128],g[]="1101";
inta,e,c;
void xor()
{
for(c=1;c<N;c++)
cs[c]=((cs[c]==g[c])?'0':'1');
}

void crc()
{
for(e=0;e<N;e++)
cs[e]=t[e];
do{
if(cs[0]=='1')
xor();
for(c=0;c<N-1;c++)
{
cs[c]=cs[c+1];
}
cs[c]=t[e++];
}
while(e<=a+N-1);
}
void main()
{
printf("\nEnter the polynomial:");
scanf("%s",t);
printf("\nGenerator polynomial is:%s",t);
a=strlen(t);
for(e=a;e<a+N;e++)
t[e]='0';
printf("\nModified t[u] is:%s",t);
crc();
printf("\nChecksum is:%s",cs);
for(e=a;e<a+N-1;e++)
t[e]=cs[e-a];
printf("\nFinalcodeword is:%s",t);
printf("\nTest error detection 0(yes) 1(no) ?:");
scanf("%d",&e);
if(e==0)
{
printf("enter the position where the error is to be insertend:");
scanf("%d",&e);
e=e-1;
t[e]=(t[e]=='0')?'1':'0';
printf("Errorneous data: %s\n",t);
}

crc();
for(e=0;(e<N-1)&&(cs[e]!='1');e++);
if(e<N-1==1)
printf("Error detected.");
else
printf("No Error detected.");
}
Steps for execution:
 Open vi editor and type program. Program name should have the extension “ .c ”
[root@localhost ~]# vi lab1.c
 Save the program by pressing “ESC key” first, followed by “Shift and :” key
simultaneously and type “wq” and press Enter key.
12) Run the simulation program
[root@localhost~]# cc lab1.c
[root@localhost~]# ./a.out

Output
Experiment 05:
Aim: Write a program for congestion control using leaky bucket algorithm.
Theory:
The main concept of the leaky bucket algorithm is that the output data flow remains
constant despite the variant input traffic, such as the water flow in a bucket with a small hole at
the bottom. In case the bucket contains water (or packets) then the output flow follows a
constant rate, while if the bucket is full any additional load will be lost because of spillover. In
a similar way if the bucket is empty the output will be zero. From network perspective, leaky
bucket consists of a finite queue (bucket) where all the incoming packets are stored in case
there is space in the queue, otherwise the packets are discarded. In order to regulate the output
flow, leaky bucket transmits one packet from the queue in a fixed time (e.g. at every clock
tick). In the following figure we can notice the main rationale of leaky bucket algorithm, for
both the two approaches (e.g. leaky bucket with water (a) and with packets (b)).

Fig: The leaky bucket traffic shaping algorithm


While leaky bucket eliminates completely bursty traffic by regulating the incoming data
flow its main drawback is that it drops packets if the bucket is full. Also, it doesn’t take into
account the idle process of the sender which means that if the host doesn’t transmit data for
some time the bucket becomes empty without permitting the transmission of any packet.
Implementation Algorithm:
Steps:
1. Read the Data for Packets
2. Read the Queue Size
3. Divide the Data into Packets
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 into Queue
b. if (clock % 5 == 0 )
i. Remove packet from Queue
6. End

Program :
#include<stdio.h>
#include<string.h>
#include<time.h>
void main()
{
int a[5],buck_rem=0,buck_cap=0,rate=0,i,sent,recv;

printf("\n enter the bucket capacity \n");


scanf("%d",&buck_cap);
printf("enter the rate of transission \n");
scanf("%d",&rate);
srand(time(NULL));
for(i=0;i<5;i++)
a[i]=rand()%80+1;
printf("CLOCK PKT_SIZE RECEIVED SENT REMAINING \n");
for (i=0;i<5;i++)
{
if((buck_rem+a[i])>buck_cap)
recv=-1;
else
{
recv=a[i];
buck_rem=buck_rem+a[i];
}

if(buck_rem!=0)
{
sleep(1);
if(buck_rem<rate)
{
sent=buck_rem;
buck_rem=0;
}
else
{
sent=rate;
buck_rem=buck_rem-rate;
}
}
else
sent=0;
if(recv==-1)
printf("\n%d\t%d\t[d]\t%d\t%d\t\n",i,a[i],sent,buck_rem);
else
printf("\n%d\t%d\t%d\t%d\t%d\n",i,a[i],recv,sent,buck_rem);
}
}
Steps for execution:
 Open vi editor and type program. Program name should have the extension “ .c ”
[root@localhost ~]# vi lab1.c
 Save the program by pressing “ESC key” first, followed by “Shift and :” key
simultaneously and type “wq” and press Enter key.
13) Run the simulation program
[root@localhost~]# cc lab1.c
[root@localhost~]# ./a.out

Output
Experiment: 06

Aim:Implementation of stop and wait protocol and sliding window protocol


Theory:

Characteristics
Used in Connection-oriented communication.
It offers error and flow control
It is used in Data Link and Transport Layers
Stop and Wait ARQ mainly implements Sliding Window Protocol concept with Window Size 1
Useful Terms:
Propagation Delay: Amount of time taken by a packet to make a physical journey from one
router to another router.
Propagation Delay = (Distance between routers) / (Velocity of propagation)
RoundTripTime (RTT) = 2* Propagation
Delay TimeOut (TO) = 2* RTT
Time To Live (TTL) = 2* TimeOut. (Maximum TTL is 180 seconds)
Working of Stop and Wait ARQ:
1) Sender A sends a data frame or packet with sequence number 0.
2) Receiver B, after receiving data frame, sends and acknowledgement with sequence number 1
(sequence number of next expected data fram e or packet) There is only one bit sequence number that
implies that both sender and receiver have buffer for one frame or packet only.

Characteristics of Stop and Wait ARQ:

It uses link between sender and receiver as half duplex


link Throughput = 1 Data packet/frame per RTT
If Bandwidth*Delay product is very high, then stop and wait protocol is not so useful. The
sender has to keep waiting for acknowledgements before sending the processed next packet.
It is an example for “Closed Loop OR connection oriented “ protocols
It is an special category of SWP where its window size is 1
Irrespective of number of packets sender is having stop and wait protocol requires only 2
sequence numbers 0 and 1
The Stop and Wait ARQ solves main three problems, but may cause big performance issues as
sender always waits for acknowledgement even if it has next packet ready to send. Consider a
situation where you have a high bandwidth connection and propagation delay is also high (you are
connected to some server in some other country though a high speed connection). To solve this
problem, we can send more than one packet at a time with a larger sequence numbers. We will be
discussing these protocols in next articles.
So Stop and Wait ARQ may work fine where propagation delay is very less for example
LAN connections, but performs badly for distant connections like satellite connection.
Implementation of Stop and wait protocol and sliding window protocol

Stop and wait protocol

CODING:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{ int
i,j,noframes,x,x1=10,x2;
clrscr(); for(i=0;i<200;i++)
rand();
noframes=rand()/2200;
i=1;
j=1;
noframes = noframes / 8;
printf("\n number of frames is
%d",noframes); getch();
while(noframes>0)
{
printf("\nsending frame
%d",i); srand(x1++);
x = rand()%10;
if(x%2 == 0)
{
for (x2=1; x2<2; x2++)
{
printf("waiting for %d seconds\n",
x2); sleep(x2);
}
printf("\nsending frame
%d",i); srand(x1++);
x = rand()%10;

}
printf("\nack for frame %d",j);
noframes-=1;
i++;
j++;
}
printf("\n end of stop and wait protocol");
getch();
}
OUTPUT:
No of frames is 6
Sending frame 1
Acknowledgement for frame 1
Sending frame 2
Acknowledgement for frame 2
Sending frame 3
Acknowledgement for frame 3
Sending frame 4
Acknowledgement for frame 4
Sending frame 5
Waiting for 1 second
Retransmitting frame 5
Acknowledgement for frame 5
Sending frame 6
Waiting for 1 second
Sending frame 6
Acknowledgement for frame 6
End of stop and wait protocol

sliding window protocol

CODING:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{ int temp1,temp2,temp3,temp4,i,winsize=8,noframes,moreframes;
char c;
int reciever(int); int simulate(int);
clrscr();
temp4=0,temp1=0,temp2=0,temp3=0;
for(i=0;i<200;i++)
rand();
noframes=rand()/200;
printf("\n number of frames is
%d",noframes); getch();
moreframes=noframes;
while(moreframes>=0)
{ temp1=simulate(winsize);
winsize-=temp1;
temp4+=temp1;
if(temp4 >noframes)
temp4 = noframes;
for(i=temp3+1;i<=temp4;i++)
printf("\nsending frame %d",i);
getch();

temp2=reciever(temp1);
temp3+=temp2;
if(temp3 > noframes)
temp3 = noframes;
printf("\n acknowledgement for the frames up to %d",temp3);
getch();
moreframes-=temp2;
temp4=temp3;
if(winsize<=0)
winsize=8;
}
printf("\n end of sliding window protocol");
getch();
} int reciever(int
temp1) { int i;
for(i=1;i<100;i++)
rand(); i=rand()
%temp1; return i;
} int simulate(int winsize)
{ int temp1,i;
for(i=1;i<50;i++)
temp1=rand();
if(temp1==0)
temp1=simulate(winsize);
i = temp1%winsize;
if(i==0)
return
winsize; else
return temp1%winsize;
}

OUTPUT:
Number of frames: 55
Sending frame 1
Sending frame 2
Sending frame 3
Acknowledgement for the frames upto 0
Sending frame 1
Acknowledgement for the frames upto 0
Sending frame 1
Sending frame 3Sending frame 4
Acknowledgement for the frames upto 4
Acknowledgement for the frames upto 54
Sending frame 55
Acknowledgement for the frames upto 55
End of sliding window protocol

You might also like