Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
80% found this document useful (5 votes)
6K views

Computer Networks Lab Manual-17ECL68

This document is a laboratory manual for the subject of Computer Networks at M S Palya, AmbhaBhavani Temple Road, Bengaluru-97. It was prepared by Prof. K.EZHILARASAN and Prof. SOWNDESWARI S for the Department of Electronics and Communication Engineering. The manual describes the course objectives, experiments to be performed using network simulation tools and programming in C/C++, expected outcomes, and guidelines for practical examinations. It includes topics such as point-to-point networks, Ethernet LAN, routing algorithms, data encoding, and congestion control.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
80% found this document useful (5 votes)
6K views

Computer Networks Lab Manual-17ECL68

This document is a laboratory manual for the subject of Computer Networks at M S Palya, AmbhaBhavani Temple Road, Bengaluru-97. It was prepared by Prof. K.EZHILARASAN and Prof. SOWNDESWARI S for the Department of Electronics and Communication Engineering. The manual describes the course objectives, experiments to be performed using network simulation tools and programming in C/C++, expected outcomes, and guidelines for practical examinations. It includes topics such as point-to-point networks, Ethernet LAN, routing algorithms, data encoding, and congestion control.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

M S Palya, AmbhaBhavani Temple Road, Bengaluru-97

(Affiliated to VTU, Belagavi, Recognized by the AICTE, New Delhi)

COMPUTER NETWORKS LABORATORY MANUAL


Subject Code: 17ECL68

B.E. VI Semester

[As per Choice Based Credit System (CBCS) scheme]

Prepared by
Prof. K.EZHILARASAN
&
Prof. SOWNDESWARI S

DEPARTMENT OF ELECTRONICS AND COMMUNICATION


ENGINEERING
2019-2020
COMPUTER NETWORKS LABORATORY 2019

(Affiliated to VTU, Belagavi, Recognized by the AICTE, New Delhi)

DEPARTMENT OF ELECTRONICS AND COMMUNICATION


ENGINEERING

COMPUTER NETWORKS LABORATORY


B.E., VI Semester, Electronics & Communication Engineering
[As per Choice Based Credit System (CBCS) scheme]

Subject Code: 17ECL68


IA Marks: 40 Exam Marks: 100 Exam Hours: 03

Number of Lecture 01Hour Tutorial (Instructions) + 02 Hours Laboratory =


Hours/Week 03

Course objectives: This course will enable students to:

 Choose suitable tools to model a network and understand the protocols at various OSI
reference levels.
 Design a suitable network and simulate using a Network simulator tool.
 Simulate the networking concepts and protocols using C/C++ programming.
 Model the networks for different configurations and analyze the results.

Dept. of ECE, SaIT, Bengaluru Page 2


COMPUTER NETWORKS LABORATORY 2019

LABORATORY EXPERIMENTS

PART-A: Simulation experiments using NS2/ NS3/ OPNET/ NCTUNS/ NetSim / QualNet /
Packet Tracer or any other equivalent tool.

1. Implement a point to pint network with four nodes and duplex links between them.
Analyze the network performance by setting the queue size and varying the bandwidth.
2. Implement a four node point to point network with links n0-n2, n1-n2 and n2-n3. Apply
TCP agent between n0-n3 and UDP between n1-n3. Apply relevant applications over
TCP and UDP agents changing the parameter and determine the number of packets sent
by TCP/UDP.
3. Implement Ethernet LAN using n (6-10) nodes. Compare the throughput by changing the
error rate and data rate.
4. Implement Ethernet LAN using n nodes and assign multiple traffic to the nodes and
obtain congestion window for different sources/ destinations.
5. Implement ESS with transmission nodes in Wireless LAN and obtain the performance
parameters.
6. Implementation of Link state routing algorithm.

PART-B: Implement the following in C/C++.

1. Write a program for a HLDC frame to perform the following. i) Bit stuffing ii) Character
stuffing.
2. Write a program for distance vector algorithm to find suitable path for transmission.
3. Implement Dijkstra’s algorithm to compute the shortest routing path.
4. For the given data, use CRC-CCITT polynomial to obtain CRC code. Verify the program
for the cases: i) Without error ii) With error.
5. Implementation of Stop and Wait Protocol and Sliding Window Protocol.
6. Write a program for congestion control using leaky bucket algorithm.

Dept. of ECE, SaIT, Bengaluru Page 3


COMPUTER NETWORKS LABORATORY 2019

Course outcomes: On the completion of this laboratory course, the students will be able to:

 Design and Simulate Network elements with various protocols and standards.
 Use the network simulator tools for learning and practice of networking algorithms.
 Demonstrate the working of various protocols and algorithms using C programming.

Graduate Attributes (as per NBA)

 Engineering Knowledge.
 Problem Analysis.
 Design/Development of solutions.

Conduct of Practical Examination:


1. All laboratory experiments are to be included for practical examination.
2. For examination one question from software and one question from hardware or only one
hardware experiments based on the complexity to be set.
3. Students are allowed to pick one experiment from the lot.
4. Strictly follow the instructions as printed on the cover page of answer script for breakup
of marks.
5. Change of experiment is allowed only once and 15% Marks allotted to the procedure part
to be made zero.

Dept. of ECE, SaIT, Bengaluru Page 4


COMPUTER NETWORKS LABORATORY 2019

OSI MODEL

Group Layer Layer Description


Number Name
Top Layers 7 Application Provide user interface to send and receive the data
6 Presentation Encrypt, format and compress the data for
transmission
5 Session Initiate and terminate session with remote system
Bottom 4 Transport Break data stream in smaller segments and provide
Layers reliable and unreliable data delivery
3 Network Provide logical addressing
2 Data Link Prepare data for transmission
1 Physical Move data between devices

Dept. of ECE, SaIT, Bengaluru Page 5


COMPUTER NETWORKS LABORATORY 2019

Computer Networks and the Layering Concept:

A computer network is usually defined as a collection of computers interconnected for gathering,


processing, and distributing information. Computer is used as a broad term here to include
devices such as workstations, servers, routers, modems, base stations, wireless extension points,
etc. These computers are connected by communications links such as copper cables, fiber
optic cables, and microwave/satellite/radio links. A computer network can be built as a nesting
and/or interconnection of several networks. The Internet is a good example of computer
networks. In fact, it is a network of networks, within which, tens of thousands of networks
interconnect millions of computers worldwide.
Layering Concept:
A computer network is a complex system. To facilitate design and flexible implementation of
such a system, the concept of layering is introduced. Using a layered structure, the functionalities
of a computer network can be organized as a stack of layers. There is a peer-to-peer relationship
(or virtual link) between the corresponding layers in two communicating nodes. However, actual
data flow occurs in a vertical fashion – from the highest layer to the lowest layer in a node, and
then through the physical link to reach the lowest layer at the other node, and then following
upwards to reach the highest layer in the stack. Each layer represents a well-defined and specific
part of the system and provides certain services to the above layer. Accessible (by the upper
layers) through so-called interfaces, these services usually define what should be done in terms
of network operations or primitives, but does not specifically define how such things are
implemented. The details of how a service is implemented is defined in a so-called protocol. For
example, the transmitter at a source computer can use a specific protocol (e.g., a data encoding
scheme) at the physical layer to transmit information bits to the receiving computer, which
should be able to decode the received information based on the protocol rules. The beauty of this
layering concept is the layer independency. That is, a change in a protocol of a certain layer does
not affect the rest of the system as long as the interfaces remain unchanged. Here, we highlight
the words services, protocol, and interface to emphasize that it is the interaction among these
components that makes up the layering concept. Figure 1.1 graphically shows an overall view of
the layering concept used for communication between two computer hosts: a source host and a
destination host. In this figure, the functionality of each computer host is divided into four

Dept. of ECE, SaIT, Bengaluru Page 6


COMPUTER NETWORKS LABORATORY 2019

layers.1 When virtually linked with the same layer on another host, these layers are called
peers.2 Although not directly connected to each other, these peers virtually communicate with
one another using a protocol represented by an arrow. As has already been mentioned, the actual
communication needs to propagate down the stack and use the above layering concept.

Suppose an application process running on Layer 4 of the source generates data or messages
destined for the destination. The communication starts by passing a generated message M down
to Layer 3, where the data are segmented into two chunks (M1 and M2), and control information
called header (H3) specific to Layer 3 is appended to M1 and M2. The control information are,
for example, sequence numbers, packet sizes, and error checking information. These information
are understandable and used only by the peering layer on the destination to recover the data (M).
The resulting data (e.g., H3+M1) is handed to the next lower layer, where some protocol-specific
control information are again added to the message. This process continues until the message
reaches the lowest layer, where transmission of information is actually performed over a physical
medium. Note that, along the line of these processes, it might be necessary to further segment the
data from upper layers into smaller segments for various purposes. When the message reaches
the destination, the reverse process takes place. That is, as the message is moving up the stack,
its headers are ripped off layer by layer. If necessary, several messages are put together before

Dept. of ECE, SaIT, Bengaluru Page 7


COMPUTER NETWORKS LABORATORY 2019

being passed to the upper layer. The process continues until the original message (M) is
recovered at Layer 4.

OSI and TCP/IP Reference Models:

The OSI (Open Systems Interconnection) model was the first reference model developed by ISO
(International Standards Organization) to provide a standard framework in order to describe the
protocol stacks in a computer network. Its consists of seven layers where each layer is intended
to perform a well-defined function. These are physical layer, data link layer, network layer,
transport layer, session layer, presentation layer, and application layer. The OSI model only
specifies what each layer should do; it does not specify the exact services and protocols to be
used in each layer. Although not implemented in current systems, the OSI model philosophy
(i.e., the layering concept) lays a strong foundation for further development in computer
networking.

The TCP (Transmission Control Protocol)/IP (Internet Protocol) reference model, which is based
on the two primary protocols, namely, TCP and IP, is used in the current Internet. These
protocols have proven very powerful, and as a result, have experienced widespread use and
implementation in the existing computer networks. It was developed for ARPANET, a research
network sponsored by the U.S. Department of Defense, which is considered as the grandparent
of all computer networks. In the TCP/IP model, the protocol stack consists of five layers –
physical, data link, network, transport, and application – each of which is responsible for certain
services as will be discussed shortly. Note that the application layer in the TCP/IP model can be
considered as the combination of session, presentation, and application layers of the OSI model.

Application Layer
The application layer sits on top of the stack, and uses services from the transport layer
(discussed below). This layer supports several higher-level protocols such as HTTP (Hypertext
Transfer Protocol) for World Wide Web applications, SMTP (Simple Mail Transfer Protocol) for
electronic mail, TELNET for remote virtual terminal, DNS (Domain Name Service) for mapping
comprehensible host names to their network addresses, and FTP (File Transfer Protocol) for file
transfer.

Dept. of ECE, SaIT, Bengaluru Page 8


COMPUTER NETWORKS LABORATORY 2019

Transport Layer

The objective of a transport layer is to transport the messages from the application layer of the
source host to that of the destination host. To accomplish this goal, two well-known protocols,
namely, TCP and UDP (User Datagram Protocol), are defined in this layer. While TCP is
responsible for a reliable and connection-oriented communication between the two hosts, UDP
supports an unreliable connectionless transport. TCP is ideal for applications that prefer accuracy
over prompt delivery and the reverse is true for UDP. Generally, control information related to
low control and error control need to be embedded into the messages. Also, before adding any
header, fragmentation is usually performed to break a long message into segments. For this
reason, the protocol data units in this layer are normally called segments.

Network Layer

This layer provides routing services to the transport layer. Network layer is designed to deliver
the data units, usually called packets, along the paths they are meant to traverse from a source
host to a destination host. Again, to facilitate routing, headers containing information such as
source and destination network addresses are added to the transport protocol data units to
formulates network-layer data unit.

Link Layer

The packets are generally routed through several communication links and nodes before they
actually reach the destination node. To successfully route these packets all the way to the
destination, a mechanism is required for node to-node delivery across each of the communication
links. A link layer protocol is responsible for data delivery across a communication link.
A link layer protocol has three main responsibilities. First, flow control regulates the
transmission speed in a communication link. Secondly, error control ensures the integrity of data
transmission. Thirdly, flow multiplexing/demultiplexing combines multiple data flows into and
extracts data flows from a communication link. Choices of link layer protocols may vary from
host to host and network to network. Examples of widely-used link layer protocols/technologies
include Ethernet, Point-to-Point Protocol (PPP), IEEE 802.11 (i.e., WiFi), and Asynchronous

Dept. of ECE, SaIT, Bengaluru Page 9


COMPUTER NETWORKS LABORATORY 2019

Transfer Mode (ATM).


Physical Layer

The physical layer deals with the transmission of data bits across a communication link. Its
primary goal is to ensure that the transmission parameters (e.g., transmission power, modulation
scheme) are set appropriately to achieve the required transmission performance (e.g., to achieve
the target bit error rate performance). Finally, we point out that the five layers discussed above
are common to the OSI layer. As has already been mentioned, the OSI model contains two other
layers sitting on top of the transport layer, namely, session and presentation layers. The session
layer simply allows users on different computers to create communication sessions among
themselves. The presentation layer basically takes care of different data presentations existing
across the network. For example, a unified network management system gathers data with
different format from different computers and converts their format into a uniform format.

Dept. of ECE, SaIT, Bengaluru Page 10


COMPUTER NETWORKS LABORATORY 2019

Introduction to NS-2:
 Widely known as NS2, is simply an event driven simulation tool.
 Useful in studying the dynamic nature of communication networks.
 Simulation of wired as well as wireless network functions and protocols (e.g., routing
algorithms, TCP, UDP) can be done using NS2.
 In general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviors.

Basic Architecture of NS2

Tcl scripting
• Tcl is a general purpose scripting language. [Interpreter]
• Tcl runs on most of the platforms such as Unix, Windows etc...
• The strength of Tcl is its simplicity.
• It is not necessary to declare a data type for variable prior to the usage.
Basics of TCL
Syntax: command arg1 arg2 arg3
 Hello World!
puts stdout{Hello, World!}
Hello, World!
 Variables Command Substitution
set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]

Dept. of ECE, SaIT, Bengaluru Page 11


COMPUTER NETWORKS LABORATORY 2019

 Simple Arithmetic
expr 7.2 / 4
 Procedures
proc Diag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
return $c }
puts “Diagonal of a 3, 4 right triangle is [Diag 3 4]”
Output: Diagonal of a 3, 4 right triangle is 5.0
 Loops
while{$i < $n} { for {set i 0} {$i < $n} {incr i} {
... ...
} }
Wired TCL Script Components
 Create the event scheduler.
 Open new files & turn on the tracing.
 Create the nodes.
 Setup the links.
 Configure the traffic type (e.g., TCP, UDP, etc).
 Set the time of traffic generation (e.g., CBR, FTP).
 Terminate the simulation.
NS Simulator Preliminaries
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and applications.
4. The nam visualization tool.
5. Tracing and random variables.
Initialization and Termination of TCL Script in NS-2
An ns simulation starts with the command

set ns [new Simulator]

Dept. of ECE, SaIT, Bengaluru Page 12


COMPUTER NETWORKS LABORATORY 2019

It is the first line in the tcl script. This line declares a new variable as using the set command, you
can call this variable as you wish, In general people declares it as ns because it is an instance of
the Simulator class, so an object the code[new Simulator] is indeed the installation of the class
Simulator using the reserved word new.

In order to have output files with data on the simulation (trace files) or files used for
visualization (nam files), we need to create the files using “open” command:
#Open the Trace file set tracefile1 [open out.tr w]

$ns trace-all $tracefile1

#Open the NAM trace file


set namfile [open out.nam w]

$ns namtrace-all $namfile

The above creates a trace file called “out.tr” and a nam visualization trace file called
“out.nam”.Within the tcl script, these files are not called explicitly by their names, but instead by
pointers that are declared above and called “tracefile1” and “namfile” respectively. Remark that
they begin with a # symbol. The second line open the file “out.tr” to be used for writing, declared
with the letter “w”. The third line uses a simulator method called trace-all that have as parameter
the name of the file where the traces will go.
The last line tells the simulator to record all simulation traces in NAM input format. It
also gives the file name that the trace will be written to later by the command $ns flush-trace. In
our case, this will be the file pointed at by the pointer “$namfile”, i.e the file “out.tr”.
The termination of the program is done using a “finish” procedure.
#Define a ‘finish’ procedure
Proc finish { } {

global ns tracefile1 namfile

$ns flush-trace

Close $tracefile1

Close $namfile

Exec nam out.nam &

Exit 0

Dept. of ECE, SaIT, Bengaluru } Page 13


COMPUTER NETWORKS LABORATORY 2019

The word proc declares a procedure in this case called finish and without arguments. The
word global is used to tell that we are using variables declared outside the procedure. The
simulator method “flush-trace” will dump the traces on the respective files. The tcl command
“close” closes the trace files defined before and exec executes the nam program for visualization.
The command exit will ends the application and return the number 0 as status to the system. Zero
is the default for a clean exit. Other values can be used to say that is a exit because something
fails.
At the end of ns program we should call the procedure “finish” and specify at what time
the termination should occur. For example,
$ns at 125.0 “finish”

It will be used to call “finish” at time 125sec. This simulator allows us to schedule events
explicitly.
The simulation can then begin using the command

$ns run

Definition of a network of links and nodes


The way to define a node is

set n0 [$ns node]

The node is created which is printed by the variable n0. When we shall refer to that node in the
script we shall thus write $n0.
Once we define several nodes, we can define the links that connect them. An example of
a definition of a link is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail

Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of
propagation delay and a capacity of 10Mb per sec for each direction.
To define a directional link instead of a bi-directional one, we should replace “duplex-
link” by “simplex-link”.
In NS, an output queue of a node is implemented as a part of each link whose input is that
node. The definition of the link then includes the way to handle overflow at that queue. In our

Dept. of ECE, SaIT, Bengaluru Page 14


COMPUTER NETWORKS LABORATORY 2019

case, if the buffer capacity of the output queue is exceeded then the last packet to arrive is
dropped. Many alternative options exist, such as the RED (Random Early Discard) mechanism,
the FQ (Fair Queuing), the DRR (Deficit Round Robin), the stochastic Fair Queuing (SFQ) and
the CBQ (which including a priority and a round-robin scheduler).
In ns, an output queue of a node is implemented as a part of each link whose input is that
node. We should also define the buffer capacity of the queue related to each link. An example
would be:
#set Queue Size of link (n0-n2) to 20$ns
queue-limit $n0 $n2 20

Agents and Applications


We need to define routing (sources, destinations) the agents (protocols) the application
that use them.
FTP over TCP
TCP is a dynamic reliable congestion control protocol. It uses Acknowledgements
created by the destination to know whether packets are well received.
There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno, Vegas.
The type of agent appears in the first line:

set tcp [new Agent/TCP]

The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command
set sink [new Agent /TCPSink]

Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.
#Setup a UDP connection
set udp [new Agent/UDP]

$ns attach-agent $n1 $udp

set null [new Agent/Null]

$ns attach-agent $n5 $null

$ns connect $udp $null

$udp set fid_2

Dept. of ECE, SaIT, Bengaluru Page 15


COMPUTER NETWORKS LABORATORY 2019

#setup a CBR over UDP connection


The below shows the definition of a CBR application using a UDP agent. The command
$ns attach-agent $n4 $sink defines the destination node. The command $ns connect $tcp $sink
finally makes the TCP connection between the source and destination nodes.

set cbr [new Application/Traffic/CBR]

$cbr attach-agent $udp

$cbr set packetsize_ 100

$cbr set rate_ 0.01Mb

$cbr set random_ false

TCP has many parameters with initial fixed defaults values that can be changed if
mentioned explicitly. For example, the default TCP packet size has a size of 1000bytes.This can
be changed to another value, say 552bytes, using the command $tcp set packetSize_ 552.
When we have several flows, we may wish to distinguish them so that we can identify
them with different colors in the visualization part. This is done by the command $tcp set fid_ 1
that assigns to the TCP connection a flow identification of “1”.We shall later give the flow
identification of “2” to the UDP connection.

CBR over UDP


A UDP source and destination is defined in a similar way as in the case of TCP.
Instead of defining the rate in the command $cbr set rate_ 0.01Mb, one can define the
time interval between transmission of packets using the command.

$cbr set interval_ 0.005

The packet size can be set to some value using

$cbr set packetSize_ <packet size>

Dept. of ECE, SaIT, Bengaluru Page 16


COMPUTER NETWORKS LABORATORY 2019

Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event should occur.
The initializing command set ns [new Simulator] creates an event scheduler, and events are then
scheduled using the format:

$ns at <time> <event>

The scheduler is started when running ns that is through the command $ns run.
The beginning and end of the FTP and CBR application can be done through the following
command

$ns at 0.1 “$cbr start”

$ns at 1.0 “ $ftp start”

$ns at 124.0 “$ftp stop”

$ns at 124.5 “$cbr stop”

Structure of Trace Files


When tracing into an output ASCII file, the trace is organized in 12 fields as follows in
fig shown below, The meaning of the fields are:

1. The first field is the event type identifier. It is given by one of four possible symbols r, +, -, d
which correspond respectively to receive (at the output of the link), enqueued, dequeued and
dropped.
2. The second field gives the time at which the event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (eg CBR or TCP)
6. Gives the packet size
7. Some flags

Dept. of ECE, SaIT, Bengaluru Page 17


COMPUTER NETWORKS LABORATORY 2019

8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script one
can further use this field for analysis purposes; it is also used when specifying stream color
for the NAM display.
9. This is the source address given in the form of “node.port”.
10. This is the destination address, given in the same form.
11. This is the network layer protocol’s packet sequence number. Even though UDP
implementations in a real network do not use sequence number, ns keeps track of UDP
packet sequence number for analysis purposes
12. The last field shows the Unique id of the packet.

Example Trace File:

Dept. of ECE, SaIT, Bengaluru Page 18


COMPUTER NETWORKS LABORATORY 2019

XGRAPH
The xgraph program draws a graph on an x-display given data read from either data file
or from standard input if no files are specified. It can display upto 64 independent data sets using
different colors and line styles for each set. It annotates the graph with a title, axis labels, grid
lines or tick marks, grid labels and a legend.

Syntax:
Xgraph [options] file-name

Options are listed here


/-bd <color> (Border)
This specifies the border color of the xgraph window.
/-bg <color> (Background)
This specifies the background color of the xgraph window.
/-fg<color> (Foreground)
This specifies the foreground color of the xgraph window.
/-lf <fontname> (LabelFont)
All axis labels and grid labels are drawn using this font.
/-t<string> (Title Text)
This string is centered at the top of the graph.
/-x <unit name> (XunitText)
This is the unit name for the x-axis. Its default is “X”.
/-y <unit name> (YunitText)
This is the unit name for the y-axis. Its default is “Y”.

Awk- An Advanced

awk is a programmable, pattern-matching, and processing tool available in UNIX. It


works equally well with text and numbers.
awk is not just a command, but a programming language too. In other words, awk utility
is a pattern scanning and processing language. It searches one or more files to see if they contain

Dept. of ECE, SaIT, Bengaluru Page 19


COMPUTER NETWORKS LABORATORY 2019

lines that match specified patterns and then perform associated actions, such as writing the line to
the standard output or incrementing a counter each time it finds a match.
Syntax:
awk option ‘selection_criteria {action}’ file(s)

Here, selection_criteria filters input and select lines for the action component to act upon.
The selection_criteria is enclosed within single quotes and the action within the curly braces.
Both the selection_criteria and action forms an awk program.
Example: $ awk ‘/manager/ {print}’ emp.lst

Variables
Awk allows the user to use variables of their choice. You can now print a serial number,
using the variable kount, and apply it those directors drawing a salary exceeding 6700:
$ awk –F”|” ‘$3 == “director” && $6 > 6700 {
kount =kount+1
printf “ %3f %20s %-12s %d\n”, kount,$2,$3,$6 }’ empn.lst

THE –f OPTION: STORING awk PROGRAMS IN A FILE


You should holds large awk programs in separate file and provide them with the awk
extension for easier identification. Let’s first store the previous program in the file empawk.awk:
$ cat empawk.awk
Observe that this time we haven’t used quotes to enclose the awk program. You can now
use awk with the –f filename option to obtain the same output:

Awk –F”|” –f empawk.awk empn.lst

THE BEGIN AND END SECTIONS


Awk statements are usually applied to all lines selected by the address, and if there are no
addresses, then they are applied to every line of input. But, if you have to print something before
processing the first line, for example, a heading, then the BEGIN section can be used gainfully.
Similarly, the end section useful in printing some totals after processing is over.

Dept. of ECE, SaIT, Bengaluru Page 20


COMPUTER NETWORKS LABORATORY 2019

The BEGIN and END sections are optional and take the form
BEGIN {action}
END {action}
These two sections, when present, are delimited by the body of the awk program. You
can use them to print a suitable heading at the beginning and the average salary at the end.
BUILT-IN VARIABLES
Awk has several built-in variables. They are all assigned automatically, though it is also
possible for a user to reassign some of them. You have already used NR, which signifies the
record number of the current line. We’ll now have a brief look at some of the other variable.
The FS Variable: as stated elsewhere, awk uses a contiguous string of spaces as the default field
delimiter. FS redefines this field separator, which in the sample database happens to be the |.
When used at all, it must occur in the BEGIN section so that the body of the program knows its
value before it starts processing:
BEGIN {FS=”|”}
This is an alternative to the –F option which does the same thing.
The OFS Variable: when you used the print statement with comma-separated arguments, each
argument was separated from the other by a space. This is awk’s default output field separator,
and can reassigned using the variable OFS in the BEGIN section:
BEGIN { OFS=”~” }
When you reassign this variable with a ~ (tilde), awk will use this character for delimiting the
print arguments. This is a useful variable for creating lines with delimited fields.
The NF variable: NF comes in quite handy for cleaning up a database of lines that don’t contain
the right number of fields. By using it on a file, say emp.lst, you can locate those lines not having
6 fields, and which have crept in due to faulty data entry:
$awk ‘BEGIN {FS = “|”}
NF! =6 {
Print “Record No “, NR, “has”, “fields”}’ empx.lst

To perform simulation for TCL script by executing


>>ns myfirst_ns.tcl

Dept. of ECE, SaIT, Bengaluru Page 21


COMPUTER NETWORKS LABORATORY 2019

NS-2 Simulation:

Simulation using NS2 consists of three main steps. First, the simulation design is probably the
most important step. Here, we need to clearly specify the objectives and assumptions of the
simulation. Secondly, configuring and running simulation implements the concept designed in
the first step. This step also includes configuring the simulation scenario and running simulation.
The final step in a simulation is to collect the simulation result and trace the simulation if
necessary.

To execute awk Script:

>> awk -f lab1.awk lab1.tr

Dept. of ECE, SaIT, Bengaluru Page 22


COMPUTER NETWORKS LABORATORY 2019

PART-A
Simulation
experiments
using NS2

Dept. of ECE, SaIT, Bengaluru Page 23


COMPUTER NETWORKS LABORATORY 2019

1. Implement a point to pint network with four nodes and duplex links between them.
Analyze the network performance by setting the queue size and varying the bandwidth.

#===================================
# Simulation parameters setup
#===================================
set val(stop) 10.0; # time of simulation end

#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]

#Open the NS trace file


set tracefile [open lab1.tr w]
$ns trace-all $tracefile

#Open the NAM trace file


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

#===================================
# Nodes Definition
#===================================
#Create 4 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

#===================================
# Links Definition
#===================================

Dept. of ECE, SaIT, Bengaluru Page 24


COMPUTER NETWORKS LABORATORY 2019

#Createlinks between nodes


$ns duplex-link $n0 $n2 300.0Mb 10ms DropTail
$ns queue-limit $n0 $n2 10
$ns duplex-link $n1 $n2 400.0Mb 10ms DropTail
$ns queue-limit $n1 $n2 20
$ns duplex-link $n2 $n3 10.0Mb 10ms DropTail
$ns queue-limit $n2 $n3 3

#Give node position (for NAM)


$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right

#===================================
# Agents Definition
#===================================
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink2 [new Agent/TCPSink]
$ns attach-agent $n3 $sink2
$ns connect $tcp0 $sink2
$tcp0 set packetSize_ 1500

#Setup a TCP connection


set tcp1 [new Agent/TCP]
$ns attach-agent $n1 $tcp1
set sink3 [new Agent/TCPSink]
$ns attach-agent $n3 $sink3
$ns connect $tcp1 $sink3
$tcp1 set packetSize_ 1500

#===================================
# Applications Definition
#===================================
#Setup a FTP Application over TCP connection
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns at 1.0 "$ftp0 start"
$ns at 2.0 "$ftp0 stop"

#Setup a FTP Application over TCP connection


set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
$ns at 1.0 "$ftp1 start"
$ns at 2.0 "$ftp1 stop"

#===================================
# Termination
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace

Dept. of ECE, SaIT, Bengaluru Page 25


COMPUTER NETWORKS LABORATORY 2019

close $tracefile
close $namfile
exec nam lab1.nam &
exit 0
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Awk Script:
BEGIN{
tcppack=0
tcppack1=0
}
{
if($1=="r"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
tcppack++;
}
if($1=="d"&&$3=="2"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
tcppack1++;
}

}
END{
printf("\n total number of data packets received at Node 3: %d\n",
tcppack++);
printf("\n total number of packets dropped at Node 2: %d\n", tcppack1++);
}
Output:

Dept. of ECE, SaIT, Bengaluru Page 26


COMPUTER NETWORKS LABORATORY 2019

Network animator (lab1.nam):

Trace file (lab1.tr):

Dept. of ECE, SaIT, Bengaluru Page 27


COMPUTER NETWORKS LABORATORY 2019

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

#===================================
# Simulation parameters setup
#===================================
set val(stop) 10.0; # time of simulation end

#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]

#Open the NS trace file


set tracefile [open lab2.tr w]
$ns trace-all $tracefile

#Open the NAM trace file


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

#===================================
# Nodes Definition
#===================================
#Create 4 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

#===================================

Dept. of ECE, SaIT, Bengaluru Page 28


COMPUTER NETWORKS LABORATORY 2019

# Links Definition
#===================================
#Createlinks between nodes
$ns duplex-link $n0 $n2 200.0Mb 10ms DropTail
$ns queue-limit $n0 $n2 50
$ns duplex-link $n2 $n3 200.0Mb 10ms DropTail
$ns queue-limit $n2 $n3 50
$ns duplex-link $n1 $n2 200.0Mb 10ms DropTail
$ns queue-limit $n1 $n2 50

#Give node position (for NAM)


$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n1 $n2 orient right-up

#===================================
# Agents Definition
#===================================
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink3 [new Agent/TCPSink]
$ns attach-agent $n3 $sink3
$ns connect $tcp0 $sink3
$tcp0 set packetSize_ 1000
$tcp0 set interval_ 0.1

#Setup a UDP connection


set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1
set null2 [new Agent/Null]
$ns attach-agent $n3 $null2
$ns connect $udp1 $null2
$udp1 set packetSize_ 1100
$udp1 set interval_ 0.1
#===================================
# Applications Definition
#===================================
#Setup a FTP Application over TCP connection
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns at 1.0 "$ftp0 start"
$ns at 9.0 "$ftp0 stop"

#Setup a CBR Application over UDP connection


set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1
$cbr1 set packetSize_ 1000
$cbr1 set rate_ 1.0Mb
$cbr1 set random_ null
$ns at 1.0 "$cbr1 start"
$ns at 9.0 "$cbr1 stop"
#===================================
# Termination

Dept. of ECE, SaIT, Bengaluru Page 29


COMPUTER NETWORKS LABORATORY 2019

#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam lab2.nam &
exit 0
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Awk Script:
BEGIN{
tcppack=0
tcppack1=0
}
{
if($1=="r"&&$4=="2"&&$5=="tcp"&&$6=="340")
{
tcppack++;
}
if($1=="r"&&$4=="2"&&$5=="cbr"&&$6=="300")
{
tcppack1++;
}

}
END{
printf("\n total number of TCP data packets sent between Node 0 and Node
2: %d\n", tcppack++);
printf("\n total number of UDP data packets sent between Node 1 and Node
2: %d\n", tcppack1++);
}

Dept. of ECE, SaIT, Bengaluru Page 30


COMPUTER NETWORKS LABORATORY 2019

Output:

Network animator (lab2.nam):

Results:

Dept. of ECE, SaIT, Bengaluru Page 31


COMPUTER NETWORKS LABORATORY 2019

3. Implement Ethernet LAN using n (6-10) nodes. Compare the throughput by changing the
error rate and data rate.

set ns [new Simulator]


set tf [open lab3.tr w]
$ns trace-all $tf

set nf [open lab3.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"

$n1 label "Source/UDP"


$n3 label "Error Node"
$n7 label "Destination"

$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

Dept. of ECE, SaIT, Bengaluru Page 32


COMPUTER NETWORKS LABORATORY 2019

$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.3

# 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.1
set null [new Agent/Null]
$ns attach-agent $n7 $null

$ns connect $udp $null

proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab3.nam &
exit 0
}
$ns at 0.1 "$cbr start"
$ns at 3.0 "finish"
$ns run

Awk Script:
BEGIN{
tcppack=0
tcppack1=0
}
{
if($1=="r"&&$4=="7"&&$5=="cbr"&&$6=="1000")
{
tcppack++;
}
}
END{
printf("\n total number of data packets at Node 7: %d\n", tcppack++);

Dept. of ECE, SaIT, Bengaluru Page 33


COMPUTER NETWORKS LABORATORY 2019

Output:

Results:

Dept. of ECE, SaIT, Bengaluru Page 34


COMPUTER NETWORKS LABORATORY 2019

4. Implement Ethernet LAN using n nodes and assign multiple traffic to the nodes and
obtain congestion window for different sources/ destinations.

//setup initialization//
set ns [new Simulator]
set tf [open lab4.tr w]
$ns trace-all $tf
set nf [open lab4.nam w]
$ns namtrace-all $nf

//setup node definition//


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

//setup LAN definition//


$ns make-lan "$n0 $n1 $n2 $n3" 10mb 10ms LL Queue/DropTail Mac/802_3

// setup Agent definition//


set tcp0 [new Agent/TCP/Reno]
$ns attach-agent $n0 $tcp0
set sink3 [new Agent/TCPSink]
$ns attach-agent $n3 $sink3
set tcp2 [new Agent/TCP]
$ns attach-agent $n2 $tcp2
set sink1 [new Agent/TCPSink]
$ns attach-agent $n1 $sink1

//setup Application Agent//

set ftp0 [new Application/FTP]


$ftp0 attach-agent $tcp0
$ns connect $tcp0 $sink3
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
$ns connect $tcp2 $sink1

Dept. of ECE, SaIT, Bengaluru Page 35


COMPUTER NETWORKS LABORATORY 2019

######To trace the congestion window##########


//setup Congestion window//

set file1 [open file1.tr w]


$tcp0 attach $file1
$tcp0 trace cwnd_
#$tcp0 set maxcwnd_ 10
set file2 [open file2.tr w]
$tcp2 attach $file2
$tcp2 trace cwnd_

//Process Termination//

proc finish { } {
global nf tf ns
$ns flush-trace
exec nam lab7.nam &
close $nf
close $tf
exit 0
}
$ns at 0.1 "$ftp0 start"
$ns at 1.5 "$ftp0 stop"
$ns at 2 "$ftp0 start"
$ns at 3 "$ftp0 stop"
$ns at 0.2 "$ftp2 start"
$ns at 2 "$ftp2 stop"
$ns at 2.5 "$ftp2 start"
$ns at 4 "$ftp2 stop"
$ns at 5.0 "finish"

$ns run

Awk Script:
BEGIN{
tcppack=0
tcppack1=0
}
{
if($1=="r"&&$4=="7"&&$5=="cbr"&&$6=="1000")
{
tcppack++;
}
}
END{
printf("\n total number of data packets at Node 7: %d\n", tcppack++);

Output:

Dept. of ECE, SaIT, Bengaluru Page 36


COMPUTER NETWORKS LABORATORY 2019

Dept. of ECE, SaIT, Bengaluru Page 37


COMPUTER NETWORKS LABORATORY 2019

5. Implement ESS with transmission nodes in Wireless LAN and obtain the performance
parameters.

set ns [new Simulator]


set tf [open lab5.tr w]
$ns trace-all $tf
set topo [new Topography]
$topo load_flatgrid 1000 1000
set nf [open lab5.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 \
-phyType Phy/WirelessPhy \
-channelType Channel/WirelessChannel \
-propType Propagation/TwoRayGround \
-antType Antenna/OmniAntenna \
-topoInstance $topo \
-agentTrace ON \
-routerTrace OFF

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

Dept. of ECE, SaIT, Bengaluru Page 38


COMPUTER NETWORKS LABORATORY 2019

$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 nf tf
$ns flush-trace
exec nam lab5.nam &
close $tf
exit 0
}
$ns at 250 "finish"
$ns run

Output:

Dept. of ECE, SaIT, Bengaluru Page 39


COMPUTER NETWORKS LABORATORY 2019

6. Implementation of Link state routing algorithm.

#===================================
# Simulation parameters setup
#===================================
set val(stop) 10.0; # time of simulation end

#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]

#Open the NS trace file


set tracefile [open lab6.tr w]
$ns trace-all $tracefile

#Open the NAM trace file


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

#===================================
# Nodes Definition
#===================================
#Create 5 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]

#===================================
# Links Definition
#===================================
#Createlinks between nodes
$ns duplex-link $n0 $n1 100.0Mb 10ms DropTail
$ns queue-limit $n0 $n1 50
$ns duplex-link $n0 $n2 100.0Mb 10ms DropTail

Dept. of ECE, SaIT, Bengaluru Page 40


COMPUTER NETWORKS LABORATORY 2019

$ns queue-limit $n0 $n2 50


$ns duplex-link $n2 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n2 $n3 50
$ns duplex-link $n1 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n1 $n3 50
$ns duplex-link $n3 $n4 100.0Mb 10ms DropTail
$ns queue-limit $n3 $n4 50
$ns duplex-link $n0 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n0 $n3 50
$ns duplex-link $n1 $n2 100.0Mb 10ms DropTail
$ns queue-limit $n1 $n2 50

#Give node position (for NAM)


$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n1 $n3 orient left-down
$ns duplex-link-op $n3 $n4 orient left-down
$ns duplex-link-op $n0 $n3 orient right-down
$ns duplex-link-op $n1 $n2 orient left-down

#Set the link costs. All link costs are symmetric

$ns cost $n0 $n1 2


$ns cost $n0 $n2 1
$ns cost $n0 $n3 3

$ns cost $n1 $n0 2


$ns cost $n1 $n2 2
$ns cost $n1 $n3 3

$ns cost $n2 $n1 2


$ns cost $n2 $n0 1
$ns cost $n2 $n3 1

$ns cost $n3 $n2 1


$ns cost $n3 $n1 3
$ns cost $n3 $n0 3
$ns cost $n3 $n4 2

$ns cost $n4 $n3 2

#===================================
# Agents Definition
#===================================
#Setup a UDP connection
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
set null1 [new Agent/Null]
$ns attach-agent $n4 $null1
$ns connect $udp0 $null1
$udp0 set packetSize_ 1500

Dept. of ECE, SaIT, Bengaluru Page 41


COMPUTER NETWORKS LABORATORY 2019

#===================================
# Applications Definition
#===================================
#Setup a CBR Application over UDP connection
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
$cbr0 set packetSize_ 1000
$cbr0 set rate_ 1.0Mb
$cbr0 set random_ null
$ns at 1.0 "$cbr0 start"
$ns at 5.0 "$cbr0 stop"
$ns rtproto LS

#===================================
# Termination
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam lab6.nam &
exit 0
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Output:

Dept. of ECE, SaIT, Bengaluru Page 42


COMPUTER NETWORKS LABORATORY 2019

PART-B:
Implement the
following in
C/C++.

Dept. of ECE, SaIT, Bengaluru Page 43


COMPUTER NETWORKS LABORATORY 2019

1. Write a program for a HLDC frame to perform the following. i) Bit stuffing ii)
Character stuffing.

Theory
Security and Error detection are the most prominent features that are to be provided by any
application which transfers data from one end to the other end. One of such a mechanism in
tracking errors which may add up to the original data during transfer is known as Stuffing. It
is of two types namely Bit Stuffing and the other Character Stuffing. Coming to the Bit
Stuffing, 01111110 is appended within the original data while transfer of it. The following
program describes how it is stuffed at the sender end and de-stuffed at the receiver end.

Algorithm:

1. Start
2. Initialize the array for transmitted stream with the special bit pattern 0111 1110which
indicates the beginning of the frame.
3. Get the bit stream to be transmitted in to the array.
4. Check for five consecutive ones and if they occur, stuff a bit 0
5. Display the data transmitted as it appears on the data line after appending 0111 1110 at the
end
6. For de−stuffing, copy the transmitted data to another array after detecting the stuffed bits
7. Display the received bit stream
8. Stop

i) Bit stuffing:

#include<stdio.h>
#include<string.h>

int main()
{
char data[50],stuff[50],dstuff[50];
int i,j,count,length;
printf("enter the data\n");
scanf("%s",data);

Dept. of ECE, SaIT, Bengaluru Page 44


COMPUTER NETWORKS LABORATORY 2019

length=strlen(data);
count=0,j=0;
for (i=0;i<length;i++)
{
if(data[i]=='1')
{
count++;

}
else
{
count=0;
}
stuff[j]=data[i];
j++;
if(count==5 && data[i+1]=='1')
{
stuff[j]='0';
j++;
count=0;
}
}
stuff[j]='\0';
printf("stuffed data at intermediate site is \n 01111110 %s 01111110 \n",stuff);
///destuffing

length=strlen(stuff);
count=0;j=0;
for(i=0;i<length;i++)
{
if(stuff[i]=='1')
{
count++;
}
else
{
count=0;
}
dstuff[j]=stuff[i];
j++;

Dept. of ECE, SaIT, Bengaluru Page 45


COMPUTER NETWORKS LABORATORY 2019

if(count==5 && stuff[i+1]=='0')


{
count=0;
i++;
}
}

dstuff[j]='\0';
printf("\n\ndestuffed data : %s",dstuff);

Output:

enter the data


11011111101101
stuffed data at intermediate site is
01111110 110111110101101 01111110
destuffed data : 11011111101101

ii) Character stuffing and Destuffing:

Theory
The Character Stuffing, DLESTX and DLEETX are used to denote start and end of character
data with some constraints imposed on repetition of characters as shown in the program below
clearly.

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
SAMBHRAM) insert another DLE in the string (ex: SAMBHRAMDLE)
4. Transmit DLE ETX at the end of the string
5. Display the string
6. Stop

Dept. of ECE, SaIT, Bengaluru Page 46


COMPUTER NETWORKS LABORATORY 2019

Algorithm for Character De−stuffing


1. Start
2. Neglect initial DLE STX
3. If DLE is present in the text, neglect it; if another DLE follows, copy the same to output.
4. Neglect the trailing DLE ETX
5. Stop
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<process.h>
void main()
{
int i=0,j=0,n,pos;
char a[20],b[50],ch;
clrscr();
printf("enter string\n");
scanf("%s",&a);
n=strlen(a);
printf("enter position\n");
scanf("%d",&pos);
if(pos>n)
{
printf("invalid position, Enter again :");
scanf("%d",&pos);
}
printf("enter the character\n");
ch=getche();

b[0]='d';
b[1]='l';
b[2]='e';
b[3]='s';
b[4]='t';
b[5]='x';
j=6;
while(i<n)
{
if(i==pos-1)
{
b[j]='d';

Dept. of ECE, SaIT, Bengaluru Page 47


COMPUTER NETWORKS LABORATORY 2019

b[j+1]='l';
b[j+2]='e';
b[j+3]=ch;
b[j+4]='d';
b[j+5]='l';
b[j+6]='e';
j=j+7;
}
if(a[i]=='d' && a[i+1]=='l' && a[i+2]=='e')
{
b[j]='d';
b[j+1]='l';
b[j+2]='e';
j=j+3;
}

b[j]=a[i];
i++;
j++;
}
b[j]='d';
b[j+1]='l';
b[j+2]='e';
b[j+3]='e';
b[j+4]='t';
b[j+5]='x';
b[j+6]='\0';
printf("\nframe after stuffing:\n");
printf("%s",b);
getch();
}

Output:
enter string
SAMBHRAM
enter position
5
enter the character
frame after stuffing:
dlestxSAMBdle
dleHRAMdleetx

Dept. of ECE, SaIT, Bengaluru Page 48


COMPUTER NETWORKS LABORATORY 2019

2. Write a program for distance vector algorithm to find suitable path for
transmission.

Each node constructs a one-dimensional array containing the "distances"(costs) to all other nodes
and distributes that vector to its immediate neighbors.

1. The starting assumption for distance-vector routing is that each node knows the cost of
the link to each of its directly connected neighbors.
2. A link that is down is assigned an infinite cost.

Note that each node only knows the information in one row of the table.

1. Every node sends a message to its directly connected neighbors containing its personal
list of distance. ( for example, A sends its information to its neighbors B,C,E, and F. )
2. If any of the recipients of the information from A find that A is advertising a path shorter
than the one they currently know about, they update their list to give the new path length
and note that they should send packets for that destination through A. ( node B learns
from A that node E can be reached at a cost of 1; B also knows it can reach A at a cost of
1, so it adds these to get the cost of reaching E by means of A. B records that it can reach
E at a cost of 2 by going through A.)
3. After every node has exchanged a few updates with its directly connected neighbors, all
nodes will know the least-cost path to all the other nodes.

Dept. of ECE, SaIT, Bengaluru Page 49


COMPUTER NETWORKS LABORATORY 2019

4. In addition to updating their list of distances when they receive updates, the nodes need to
keep track of which node told them about the path that they used to calculate the cost, so
that they can create their forwarding table. ( for example, B knows that it was A who said
" I can reach E in one hop" and so B puts an entry in its table that says " To reach E, use
the link to A.)

Information Distance to Reach Node


A B C D E F G
Stored at Node
A 0 1 1 2 1 1 2
B 1 0 1 2 2 2 3
C 1 1 0 1 2 2 2
D  2 1 0 3 2 1
E 1 2 2 3 0 2 3
F 1 2 2 2 2 0 1
G  3 2 1 3 1 0

#include<stdio.h>
#include<stdlib.h>

struct node
{
int dist[15];
int from[15];
};

int main()
{
int a[15][15],n=0,i,j,k,count;
struct node s[10];
printf("enter number of nodes\n");
scanf("%d",&n);
printf("enter matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
Dept. of ECE, SaIT, Bengaluru Page 50
COMPUTER NETWORKS LABORATORY 2019

s[i].dist[j]=a[i][j];//read it as from i to j distance is a[i][j]


s[i].from[j]=j; // read it as from i to j next node is j
}
}
//remember floyd's algorithm? all pairs shortest path, apply the same logic!
do
{
count=0;
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(s[i].dist[j] > a[i][k] + s[k].dist[j])
{
s[i].dist[j] = a[i][k] + s[k].dist[j];
s[i].from[j]=k;
count++;
}
}
}
}
}while(count!=0);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("Src : %d -> Dest : %d Next node : %d Distance :
%d\n",i,j,s[i].from[j],s[i].dist[j]);
}
printf("\n");
}
}

Output:

enter number of nodes


7
enter matrix

Dept. of ECE, SaIT, Bengaluru Page 51


COMPUTER NETWORKS LABORATORY 2019

0112112
1012223
1101222
2210321
1223023
1222201
2321310
Src : 1 > Dest : 1 Next node : 1 Distance : 0
Src : 1 > Dest : 2 Next node : 2 Distance : 1
Src : 1 > Dest : 3 Next node : 3 Distance : 1
Src : 1 > Dest : 4 Next node : 4 Distance : 2
Src : 1 > Dest : 5 Next node : 5 Distance : 1
Src : 1 > Dest : 6 Next node : 6 Distance : 1
Src : 1 > Dest : 7 Next node : 7 Distance : 2

Src : 2 > Dest : 1 Next node : 1 Distance : 1


Src : 2 > Dest : 2 Next node : 2 Distance : 0
Src : 2 > Dest : 3 Next node : 3 Distance : 1
Src : 2 > Dest : 4 Next node : 4 Distance : 2
Src : 2 > Dest : 5 Next node : 5 Distance : 2
Src : 2 > Dest : 6 Next node : 6 Distance : 2
Src : 2 -> Dest : 7 Next node : 7 Distance : 3

Src : 3 > Dest : 1 Next node : 1 Distance : 1


Src : 3 > Dest : 2 Next node : 2 Distance : 1
Src : 3 > Dest : 3 Next node : 3 Distance : 0
Src : 3 > Dest : 4 Next node : 4 Distance : 1
Src : 3 > Dest : 5 Next node : 5 Distance : 2
Src : 3 > Dest : 6 Next node : 6 Distance : 2
Src : 3 > Dest : 7 Next node : 7 Distance : 2

Src : 4 > Dest : 1 Next node : 1 Distance : 2


Src : 4 > Dest : 2 Next node : 2 Distance : 2
Src : 4 > Dest : 3 Next node : 3 Distance : 1
Src : 4 > Dest : 4 Next node : 4 Distance : 0
Src : 4 > Dest : 5 Next node : 5 Distance : 3
Src : 4> Dest : 6 Next node : 6 Distance : 2
Src : 4 > Dest : 7 Next node : 7 Distance : 1

Src : 5 > Dest : 1 Next node : 1 Distance : 1


Src : 5 > Dest : 2 Next node : 2 Distance : 2
Src : 5 > Dest : 3 Next node : 3 Distance : 2
Src : 5 > Dest : 4 Next node : 4 Distance : 3
Src : 5 > Dest : 5 Next node : 5 Distance : 0

Src : 5 > Dest : 6 Next node : 6 Distance : 2

Dept. of ECE, SaIT, Bengaluru Page 52


COMPUTER NETWORKS LABORATORY 2019

Src : 5 -> Dest : 7 Next node : 7 Distance : 3

Src : 6 > Dest : 1 Next node : 1 Distance : 1


Src : 6 > Dest : 2 Next node : 2 Distance : 2
Src : 6 > Dest : 3 Next node : 3 Distance : 2
Src : 6 > Dest : 4 Next node : 4 Distance : 2
Src : 6 > Dest : 5 Next node : 5 Distance : 2
Src : 6 > Dest : 6 Next node : 6 Distance : 0
Src : 6 > Dest : 7 Next node : 7 Distance : 1

Src : 7 > Dest : 1 Next node : 1 Distance : 2


Src : 7 > Dest : 2 Next node : 2 Distance : 3
Src : 7 > Dest : 3 Next node : 3 Distance : 2
Src : 7 > Dest : 4 Next node : 4 Distance : 1
Src : 7 > Dest : 5 Next node : 5 Distance : 3
Src : 7 > Dest : 6 Next node : 6 Distance : 1
Src : 7 -> Dest : 7 Next node : 7 Distance : 0

Dept. of ECE, SaIT, Bengaluru Page 53


COMPUTER NETWORKS LABORATORY 2019

3. Implement Dijkstra’s algorithm to compute the shortest routing path.

Theory:

Dijkstra’s Shortest Path Algorithm is a popular algorithm for finding the shortest path between
different nodes in a graph. Often used in routing, this algorithm is implemented as a subroutine
in other graph algorithm. Dijkstra’s algorithm finds the solution for the single source shortest
path problems only when all the edge-weights are non-negative on a weighted, directed graph. In
other words, the graph is weighted and directed with the first two integers being the number of
vertices and edges that must be followed by pairs of vertices having an edge between them.In the
source code for Dijkstra’s algorithm in C, the inputs are asked as source, target and the weight of
the path between two nodes. Before going through the source code for Dijkstra’s algorithm in C,
here’s a look at the algorithm itself and a pseudo code based on the algorithm.

Alogorithm:

Let’s fix a node as the initial node; this will be the node at which we are starting. Let the
distance of node “Y” be the distance from the initial node to “Y”. Now, in Dijkstra’s algorithm,
some initial distance values are assigned, and these values are improved step by step. The
algorithm procedure is given below:

1. A tentative distance value is assigned to every node; this value is set to zero for the initial
node, and to infinity for all other nodes.
2. All nodes unvisited are marked, and the initial node is set as current. An unvisited set ( a
set of all the unvisited nodes) consisting of all the nodes is created.
3. For the current/initial node, take into account all the unvisited nearby nodes, and
calculate their tentative distances. Make a comparison of the current assigned value and
the newly calculated tentative distance; assign the smaller value. For example: if the
current/initial node X was marked with a distance of 4, and the edge connecting it with a
nearby neighbor node Y has length 1, then the distance through X to Y will be 4 + 1 = 5. If

Dept. of ECE, SaIT, Bengaluru Page 54


COMPUTER NETWORKS LABORATORY 2019

Y was previously assigned a value greater than 5, then change it to 5. Otherwise, keep the
value as it is.
4. A visited node is never to be checked again. So, after finishing above steps with all the
neighbors of the current node, make that node as visited and remove is from the unvisited
set.
5. Stop the algorithm if, when planning a route between two specific nodes, the destination
node has been marked visited.
6. Also, stop the algorithm if, when planning a complete traversal, the smallest tentative
distance among the nodes in the unvisited set is infinity. This case is a result of no
connection between the initial node and the remaining unvisited nodes.
7. Find the unvisited node assigned with the smallest tentative distance value, and this will
be the new “current mode”. Go back to step 3, and continue.

Example:

Consider the following graph.

Steps

Step 1: Remove all loops

Any edge that starts and ends at the same vertex is a loop.

Loops are marked in the image given below.

Dept. of ECE, SaIT, Bengaluru Page 55


COMPUTER NETWORKS LABORATORY 2019

Step 2: Remove all parallel edges between two vertex except the one with least
weight

In this graph, vertex A and C are connected by two parallel edges having weight 10 and 12
respectively. So, we will remove 12 and keep 10.

We are now ready to find the shortest path from
 vertex A to vertex D.

Dept. of ECE, SaIT, Bengaluru Page 56


COMPUTER NETWORKS LABORATORY 2019

Step 3: Create shortest path table

As our graph has 4 vertices, so our table will have 4 columns.

Note! Column name is same as the name of the vertex.

After solving this we will have the following result. (See the above video for the steps)

Dept. of ECE, SaIT, Bengaluru Page 57


COMPUTER NETWORKS LABORATORY 2019

Result

Following is the required shortest path

Code

Note! In the given code we are representing Vertices using decimal numbers.
So,
vertex A is denoted by digit 0.
vertex B is denoted by digit 1.
vertex C is denoted by digit 2.
vertex D is denoted by digit 3.

Program:

#include <stdio.h>
#include <stdlib.h>

/**
* contant to represent infinity
* it is assumed that no edge in the vertex will have weight equal
* to this value.
*/
#define INF 9999

// total number of vertices in the graph//

#define V 4

Dept. of ECE, SaIT, Bengaluru Page 58


COMPUTER NETWORKS LABORATORY 2019

// this function will return the minimum value//


int findMin(int x, int y) {
if (x < y) {
return x;
}
return y;
}

// this function will check if the vertex is marked//

int isMarked(int v, int markedVertices[], int markedVerticesIdx)


{

int i = 0;
for (i = 0; i < markedVerticesIdx; i++) {
if (v == markedVertices[i]) {
return 1;
}
}

return 0;
}

// this function will find shortest path between source and destination vertex//

void dijkstra(int graph[V][V], int src, int dest)


{

//variables
int i, r, c,
tmpC,
min,
currVertex,
edgeWt = 0,
destValue = 0,
markedValue = 0,
wtTableR = 0,
markedVerticesIdx = 0;

// array containing vertices in the shortest path//

int shortestPathVertices[V] = {-1};


int shortestPathVerticesIdx = 0;

Dept. of ECE, SaIT, Bengaluru Page 59


COMPUTER NETWORKS LABORATORY 2019

// this table will hold the weight//

int weightTable[V][V];
for (r = 0; r < V; r++)
{
for (c = 0; c < V; c++)
{
weightTable[r][c] = INF;
}
}
weightTable[wtTableR++][src] = 0;

// vertices that are marked//

int markedVertices[V] = {-1};


markedVertices[markedVerticesIdx++] = src;
currVertex = src;

// find shortest path //


while(currVertex != dest) {

// copy marked values to the next row of weightTable //

for (i = 0; i < markedVerticesIdx; i++)


{
c = markedVertices[i];
weightTable[wtTableR][c] = weightTable[wtTableR - 1][c];
}

/*** find the weight from the current vertex to all the other vertices that are directly
connected and not yet marked */

for (c = 0; c < V; c++)


{

if (c != currVertex && !isMarked(c, markedVertices, markedVerticesIdx))


{

edgeWt = graph[currVertex][c];
destValue = weightTable[wtTableR - 1][c];
markedValue = weightTable[wtTableR][currVertex];

min = findMin(destValue, markedValue + edgeWt);

weightTable[wtTableR][c] = min;

Dept. of ECE, SaIT, Bengaluru Page 60


COMPUTER NETWORKS LABORATORY 2019

/** * find minimum unmarked vertices in current row */

min = INF;
for (c = 0; c < V; c++) {

if (!isMarked(c, markedVertices, markedVerticesIdx))


{
if (weightTable[wtTableR][c] < min)
{
min = weightTable[wtTableR][c];
tmpC = c;
}
}

/*** found a new vertex for marking */

markedVertices[markedVerticesIdx++] = tmpC;
currVertex = tmpC;

/** * variables update */

wtTableR++;

/*** compute shortest path vertices */

c = dest;
shortestPathVertices[shortestPathVerticesIdx++] = c;
markedValue = weightTable[wtTableR - 1][dest];
for (r = wtTableR - 2; r >= 0; r--)
{

if (weightTable[r][c] != markedValue)
{
c = markedVertices[r];
markedValue = weightTable[r][c];
shortestPathVertices[shortestPathVerticesIdx++] = c;
}

Dept. of ECE, SaIT, Bengaluru Page 61


COMPUTER NETWORKS LABORATORY 2019

/*** display the weight and shortest path */

printf("Shortest Path between %d and %d\n", src, dest);


for (i = shortestPathVerticesIdx-1; i >= 0; i--)
{
printf("%d", shortestPathVertices[i]);
if (i > 0)
{
printf(" --> ");
}
}
printf("\n");
printf("Weight of the path: %d\n", weightTable[wtTableR-1][dest]);

int main(void)
{

/** * 2d array which holds the weight of the edges */


int graph[V][V] =
{
{0, 5, 10, INF},
{5, 0, 4, 11},
{10, 4, 0, 5},
{INF, 11, 5, 0}
};

/** * source and destination vertices */


int src = 0;
int dest = 3;

/** * find shortest path */


dijkstra(graph, src, dest);

return 0;
}

Output:

Shortest Path between 0 and 3


0 --> 1 --> 2 --> 3
Weight of the path: 14

Dept. of ECE, SaIT, Bengaluru Page 62


COMPUTER NETWORKS LABORATORY 2019

Example -2 : Dijkstra Algorithm - Finding Shortest Path

Minimum Value Formula:

Dept. of ECE, SaIT, Bengaluru Page 63


COMPUTER NETWORKS LABORATORY 2019

Dept. of ECE, SaIT, Bengaluru Page 64


COMPUTER NETWORKS LABORATORY 2019

4. For the given data, use CRC-CCITT polynomial to obtain CRC code. Verify the
program for the cases: i) Without error ii) With error.

Theory:

Cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks
and storage devices to detect accidental changes to raw data. Blocks of data entering these
systems get a short check value attached, based on the remainder of a polynomial division of
their contents. On retrieval, the calculation is repeated and, in the event the check values do not
match, corrective action can be taken against data corruption. CRCs can be used for error
correction.

CRCs are so called because the check (data verification) value is a redundancy (it expands the
message without adding information) and the algorithm is based on cyclic codes. CRCs are
popular because they are simple to implement in binary hardware, easy to analyze
mathematically, and particularly good at detecting common errors caused by noise in
transmission channels

The basic idea is to treat the entire message as a (rather long) binary number, which both the
sender and receiver divide using the same divisor. The quotient is discarded, and the remainder is
sent as the CRC. If the message is received without error, the receiver's calculation will match
the sender's calculation, and the CRC's will agree.

Algorithm:

 A sequence of n bits is therefore a polynomial of maximum degree n-1.


 In practice it is assumed that the polynomial used to generate the CRC is known to both
the transmitter and receiver.
 Generator polynomial G (n + 1 bit)
 The Message (M) to be transmitted can be formed from any sequence of bits
 The CRC will be given by the division of M / G.
 The message to be transmitted, that contains also the CRC, will be M' which is given by
M with the CRC appended to the end of the message
 The receiver calculates the CRC on the received message M' (M' = M + CRC) and will
get rest as 0 (zero) if the transfer of data occurred without error.

Dept. of ECE, SaIT, Bengaluru Page 65


COMPUTER NETWORKS LABORATORY 2019

Input is M’=M+G (bit)

The loop is repeated until the last bit of M’

Example:

Let M be the message to be transmitted, the value is: 1010 0011 1010 1100
It is assumed that G is 11010
We call M' the message with the CRC
The CRC is M / G.
The CRC code is the result of the division M / G where to M are attached n bits null
(0) corresponding to the degree of G.
We assume that G = 11010this means that its grade is 4; this means G(bit)=4so
we attach 4null bits (0) to M.
Now M is:
M = 1010 0011 1010 11000000.
Below is an example on how to calculate the CRC.

1010 0011 1010 1100 0000


1101 0||| since the leftmost bit is 1 we do the subtraction
0111 0||| here's the result after the XOR
111 00|| bring down the next digit, an since the leftmost bit is 1 we again subtract

Dept. of ECE, SaIT, Bengaluru Page 66


COMPUTER NETWORKS LABORATORY 2019

110 10|| perform the subtraction


001 10|| here's the result after the XOR
01 101| bring down the next digit, and since the leftmost bit is 0 not do the subtraction and bring
down another bit
1 1011 as the leftmost bit is 1 we again subtract
1 1010
0 0001 here's the result after the XOR

Repeating these steps till the end, we will get:


x

1010 0011 1010 1100 0000


1101 0
0111 00
110 10
001 101
01 1011
1 1010
0 0001 1
0001 10
001 101
01 1010
1 1010
0 0000 1
0000 11
000 110
00 1100
0 1100 0
1101 0
0001 00
001 000
01 0000
1 1010
0 1010 == CRC

To create M' it is sufficient to concatenate the CRC obtained to the M (message) to be


transmitted:
M' = 1010 0011 1010 1100 + 1010
M' = 1010 0011 1010 1100 1010

If the receiver makes the division of M' with G and gets 0 (zero) it means that there were
no errors during transmission.

Below there is an example where the CRC is concatenated to message during Tx and Rx that
receive the message and recalculate the CRC (must be 0).

Dept. of ECE, SaIT, Bengaluru Page 67


COMPUTER NETWORKS LABORATORY 2019

Dept. of ECE, SaIT, Bengaluru Page 68


COMPUTER NETWORKS LABORATORY 2019

C Source Code:

#include<stdio.h>
int a[100], b[100], i, j, len, k, count = 0;

//Generator Polynomial:g(x)=x^16+x^12+x^5+1

int gp[] = { 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, };

int
main ()
{
void div ();
printf ("\nEnter the length of Data Frame :");
scanf ("%d", &len);
printf ("\nEnter the Message :");
for (i = 0; i < len; i++)
scanf ("%d", &a[i]);

//Append r (16) degree Zeros to Msg bits//

for (i = 0; i < 16; i++)


a[len++] = 0;

//Xr.M(x) (ie. Msg+16 Zeros)

for (i = 0; i < len; i++)


b[i] = a[i];

//No of times to be divided ie. Message Length


k = len - 16;
div ();

Dept. of ECE, SaIT, Bengaluru Page 69


COMPUTER NETWORKS LABORATORY 2019

for (i = 0; i < len; i++)


b[i] = b[i] ^ a[i]; //MOD 2 Subtraction
printf ("\nData to be transmitted : ");
for (i = 0; i < len; i++)
printf ("%2d", b[i]);

printf ("\n\nEnter the Reveived Data : ");


for (i = 0; i < len; i++)
scanf ("%d", &a[i]);

div ();

for (i = 0; i < len; i++)


if (a[i] != 0)
{
printf ("\nERROR in Recived Data");
return 0;
}
printf ("\nData Recived is ERROR FREE");
}

void
div ()
{
for (i = 0; i < k; i++)
{
if (a[i] == gp[0])
{
for (j = i; j < 17 + i; j++)
a[j] = a[j] ^ gp[count++];
}

Dept. of ECE, SaIT, Bengaluru Page 70


COMPUTER NETWORKS LABORATORY 2019

count = 0;
}
}

Output:

Dept. of ECE, SaIT, Bengaluru Page 71


COMPUTER NETWORKS LABORATORY 2019

5. Implementation of Stop and Wait Protocol and Sliding Window Protocol.

Theory:

Stop-and-wait protocol and Sliding window protocol are the methods evolved for handling the
flow control of the network data transfers. These methods mainly differentiated by the
techniques they follow such as stop-and-wait uses the concept of the acknowledging each data
unit before sending another data unit. Conversely, sliding window protocol allows the transition
of the several data units before sending an acknowledgement. Among the two protocols, the
sliding window protocol is more efficient than the stop-and-wait protocol.

Basis for comparison Stop-and-Wait Protocol Sliding Window Protocol


Behavior Request and reply Simultaneous transmit
Number of transferrable Only one Multiple
frames
Efficiency Less More comparatively
Acknowledgement Sent after each arriving Window of acknowledgement is
packet maintained
Type of transmission Half duplex Full duplex
Propagation delay Long Short
Link utilization Poor Better

Stop-and-Wait Protocol

In a communication, if the speed of transmitting data at the sender end is very much higher than
the speed of reception of data at the receiver end, how the network is going to deal with these
kinds of cases? It requires the working speed of sender and receiver should be unvarying. The
stop-and-wait protocol has emerged as a solution to this problem. In this protocol, the sender
sends a frame then waits for the acknowledgement. When the receiver sends an
acknowledgement to the sender, it proceeds further and sends another frame.

Dept. of ECE, SaIT, Bengaluru Page 72


COMPUTER NETWORKS LABORATORY 2019

The transmission mode of the protocol is half duplex, as the sender transmits data to the receiver
at a time and receiver sends the acknowledgement when data is received.

The example of the stop-and-wait protocol is the RPC (Remote Procedure Call) because it
works in the similar pattern where the subroutine calls are implemented from the program in one
device to the library routines on another device. As most programs are single-threaded, which
make the sender wait for the reply before proceeding and sending other requests.

Sliding Window Protocol

Like stop-and-wait protocol, sliding window protocol is also a method to implement the flow
control mechanism. It has eliminated the drawback of the stop-and-wait protocol where the
restricted amount of data can be transmitted in one direction at a time. The performance of the
sliding window protocol has improved by sending multiple frames bidirectional at the same time
(i.e., n>1, while stop-and-wait limits n to 1). In this scheme, the sender sends sequentially
numbered frames to the recipient in order to keep track of the frames, if the header size is n bit
the sequence can range from 0 to (2n-1).

The window here signifies a buffer utilized to store the data till the receiver does not read it, after
reading the content the buffer is emptied. It uses two types of windows, sending window and
receiving window which can range up to (2n-1). The sending window maintains the sequence
number relating to the transmitted frames, and it is controlled at the sender’s end. Similarly, the
receiver’s end also has a receiving window to keep track of the frames allowed to accept.

Dept. of ECE, SaIT, Bengaluru Page 73


COMPUTER NETWORKS LABORATORY 2019

The TCP protocol works as the sliding window protocol and uses a buffer placed in the kernel
of the operating system.

Algorithm:

Stop and Wait Protocol Sliding Window Protocol


Sender: 1. Start the program.
Sendor Node (SN):Receiver Node (RN) 2.Get the frame size from the user
1. Accept packet from higher layer when available; 3. To create the frame based on the user request.
assign number SN to it
4. To send frames to server from the client side.
2. Transmit packet SN in frame with sequence #
SN. 5. If your frames reach the server it will send ACK
3. Wait for an error free frame from B signal to client otherwise it will send NACK signal
4. if received and it contains RN>SN in the request to client.
# field, set SN to RN and go to 1 6.Stop the program
5. if not received within given time, go to 2
Receiver:
1. Whenever an error-free frame is received from A
with a sequence # equal to RN, release received
Packet to higher layer and increment RN.
2. At arbitrary times, but within bounded delay
after receiving any error free frame from A,
transmit a frame to A containing RN in the
request # field.

Dept. of ECE, SaIT, Bengaluru Page 74


COMPUTER NETWORKS LABORATORY 2019

C Program: Stop and Wait Protocol

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int i,j,noframes,x,x1=10,x2;
noframes=10;
i=1;
j=1;
printf("number of frames is %d ",noframes);

getch();
while(noframes>0)
{
printf("\nsending frames is %d",i);
x=rand()%10;
if(x%10==0)
{
for(x2=1;x2<2;x2++)
{
printf("\n waiting for %d seconds\n",x2);
sleep(x2);
}
printf("\n sending frames %d\n",i);
x=rand()%10;
}
printf("\n ack for frame %d\n",j);
noframes=noframes-1;
i++;
j++;
}
printf("\n end of stop and wait protocol\n");

Output:

number of frames is 10
sending frames is 1
ack for frame 1

sending frames is 2
ack for frame 2

sending frames is 3
Dept. of ECE, SaIT, Bengaluru Page 75
COMPUTER NETWORKS LABORATORY 2019

ack for frame 3

sending frames is 4
ack for frame 4

sending frames is 5
ack for frame 5

sending frames is 6
ack for frame 6

sending frames is 7
ack for frame 7

sending frames is 8
ack for frame 8

sending frames is 9
ack for frame 9
sending frames is 10
ack for frame 10

end of stop and wait protocol

C Program : Sliding Window Protocol

#include<stdio.h>

int
main ()
{
int w, i, f, frames[50];

printf ("Enter window size: ");


scanf ("%d", &w);

printf ("\nEnter number of frames to transmit: ");


scanf ("%d", &f);

printf ("\nEnter %d frames: ", f);

for (i = 1; i <= f; i++)


scanf ("%d", &frames[i]);

printf

Dept. of ECE, SaIT, Bengaluru Page 76


COMPUTER NETWORKS LABORATORY 2019

("\nWith sliding window protocol the frames will be sent in the following manner (assuming
no corruption of frames)\n\n");
printf
("After sending %d frames at each stage sender waits for acknowledgement sent by the
receiver\n\n",
w);

for (i = 1; i <= f; i++)


{
if (i % w == 0)
{
printf ("%d\n", frames[i]);
printf
("Acknowledgement of above frames sent is received by sender\n\n");
}
else
printf ("%d ", frames[i]);
}

if (f % w != 0)
printf ("\nAcknowledgement of above frames sent is received by sender\n");

return 0;
}

Output:

Enter window size: 3

Enter number of frames to transmit: 5

Enter 5 frames: 12 5 89 4 6

With sliding window protocol the frames will be sent in the following manner (assuming no
corruption of frames)

After sending 3 frames at each stage sender waits for acknowledgement sent by the receiver

12 5 89
Acknowledgement of above frames sent is received by sender

46
Acknowledgement of above frames sent is received by sender

Dept. of ECE, SaIT, Bengaluru Page 77


COMPUTER NETWORKS LABORATORY 2019

6. Write a program for congestion control using leaky bucket algorithm.

Theory:

In the network layer, before the network can make Quality of service guarantees, it must know
what traffic is being guaranteed. One of the main causes of congestion is that traffic is often
bursty.

To understand this concept first we have to know little about traffic shaping. Traffic Shaping is
a mechanism to control the amount and the rate of the traffic sent to the network. Approach of
congestion management is called Traffic shaping. Traffic shaping helps to regulate rate of data
transmission and reduces congestion.

There are 2 types of traffic shaping algorithms:

1. Leaky Bucket
2. Token Bucket

Suppose we have a bucket in which we are pouring water in a random order but we have to get
water in a fixed rate, for this we will make a hole at the bottom of the bucket. It will ensure that
water coming out is in a some fixed rate, and also if bucket will full we will stop pouring in it.

The input rate can vary, but the output rate remains constant. Similarly, in networking, a
technique called leaky bucket can smooth out bursty traffic. Bursty chunks are stored in the
bucket and sent out at an average rate.

Dept. of ECE, SaIT, Bengaluru Page 78


COMPUTER NETWORKS LABORATORY 2019

In the figure, we assume that the network has committed a bandwidth of 3 Mbps for a host. The
use of the leaky bucket shapes the input traffic to make it conform to this commitment. In Figure
the host sends a burst of data at a rate of 12 Mbps for 2 s, for a total of 24 Mbits of data. The host
is silent for 5 s and then sends data at a rate of 2 Mbps for 3 s, for a total of 6 Mbits of data. In
all, the host has sent 30 Mbits of data in 10 s. The leaky bucket smooths the traffic by sending
out data at a rate of 3 Mbps during the same 10 s.

Without the leaky bucket, the beginning burst may have hurt the network by consuming more
bandwidth than is set aside for this host. We can also see that the leaky bucket may prevent
congestion.

A simple leaky bucket algorithm can be implemented using FIFO queue. A FIFO queue holds
the packets. If the traffic consists of fixed-size packets (e.g., cells in ATM networks), the process
removes a fixed number of packets from the queue at each tick of the clock. If the traffic consists
of variable-length packets, the fixed output rate must be based on the number of bytes or bits.

Dept. of ECE, SaIT, Bengaluru Page 79


COMPUTER NETWORKS LABORATORY 2019

Algorithm:

1. Start
2. Set the bucket size or the buffer size.
3. Set the output rate.
4. Transmit the packets such that there is no overflow.
5. Repeat the process of transmission until all packets are transmitted. (Reject packets
where its size is greater than the bucket size)
6. Stop

Example:

Let n=1000

Packet=
Since n> front of Queue i.e. n>200
Therefore, n=1000-200=800
Packet size of 200 is sent to the network.

Now Again n>front of the queue i.e. n > 400


Therefore, n=800-400=400
Packet size of 400 is sent to the network.

Since n< front of queue


Therefore, the procedure is stop.
Initialize n=1000 on another tick of clock.
This procedure is repeated until all the packets are sent to the network.

C Program:

#include<stdio.h>
#include<stdlib.h>
#define MIN(x,y) (x>y)?y:x
int main()
{
int orate,drop=0,cap,x,count=0,inp[10]={0},i=0,nsec,ch;
printf("\n enter bucket size : ");
scanf("%d",&cap);

Dept. of ECE, SaIT, Bengaluru Page 80


COMPUTER NETWORKS LABORATORY 2019

printf("\n enter output rate :");


scanf("%d",&orate);
do
{
printf("\n enter number of packets coming at second %d :",i+1);
scanf("%d",&inp[i]);
i++;
printf("\n enter 1 to contiue or 0 to quit..........");
scanf("%d",&ch);
}
while(ch);
nsec=i;
printf("\n second \t recieved \t sent \t dropped \t remained \n");
for(i=0;count || i<nsec;i++)
{
printf(" %d",i+1);
printf(" \t%d\t ",inp[i]);
printf(" \t %d\t ",MIN((inp[i]+count),orate));
if((x=inp[i]+count-orate)>0)
{
if(x>cap)
{
count=cap;
drop=x-cap;
}
else
{
count=x;
drop=0;
}
}

Dept. of ECE, SaIT, Bengaluru Page 81


COMPUTER NETWORKS LABORATORY 2019

else
{
drop=0;
count=0;
}
printf(" \t %d \t %d \n",drop,count);
}
return 0;
}

Output:

enter bucket size : 10

enter output rate :6

enter number of packets coming at second 1 :3

enter 1 to contiue or 0 to quit..........1

enter number of packets coming at second 2 :7

enter 1 to contiue or 0 to quit..........1

enter number of packets coming at second 3 :9

enter 1 to contiue or 0 to quit..........1

enter number of packets coming at second 4 :7

enter 1 to contiue or 0 to quit..........1

enter number of packets coming at second 5 :4

enter 1 to contiue or 0 to quit..........0

Dept. of ECE, SaIT, Bengaluru Page 82


COMPUTER NETWORKS LABORATORY 2019

second recieved sent dropped remained

1 3 3 0 0
2 7 6 0 1
3 9 6 0 4
4 7 6 0 5
5 4 6 0 3
6 0 3 0 0

Dept. of ECE, SaIT, Bengaluru Page 83


COMPUTER NETWORKS LABORATORY 2019

VIVA QUESTIONS
1. What is FIFO? How to implement Multiple FIFOs? Disadvantages of FIFO.
2. What is congestion? Explain leaky bucket and token bucket algorithm? What are its
disadvantages of each?
3. List other congestion control algorithm.
4. What are the disadvantages of RSA Algorithm?
5. What is the need for routing protocols? List some routing protocols. Which are common
routing algorithms used by routing protocols?
6. Disadvantages of Distance vector routing. Explain the method to overcome such
disadvantage.
7. What is CRC? What is the need for CRC? Which Layer it is implemented?
8. Can CRC be employed for error correction if so how.
9. Explain steps of error correction and error detection. What is encoding and decoding,
why it is required?
10. What is Hamming code? Can it be used for error detection and correction how?
11. What are linear block codes? Explain their advantages.
12. What is protocol? List some protocols. How to modify existing protocol?
13. Difference between TCP/IP and OSI Layer Model?
14. Difference between Router, Bridge, Gateway channel. In which layer it is used?
15. Difference between hub and switch. Which is more compatible and reliable?
16. Explain various Ethernet standards.
17. Difference between IP and MAC address.
18. In which layer ATM protocol is used? Explain the purpose.
19. In Which layer or protocol which converts IP to MAC Address.
20. Which are the different collision detection protocols?
21. Which are the different channelization protocol and explain their needs?
22. Explain term error rate, bandwidth, throughput transmission delay, BER, Interarrival
time. What is unit of bandwidth?

Dept. of ECE, SaIT, Bengaluru Page 84


COMPUTER NETWORKS LABORATORY 2019

CONTENT BEYOND SYLLABUS


1. What is congestion/contention Window? How it is constructed and managed and by
which layer?
2. List and explain different link types. Differentiate its characteristics.
3. List TCP and UDP Properties?
4. Why TCP is more reliable than UDP? Is data rate and bandwidth are same?
5. Explain various factors that results in congestion and collision.
6. Explain QOS and different measures taken for implementing QOS in network.
7. List different N/W topologies.
8. Difference between Data rate versus Throughput.
9. List the meaning and term used for data in different layers of TCP/IP protocol suite.
10. Difference between intranet, internet and Ethernet. What are the relationships between
these network types?

Dept. of ECE, SaIT, Bengaluru Page 85


DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING
COMPUTER NETOWRKS LAB – 15ECL68
QUESTION BANK
1. (a) Implement a point to point network with four nodes and duplex links between them.
Analyze the network performance by setting the queue size and varying the band width.
(b).Write a C program for a HLDC frame to perform the Bit stuffing.
2. (a) Implement a four node point to point network with links no-n2, n1-n2, and n2-n3. Apply
TCP agent between no-n3 and UDP between n1-n3. Apply relevant applications over TCP and
UDP agents changing the parameter and determine the number of packets sent by TCP/UDP.
(b).Write a C program for a HLDC frame to perform the character stuffing.
3. (a) Implement Ethernet LAN using n (6-10) nodes. Compare the throughput by changing the
error rate and data rate
(b) Write a C program for a HLDC frame to perform the Bit stuffing.
4. (a) Implement Ethernet LAN using n nodes and assign multiple traffic to the nodes and
obtain congestion window for different sources/ destinations.
(b).Implement the Dijkstra’s algorithm to compute the shortest routing path using C
program.
5. (a) Implement ESS with transmission nodes in Wireless LAN and obtain the performance
parameters.
(b).Implementation of stop and wait protocol using C program.
6. (a) Implement Ethernet LAN using n (6-10) nodes and compare the throughput by changing
the error rate and data rate.
(b).Implementation of sliding window protocol using C program.
7. (a) Implement a link state routing algorithm using NS2.
(b).Write a C program for a HLDC frame to perform the Bit stuffing.
8. (a) Implement a point to point network with four nodes and duplex links between them.
Analyze the network performance by setting the Queue size and varying the Band width.
(b). Write a C program for the given data, use CRC-CCITT polynomial to obtain CRC code.
Verify the program for the cases (a) Without error (b) With error.
9. (a) Implement a four node point to point network with links no-n2, n1-n2, and n2-n3 apply
TCP agent between no-n3 and UDP between n1-n3. Apply relevant applications over TCP and
UDP agents changing the parameter and determine the number of packets sent by TCP/UDP.
(b). Write a C program for congestion control using Leaky bucket algorithm.
10. (a) Implement Ethernet LAN using n (6-10) nodes. Compare the throughput by changing
the error rate and data rete.
(b). Write a C program for a HLDC frame to perform the Character stuffing.
11. (a) Implement a link state routing algorithm using NS2.
(b). Write a C program for a HLDC frame to perform the Character stuffing.
12. (a) Implement Ethernet LAN using n nodes and assign multiple traffic to the nodes and
obtain congestion window for different sources/ destinations.
(b). Write a C program for Distance vector algorithm to find suitable path for transmission.

You might also like