CCN Lab1 Manual Doc File NEW
CCN Lab1 Manual Doc File NEW
K’S
To get some exposure to one of the most useful tools in Network research and development.
Choose suitable tools to model a network and understand the protocols at various OSI
reference levels.
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.
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.
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.
8. Do not download or install software without the assistance of the laboratory technician.
NETWORKS LABORATORY
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.
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
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:
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
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
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.
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
ALGORITHM:
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
global ns nftf
$ns flush-trace /* clears trace file contents */
close $nf
close $tf
exec nam lab1.nam &
exit 0
}
$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); }
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:
Program:
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:
Program:
set ns [new Simulator]
set tf [open lab5.tr w]
$ns trace-all $tf
$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 nftf
$ns flush-trace
close $nf
close $tf
exec nam lab5.nam &
exit 0
}
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)));
}
Output:
Experiment No: 4
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:
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
$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
‘
$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)
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 {
}
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 ,
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 (>).
[root@localhost~]# vi lab3.tr
Experiment No: 5
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:
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
create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
$n0 set X_ 50
$n0 set Y_ 50
$n0 set Z_ 0
$n1 set X_ 100
$n1 set Y_ 100
$n1 set Z_ 0
$n2 set X_ 600
$n2 set Y_ 600
$n2 set Z_ 0
AWK file: (Open a new editor using “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)));
}
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:
Program:
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 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
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:
#include<stdio.h>
#include<string.h>
int main()
{
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
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]);
return 0;
}
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
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;
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}
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
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)).
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;
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
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.
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
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