ComputerNetworksLAB 18ECL76 7thsemester
ComputerNetworksLAB 18ECL76 7thsemester
SVCE/ECE/MNL./CNL/Ver-01
SRI VENKATESHWARA COLLEGE OF ENGINEERING
VIDYANAGAR, BENGALURU-562157
DEPARTMENT OF
ELECTRONICS & COMMUNICATIONENGINEERING
LAB MANUAL
Computer Network Lab
(18ECL76)
(VII SEMESTER)
Prepared by
Dr. Vijayashree R Budyal
Dr. Ravi Gatti
Prof. Nataraja N
2021-2022
Approved By:
Dr. Vijayashree R Budyal
HoD, E&CE, SVCE, Bengaluru
INDEX
Page
Sl. No. Description
No.
1 Course objectives 2
2 Course outcomes 2
3 ABET Student Outcomes, NBA Programme 3
4 Course Outcomes Mapping with Programme outcomes 5
5 Course Syllabus 6
6 Experiments Beyond the Syllabus 7
1. 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.
2. COURSE OUTCOMES
Level of Blooms
COs After Completion of the course the student will be able to
Taxonomy
C367.1 Choose suitable tools to model a network and demonstrate and
calculate the network parameters of different protocols at various L3
OSI reference levels.
C367.2 Illustrate network performance for the transport layer protocols such
as UDP and TCP L3
C367.3 Simulate ESS and HDLC frame format for the Data communication
L3
over the Different Networks
C367.4 Analyze CRC and Leaky bucket algorithm for different network
L4
parameters using c language.
Student Outcomes are outcomes (1) through (7), plus any additional
outcomes that may be articulated by the program.
Reference: https://www.abet.org/accreditation/accreditation-criteria/criteria-for-accrediting-
engineering-programs-2020-2021/
meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental
considerations.
PO4. Conduct investigations of complex problems: Use research-based
knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
PO5. Modern tool usage: Create, select, and apply appropriate
techniques, resources, and modern engineering and IT tools including
prediction and modeling to complex engineering activities with an
understanding of the limitations.
PO6. The engineer and society: Apply reasoning informed by the
contextual knowledge to assess societal, health, safety, legal and cultural
issues and the consequent responsibilities relevant to the professional
engineering practice.
PO7. Environment and sustainability: Understand the impact of the
professional engineering solutions in societal and environmental
contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8. Ethics: Apply ethical principles and commit to professional ethics
and responsibilities and norms of the engineering practice.
PO9. Individual and teamwork: Function effectively as an individual,
and as a member or leader in diverse teams, and in multidisciplinary
settings.
PO10. Communication: Communicate effectively on complex engineering
activities with the engineering community and with society at large, such
as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear
instructions.
PO11. Project management and finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply
these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
PO12. Life-long learning: Recognize the need for, and have the
preparation and ability to engage in independent and life-long learning
in the broadest context of technological change.
C367.1 3 3 3 2 1 3 3
C367.2 3 3 2 2 2 3 3
C367.3 3 3 2 2 1 3 3
C367.4 3 3 2 2 1 3 3
C367.5 3 3 2 2 1 3 3
3 Strong Correlation
2 Moderate Correlation
1 Weak / No Correlation
PKL 3 5 6 5 6 3 3 3 NA M 3 M 3 3
C367.
3 3 3 3 2 1 2 2 2 1 2 2 2 3 3
1
C367.
3 3 3 3 1 1 3 3 3 1 2 2 1 3 2
2
C367.
3 3 3 3 1 1 3 3 3 1 2 2 1 2 2
3
C367.
4 3 3 3 1 3 2 2 2 1 2 2 2 2 2
4
C367.
5 3 3 3 1 3 3 1 3 1 2 2 2 2 2
5
3 Strong Correlation
2 Moderate Correlation
1 Weak / No Correlation
6. Course syllabus
Page
Sl. No. Description
No.
PART - A
Simulation experiments using NS2/ NS3/ OPNET/ NCTUNS/ NetSim/
QualNet/ Packet Tracer or any other equivalent tool
Implement a point to pint network with four nodes and duplex links between
1 them. Analyze the network performance by setting the queue size and varying 9
the bandwidth.
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
2 11
applications over TCP and UDP agents changing the parameter and determine
the number of packets sent by TCP/UDP.
Implement Ethernet LAN using n (6-10) nodes. Compare the throughput by
3 13
changing the error rate and data rate.
Implement Ethernet LAN using n nodes and assign multiple traffic to the nodes 15
4
and obtain congestion window for different sources/ destinations.
Implement ESS with transmission nodes in Wireless LAN and obtain the
5
performance parameters. 17
6 Implementation of Link state routing algorithm 19
PART - B : Implement the following in C/C++
Write a program for a HLDC frame to perform the following.
1 i) Bit stuffing 22
ii) Character stuffing.
Write a program for distance vector algorithm to find suitable path for
2 26
transmission.
3 Implement Dijkstra’s algorithm to compute the shortest routing path. 28
For the given data, use CRC-CCITT polynomial to obtain CRC code. Verify the
program for the cases
4 30
a. Without error
b. With error
5 Implementation of Stop and Wait Protocol and Sliding Window Protocol 32
Write a program for congestion control using leaky bucket algorithm.
6 36
Experiments beyond the syllabus
Transmission of ping message
1 38
Using TCP/IP sockets, write a client server program to make client sending the
2 file name and the server to send back the contents of the requested file 42
Implement the TCP/IP sockets, write a client server program using as message
3 queues or FIFOs as IPC channels 48
1. Transmission of Ping Message: Simulate the transmission of ping PO3, PO5, PO9,
messages over a network topology consisting of 6 nodes and find the PO11, PO12
number of packets dropped due to congestion. PSO1
2. Using TCP/IP sockets, write a client server program to make PO3, PO5, PO9,
client sending the file name and the server to send back the PO11, PO12
3. Implement the TCP/IP sockets, write a client server program PO3, PO5, PO9,
using as message queues or FIFOs as IPC channels PO11, PO12
PSO1
Programme Coordinator
Figure 1 shows the basic architecture of NS2. NS2 provides users with an executable
command ns which takes on input argument, the name of a Tcl simulation scripting file. Users
are feeding the name of a Tcl simulation script as an input argument of an NS2 executable
command ns.
In most cases, a simulation trace file is created, and is used to plot graph and/or to
create animation. NS2 consists of two key languages: C++ and Object-oriented Tool Command
Language (OTcl). While the C++ defines the internal mechanism (i.e., a backend) of the
simulation objects, the OTcl sets up simulation by assembling and configuring the objects as
well as scheduling discrete events.
The C++ and the OTcl are linked together using TclCL. Mapped to a C++ object,
variables in the OTcl domains are sometimes referred to as handles. Conceptually, a is just a
string in the OTcl domain, and does not contain any functionality. Instead, the functionality is
defined in the mapped C++ object. In the OTcl domain, a handle acts as a frontend which
interacts with users and other OTcl objects. It may define its own procedures and variables to
facilitate the interaction. Note that the member procedures and variables in the OTcl domain
are called instance procedures (instprocs) and instance variables respectively. Before
proceeding further, the readers are encouraged to learn C++ and OTcl languages. We refer the
readers to [14] for the detail of C++, while a brief tutorial of Tcl and OTcl tutorial are given in
Appendices A.1 and A.2, respectively.
NS2 provides a large number of built-in C++ objects. It is advisable to use these C++
objects to set up a simulation using a Tcl simulation script. However, advance users may find
these objects insufficient. They need to develop their own C++ objects, and use a OTcl
configuration interface to put together these objects. After simulation, NS2 outputs either text-
based or animation-based simulation results. To interpret these results graphically and
interactively, tools such as NAM (Network AniMator) and XGraph are used. To analyze a
particular behaviour of the network, users can extract a relevant subset of text-based data and
transform it to a more conceivable presentation.
CONCEPT OVERVIEW:
NS uses two languages because simulator has two different kinds of things it needs to
do. On one hand, detailed simulations of protocols require a systems programming language
which can efficiently manipulate bytes, packet headers, and implement algorithms that run
over large data sets. For these tasks run-time speed is important and turn-around time (run
simulation, find bug, fix bug, recompile, re-run) is less important. On the other hand, a large
part of network research involves slightly varying parameters or configurations, or quickly
exploring a number of scenarios.
Start ns with the command 'ns <tclscript>' (assuming that you are in the directory with the ns
executable, or that your path points to that directory), where '<tclscript>' is the name of a Tcl
script file which defines the simulation scenario. You could also just start ns without any
arguments and enter the Tcl commands in the Tcl shell, but that is definitely less comfortable.
Everything else depends on the Tcl script. The script might create some output on stdout, it might
write a tracefile or it might start nam to visualize the simulation.
Starting nam
You can either start nam with the command 'nam <nam-file>' where '<nam-file>' is the name of
a nam trace file that was generated by ns, or you can execute it directly out of the Tcl simulation
script for the simulation which you want to visualize. Below you can see a screenshot of a nam
window where the most important functions arebeing explained.
Introduction to VI:
VI is a text editor that is available in all Unix systems, other editors such pico and emacs
can also be used instead. Before you start for the first time, you must note that vi is modal editor.
A mode is like an environment. Different modes in vi interpret the same key differently. For
example, if you're in insert mode, typing a adds an a to the text, whereas in command mode,
typing a puts you in insert mode because a is the key abbreviation for the append command. If
you get confused about what mode you're in, press the Escape key on your keyboard. Pressing
Escape always returns you to the command mode (and if you're already in command mode, it
simply beeps to remind you of that fact). When you are in command mode, you can manage you
document; this includes the capability to change text, rearrange it, and delete it.
A summary of the basic vi commands are available in Appendix A. Insert mode is when you are
adding text directly into your document from the keyboard and you can maneuver the text area
using the arrow keys. For starting a new document, simply type vi after the command prompt to
the start the vi editor. The cursor will be located in the top left corner and each of the following
lines will start with a tilde (~) denoting empty lines. Note that the vi editor in currently in
command mode. In order to edit an existing file, type the name of the file along with the extension
after typing vi and a space in the Unix command prompt. To enter into the insert mode simply
press a on the keyboard. Then to save the edited document, type a colon (:) and the cursor will be
located in the bottom left corner after the colon, followed by a w and then press enter. In order to
quit the vi editor type a colon followed by a q (:q), this will take you back to the Unix prompt.
You can also choose to quit editing without saving by typing :q!, and if you forget the
exclamation mark (!) the system will issue a warning. Note: Do not forget to change the
permission settings for the edited file. This is done from the Unix command prompt by typing
chmod ugo+wrx filename.extension. In ugo, u = user, g = group, o = other, and in wrx, w = write,
r = read, x = execute, and the above command can be interpreted as, the user, the group and
everyone else can read, write and execute the file. To remove permissions, just replace the plus
sign (+) with a minus sign (-). The .tcl file must be executable.
In NCTUns, the configuration and operation for a simulated network are exactly the same as those
for a real-life IP network. This provides two advantages:
➢ If a user knows how to configure and operate a real-life IP network, he (she) immediately
knows how to configure and operate a simulated network in NCTUns,
➢ The configuration and operation of simulated networks in NCTUns are exactly the same as
those for real-life IP networks, NCTUns can be used as a training tool to educate people
how to configure and operate a real-life IP network. In NCTUns, many valuable real-life
UNIX network configuration tools (e.g., route, ifconfig, netstat) and performance
monitoring tools (e.g., ping, tcp dump, traceroute) can be directly run on a simulated
network to configure and monitor a simulated network.
NCTUns provides a highly-integrated and professional GUI environment in which a user can
easily conduct network simulations. The NCTUns GUI program is capable of,
A quick idea about what the GUI environment looks like, some screenshots of NCTUns
are shown below
➢ Starting Screen: Every time when a user launches the GUI program, the following starting
screen will pop up.
➢ Topology Editor: The topology editor provides a convenient and intuitive way to
graphically construct a network topology. A constructed network can be a fixed wired
network or a mobile wireless network.
➢ Attribute Dialog Box: A network device (node) may have many attributes. Setting and
modifying the attributes of a network node can be easily done. Just double-clicking the
icon of a network node.
➢ Performance Monitor: The performance monitor can easily and graphically generate and
display plots of some monitored performance metrics over time. Examples include a link’s
utilization or a TCP connection’s achieved throughput.
➢ Node Editor: The node editor provides a convenient environment in which a user can
flexibly configure the protocol modules used inside a network node. By using this tool, a
user can easily add, delete, or replace a module with his (her) own module. This capability
enables a user to easily test the performance of a new protocol.
➢ Packet Animation: Player By using the packet animation player, a packet transfer trace
logged during a simulation can be replayed at a specified speed. Both wired and wireless
networks are supported. This capability is very useful because it helps a researcher
visually see and debug the behavior of a network protocol.
Experiment 1
Aim:
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.
Theory:
TCP (Transmission Control protocol) is a standard that defines how to establish and maintain a network
conversation via which application programs can exchange data. TCP works with the Internet Protocol
(IP), which defines how computers send packets of data to each other. Together, TCP and IP are the basic
rules defining the Internet.
Variant I: Interfacing of the nodes and setting data communication through UDP
Data type through NS-2 Simulator
set ns [new Simulator]
set f [open lab1.tr w]
$ns trace-all $f
proc finish {} {
global f nf ns
$ns flush-trace
close $f
close $nf
exec nam lab1.nam &
exit 0
}
$ns duplex-link $n0 $n1 0.3Mb 10ms DropTail #vary bandwidth 0.3, 0.4, 0.5 0.7
$ns duplex-link $n1 $n2 0.3Mb 20ms DropTail #vary bandwidth 0.3, 0.4, 0.5 0.7
$ns duplex-link $n2 $n3 0.3Mb 20ms DropTail #vary bandwidth 0.3, 0.4, 0.5 0.7
➢ Open gedit editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# gedit lab1.tcl
➢ Save the program and quit.
➢ Run the simulation program
[root@localhost~]# ns lab1.tcl
➢ Here “ns” indicates network simulator. We get the topology shown in the network animator. Now press the
play button in the simulation window and the simulation will begins.
➢ To calculate the network performance. Execute the following command.
For calculating number of received packets
[root@localhost~]#grep ^r lab1.tr | grep “cbr” | awk ‘{s+=$6}END{print s}’
For calculating total time
[root@localhost~]#grep ^r lab1.tr | grep “cbr” | awk ‘{s+=$2}END{print s}’
➢ Write the value of network performance in observation sheet. Repeat the above step by changing the
bandwidth to [0.3Mb, 0.4Mb, 0.5Mb, 0.7Mb]to the following line of the program.
➢ $ns duplex-link $n0 $n1 0.7Mb 10ms DropTail #vary bandwidth 0.3, 0.4, 0.5 0.7
➢ $ns duplex-link $n1 $n2 0.7Mb 20ms DropTail #vary bandwidth 0.3, 0.4, 0.5 0.7
➢ $ns duplex-link $n2 $n3 0.7Mb 20ms DropTail #vary bandwidth 0.3, 0.4, 0.5 0.7
➢ Plot a graph with x- axis with bandwidth and y-axis with network performance of UDP protocol.
Variant Type-II: Interfacing of the nodes and setting data communication through TCP Data type
through NS-2 Simulator
proc finish {} {
global ns f nf
$ns flush-trace
close $f
close $nf
exec nam lab2.nam &
exit 0
}
Procedure:
Experiments 2
Aim:
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.
Theory:
UDP (User Datagram Protocol) is an alternative communications protocol to Transmission Control
Protocol (TCP) used primarily for establishing low-latency and loss-tolerating connections between
applications on the internet.
Variant Type-I: Interfacing of the 4 nodes and setting data communication through UDP Data type
through NS 2 Simulator
proc finish {} {
global ns f nf
$ns flush-trace
close $f
close $nf
exec nam lab2.nam &
exit 0
}
➢ Open gedit editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# gedit lab2.tcl
➢ Save the program and quit.
➢ To calculate the number of packets sent by UDP. Execute the following command.
Program Type-II: Interfacing of the 4 nodes and setting data communication through TCP Data
type through NS 2 Simulator
proc finish {} {
global ns f nf
$ns flush-trace
close $f
close $nf
exec nam lab2.nam &
exit 0
}
Variant Type-III: Interfacing of the 4 nodes and setting data communication through UDP/TCP
Data type through Packet Tracer
Procedure:
Experiments 3
Aim:
Implement Ethernet LAN using n (6-10) nodes. Compare the throughput by changing the error rate and
data rate.
Theory:
Local Area Network (LAN) is a data communication network connecting various terminals or computers
within a building or limited geographical area. The connection among the devices could wired or wireless.
Ethernet, Token Ring and Wireless LAN using IEEE 802.11 are examples of standard LAN technologies.
Variant Type-I: Implementation of Ethernet LAN and setting data communication through TCP
Data type through NS 2 Simulator
proc finish {} {
global nf ns tf
exec nam lab3.nam &
close $naf
close $trf
exit 0
}
$ns make-lan "$n0 $n1 $n2 $n3" 10Mb 10ms LL Queue/DropTail Mac/802_3
$ns make-lan "$n4 $n5 $n6" 10Mb 10ms LL Queue/DropTail Mac/802_3
➢ Open gedit editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# gedit lab3.tcl
➢ Save the program and quit.
➢ Run the simulation program
[root@localhost~]# ns lab3.tcl
➢ Here “ns” indicates network simulator. We get the topology shown in the network animator. Now press the
play button in the simulation window and the simulation will begins.
➢ To calculate the throughput. Execute the following command.
For calculating number of received packets
[root@localhost~]#grep ^r lab3.tr | grep “2 6” | awk ‘{s+=$6}END{print s}’
For calculating total time
[root@localhost~]#grep ^r lab3.tr | grep “2 6” | awk ‘{s+=$2}END{print s}’
➢ Write the value of throughput in observation sheet. Repeat the above step by changing the error rate to the
following line of the program.
$err set rate_ 0.7 #vary error rate 0.1, 0.4, 0.5 and 0.7
➢ Plot a graph with x- axis with Error rate and y-axis with Throughput.
Variant Type-II: Implementation of Ethernet LAN and setting data communication through TCP
Data type through NS 2 Simulator
proc finish {} {
global naf ns trf
exec nam lab3.nam &
close $naf
close $trf
exit 0
}
$ns make-lan "$n0 $n1 $n2 $n3" 10Mb 10ms LL Queue/DropTail Mac/802_3
$ns make-lan "$n4 $n5 $n6" 10Mb 10ms LL Queue/DropTail Mac/802_3
Procedure:
➢ Develop a topology shown in the figure given below
➢ Configure all the workstations
➢ Configure the switch & Router
➢ Verify the continuity using ping command
➢ Compare the throughput by changing the error rate and data rate
Experiment 4
Aim: Implement Ethernet LAN using n nodes and assign multiple traffic to the nodes and obtain
congestion window for different sources/ destinations.
Theory:
Network congestion occurs when packets sent from the source (the server) exceed what the destination
can handle (the user). When the buffers get filled up at the destination, the packets are temporarily stored
in buffers at both the source and destination as they wait to be forwarded to the upper layers. This can lead
to congestion and cause packet loss, retransmissions, reduced data throughput, performance degradation,
and even network collapse in extreme cases.
TCP can use the congestion window (cwnd) and the receiver window (rwnd) to control and avoid network
congestion. The amount of data that can be transmitted through a TCP connection is dependent on the
congestion window, which is maintained by the source. The receiver window is maintained by the
destination.
Variant Type I:
proc finish {} {
global ns f nf outFile1 outFile2
$ns flush-trace
close $f
close $nf
exec nam lab4.nam &
exec xgraph Congestion1.xg Congestion2.xg -geometry 400x400&
exit 0
}
$ns make-lan "$n0 $n1 $n2 $n3 $n4 $n5 " 10Mb 30ms LL Queue/DropTail Mac/802_3
➢ Open gedit editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# gedit lab4.tcl
➢ Save the program and quit.
➢ Run the simulation program
[root@localhost~]# ns lab4.tcl
➢ Here “ns” indicates network simulator. We get the topology shown in the network animator. Now press the
play button in the simulation window and the simulation will begins.
➢ The xgraph automatically calculates and plot the two graph of Congestion window with TCP1 and TCP2.
Variant Type II:
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the Trace files
set file1 [open out.tr w]
set winfile [open WinFile w]
$ns trace-all $file1
#Open the NAM trace file
set file2 [open out.nam w]
$ns namtrace-all $file2
#Define a 'finish' procedure
proc finish {} {
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec nam out.nam &
exit
}
#Create six nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$n1 color red
$n1 shape box
Experiment 5
Aim: Implement ESS with transmission nodes in Wireless LAN and obtain the performance parameters.
Theory:
An extended service set (ESS) is one or more interconnected basic service sets (BSSs) and their associated
LANs. Each BSS consists of a single access point (AP) together with all wireless client devices (stations,
also called STAs) creating a local or enterprise 802.11 wireless LAN (WLAN). To the logical link control
layer, the ESS appears as a solitary BSS at any one of the STAs.
Variant Type I:
create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
$n0 label "ESS"
$n1 label "mob1"
$n2 label "mob2"
$n0 set X_ 10
$n0 set Y_ 600
Department of E&CE, SVCE, Bengaluru Page 34
Computer Networks LAB (18ECL76) 2021-22
$n0 set Z_ 0
$n1 set X_ 80
$n1 set Y_ 600
$n1 set Z_ 0
$n2 set X_ 1200
$n2 set Y_ 600
$n2 set Z_ 0
$ns at 0.1 "$n0 setdest 10 600 15"
$ns at 0.1 "$n1 setdest 80 600 25"
$ns at 0.1 "$n2 setdest 1200 600 25"
proc finish { } {
global ns nf tf
$ns flush-trace
exec nam lab5.nam &
close $tf
exit 0
}
$ns at 20 "finish"
$ns run
Steps for execution:
➢ Open gedit editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# gedit lab5.tcl
create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
$n0 label "ESS"
$n1 label "mob1"
$n2 label "mob2"
$n0 set X_ 10
$n0 set Y_ 600
$n0 set Z_ 0
$n1 set X_ 80
proc finish { } {
global ns nf tf
$ns flush-trace
exec nam lab5.nam &
close $tf
exit 0
}
$ns at 20 "finish"
$ns run
Procedure:
➢ Develop a topology shown in the figure given below
➢ Configure access points AP1 & AP2 with different SSID names. port status should be
turned on
➢ Connect a hosts and two WLAN access points to a router
➢ Setup nodes around the two WLAN access points and set the path for each node
Verify the 802.11 wireless parameters in simulation mode
Experiment 6
Theory:
In link state routing, each router shares its knowledge of its neighborhood with every other router in the
internet work. (i) Knowledge about Neighborhood: Instead of sending its entire routing table a router
sends info about its neighborhood only. (ii) To all Routers: each router sends this information to every
other router on the internet work not just to its neighbor. It does so by a process called flooding.
(iii)Information sharing when there is a change: Each router sends out information about the neighbors
when there is change.
Variant Type I:
$ns rtproto LS
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam lab6.nam &
exit 0
}
$ns run
➢ Open gedit editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# gedit lab6.tcl
➢ Save the program and quit.
➢ Run the simulation program
[root@localhost~]# ns lab6.tcl
➢ Here “ns” indicates network simulator. We get the topology shown in the network animator. Now press the
play button in the simulation window and the simulation will begins.
➢ Explain link state routing algorithm using animation. How link state break and rerouting take place.
$ns rtproto LS
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam lab6.nam &
exit 0
$ns run
PART-B:
Theory:
High-Level Data Link Control (HDLC) generally uses term “frame” to indicate and represent an entity of
data or a protocol of data unit often transmitted or transferred from one station to another station. Each
and every frame on link should begin and end with Flag Sequence Field (F). Each of frames in HDLC
includes mainly six fields. It begins with a flag field, an address field, a control field, an information field,
an frame check sequence (FCS) field, and an ending flag field. The ending flag field of one frame can
serve as beginning flag field of the next frame in multiple-frame transmissions.
HDLC is a bit-oriented code-transparent synchronous data link layer protocol developed by the
International Organization for Standardization. HDLC frames can be transmitted over synchronous or
asynchronous serial communication links. Those links have no mechanism to mark the beginning or end
of a frame, so the beginning and end of each frame has to be identified. This is done by using a frame
delimiter, or flag, which is a unique sequence of bits that is guaranteed not to be seen inside a frame.
This sequence is '01111110', or, in hexadecimal notation, 0x7E. Each frame begins and ends with a
frame delimiter. A frame delimiter at the end of a frame may also mark the start of the next frame. A
sequence of 7 or more consecutive 1-bits within a frame will cause the frame to be aborted.
When no frames are being transmitted on a simplex or full-duplex synchronous link, a frame delimiter is
continuously transmitted on the link. Using the standard NRZI encoding from bits to line levels (0 bit =
transition, 1 bit = no transition), this generates one of two continuous waveforms, depending on the initial
state:
This is used by modems to train and synchronize their clocks via phase-locked loops. Some protocols
allow the 0-bit at the end of a frame delimiter to be shared with the start of the next frame delimiter, i.e.
'011111101111110'.
For half-duplex or multi-drop communication, where several transmitters share a line, a receiver on the
line will see continuous idling 1-bits in the inter-frame period when no transmitter is active.
Since the flag sequence could appear in user data, such sequences must be modified during transmission
to keep the receiver from detecting a false frame delimiter. The receiver must also detect when this has
occurred so that the original data stream can be restored before it is passed to higher layer protocols. This
can be done using bit stuffing, in which a "0" is added after the occurrence of every "11111" in the data.
When the receiver detects these "11111" in the data, it removes the "0" added by the transmitter. Bit
stuffing is a process of inserting an extra bit as 0, once the frame sequence encountered 5 consecutive 1's.
Variant Type I:
#include<stdio.h>
int main()
{
int a15];
int i,j,k,n,c=0,pos=0;
printf("\n Enter the number of bits");
scanf("%d",&n);
printf("\n Enter the bits");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
if(a[i]==1)
{
c++;
if(c==5)
{
pos=i+1;
c=0;
for(j=n;j>=pos;j--)
{
k=j+1;
a[k]=a[j];
}
a[pos]=0;
n=n+1;
}
}
else
c=0;
}
for(i=0;i<n;i++) {
printf("%d",a[i]);
}
Execution:
strcpy(des,flag);
di=strlen(flag);
while(src[si]!='\0')
{
if(src[si]=='1')
count ++;
else
count = 0;
des[di++]=src[si++];
if (count == 5)
{
count = 0;
des[di++]='0';
}
}
des[di++]='\0';
printf("stuffed message is %s ", strcat(des,flag));
si = strlen(flag);
StuffedLen = strlen(des)-2*si;
for(di=0;di<StuffedLen; si++, di++)
src[di]=des[si];
src[di] = '\0'; count = 0;
si = 0; di =0;
while (src[si]!='\0')
{
if(src[si]=='1')
count++;
else
count = 0;
des[di++]=src[si++]; if(count==5)
{
count = 0; si++;
//des[di++]=src[si++];
}
}
des[di]='\0';
printf("The destuffed data is %s" , des);
OUTPUT:
Enter the msg bits 01111111
Stuffed message is 0111111001111101101111110
Destuffed msg is 01111111
Department of E&CE, SVCE, Bengaluru Page 47
Computer Networks LAB (18ECL76) 2021-22
Variant Type I:
Program:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
char c[50],d[50],t[50];
int i,m,j;
printf("enter the number of characters\n");
scanf("%d",&m);
printf("\n enter the characters\n");
for(i=0;i<m+1;i++)
{
scanf("%c",&c[i]);
}
printf("\n original data\n");
for(i=0;i<m+1;i++)
printf("%c",c[i]);
d[0]='d';
d[1]='l';
d[2]='e';
d[3]='s';
d[4]='t';
d[5]='x';
for(i=0,j=6;i<m+1;i++,j++)
{
if((c[i]=='d'&&c[i+1]=='l'&& c[i+2]=='e'))
{
d[j]='d';
j++;
d[j]='l';
j++;
d[j]='e';
j++;
m=m+3;
}
d[j]=c[i];
}
m=m+6;
m++;
d[m]='d';
m++;
d[m]='l';
m++;
d[m]='e';
m++;
d[m]='e';
m++;
d[m]='t';
m++;
d[m]='x';
m++;
printf("\n\n transmitted data: \n");
for(i=0;i<m;i++)
{
printf("%c",d[i]);
}
for(i=6,j=0;i <m-6;i++,j++)
{
if(d[i]=='d'&&d[i+1]=='l'&&d[i+2]=='e'&&d[i+3]=='d'&&d[i+4]=='l'&&d[i+5]=='e')
i=i+3;
t[j]=d[i];
}
printf("\n\nreceived data:");
for(i=0;i<j;i++)
{printf("%c",t[i]);
}
}
Execution:
[root@localhost code]# gcc 1b.c
[root@localhost code]# ./a.out
enter the number of characters
9
original data
abcdabcde
transmitted data:
dlestx
abcdabcdedleetx
received data:
abcdabcde
{
clrscr();
int si=0, di =0;
char flag1[max]="DLESTX", flag2[max]="DLEETX", des[max], src[max];
printf("enter the string data:\n"); scanf("%s",&src);
/*stuffing process*/
strcpy(des,flag1);
di=strlen(flag1);
while(src[si]!='\0')
{
if(src[si]=='D'&& src[si+1]=='L'&& src[si+2]=='E')
{
des[di+0]='D', des[di+1]='L', des[di+2]='E',
des[di+3]='D', des[di+4]='L', des[di+5]='E';
di+=6;
si+=3;
}
else des[di++]=src[si++];
}
des[di]='\0';
strcat(des,flag2);
printf("\nthe stuffed string is %s\n",des);
/*destuffing process*/
di = strlen(des)-strlen(flag2);
des[di]='\0';
di=strlen(flag1); for(si=0;des[di]!='\0';si++,di++)
src[si]=des[di];
si=di=0;
while(src[si]!='\0')
{
if(src[si]=='D'&&src[si+1]=='L'&&src[si+2]=='E'&&
src[si+3]=='D'&&src[si+4]=='L'&&src[si+5]=='E')
{
des[di++=src[si++];
}
des[di]='\0';
printf("the destuffed string is %s", des); getch();
}
OUTPUT:
2. Write a program for distance vector algorithm to find suitable path for
transmission.
Theory:
Distance vector routing algorithms operate by having each router maintain a table (i.e.,
vector) giving the best-known distance to each destination and which line to get there. These
tables are updated by exchanging information with the neighbors. A distance-vector routing
protocol in data networks determines the best route for data packets based on distance.
Distance-vector routing protocols measure the distance by the number of routers a packet has
to pass, one router counts as one hop.
Variant Type I:
#include<stdio.h>
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];
int main()
{
int dmat[20][20];
int n,i,j,k,count=0;
printf("\nEnter the number of nodes : ");
scanf("%d",&n);
printf("\nEnter the cost matrix (999 for no link):\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&dmat[i][j]);
dmat[i][i]=0;
rt[i].dist[j]=dmat[i][j];
rt[i].from[j]=j;
}
do
{
count=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
for(k=0;k<n;k++)
if(rt[i].dist[j]>dmat[i][k]+rt[k].dist[j])
{
Department of E&CE, SVCE, Bengaluru Page 54
Computer Networks LAB (18ECL76) 2021-22
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<n;i++)
{
printf("\n\nState value for router %d is \n",i+1);
for(j=0;j<n;j++)
{
printf("\t\nnode %d via %d Distance%d", j+1,rt[i].from[j]+1, rt[i].dist[j]);
}
}
printf("\n\n");
}
Execution:
0 2 999 1
2052
999 5 0 6
1260
#include<stdio.h>
struct rtable
{
int dist[20],nextnode[20];
}table[20];
int cost[10][10],n;
void distvector()
{
int i,j,k,count=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
table[i].dist[j]=cost[i][j];
table[i].nextnode[j]=j;
}
}
do
{
count=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
for(k=0;k<n;k++)
{
if(table[i].dist[j]>cost[i][k]+table[k].dist[j])
{
table[i].dist[j]=table[i].dist[k]+table[k].dist[j];
table[i].nextnode[j]=k;
count++;
}
}
}
}
}while(count!=0);
}
int main()
{
int i,j;
printf("\nenter the no of vertices:\t");
scanf("%d",&n);
printf("\nenter the cost matrix\n");
for(i=0;i<n;i++)
Department of E&CE, SVCE, Bengaluru Page 56
Computer Networks LAB (18ECL76) 2021-22
for(j=0;j<n;j++)
scanf("%d",&cost[i][j]);
distvector();
for(i=0;i<n;i++)
{
printf("\nstate value for router %c \n",i+65);
printf("\ndestnode\tnextnode\tdistance\n");
for(j=0;j<n;j++)
{
if(table[i].dist[j]==99)
printf("%c\t\t-\t\tinfinite\n",j+65);
else
printf("%c\t\t%c\t\t%d\n",j+65,table[i].nextnode[j]+65,table[i].dist[j]);
}}
return 0;
}
OUTPUT:
Figure 12: Output window for the Distance vector routing protocol
Variant Type III:
set ns [new Simulator]
set nr [open thro.tr w]
$ns trace-all $nr
set nf [open thro.nam w]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam thro.nam &
exit 0
}
for { set i 0 } { $i < 12} { incr i 1 } {
set n($i) [$ns node]}
for {set i 0} {$i < 8} {incr i} {
$ns rtproto DV
$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)
OUTPUT:
Dijkstra’s method of computing the shortest path is a static routing algorithm. It involves
building a graph of the subnet, with each node of the graph representing a router and each are
representing a communication line or a link. to find a route between a pair of routers the
algorithm just finds the shortest path between the them on the graph.
In Dijkstra’s algorithms the metric used for calculation is distance. Each node is labled with
its distance from the source node along with the previous node in the path. initially no paths
are known so all nodes are labled with infinity. As the algorithm proceeds and paths are
found, the labels may change reflecting better paths. A label may be either tentative or
permanent. Initially all nodes are tentative and once it is discovered that the shortest possible
path to a node is got it is made permanent and never changed after that Dijkstra algorithm is
also called single source shortest path algorithm. The algorithm maintains a list visited [] of
vertices, whose shortest distance from the source is calculated.
Variant Type I:
#include<stdio.h>
#define INFINITY 9999
#define MAX 10
void dijkstra(int G[MAX][MAX],int n,int startnode);
int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}
void dijkstra(int G[MAX][MAX],int n,int startnode)
{
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
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;
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}
for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}
Execution:
Distance of node1=10
Path=1<-0
Distance of node2=50
Path=2<-3<-0
Distance of node3=30
Path=3<-0
Distance of node4=60
Path=4<-2<-3<-0
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(m[i][k]+m[k][j]<m[i][j])
{
m[i][j] =m[i][k] + m[k][j];
p[i][j] = k;
}
do
{
printf("\n enter the source & Destination nodes\n");
scanf("%d %d",&i,&j);
printf("\n the weight is %d", m[i][j]);
printf("\n the path is");
printf( "%d-->",i);
path(i,j);
printf("%d", j);
printf("\n to repeat press R");
}
while(getch()=='R');
}
void path(int i, int j)
{
int k;
k=p[i][j];
if(k!=0)
{
path(i,k);
printf("%d-->",k);
path(k,j);
}
}
OUTPUT:
4. For the given data, use CRC-CCITT polynomial to obtain CRC code. Verify
the program for the cases
a. Without error
b. With error
The polynomial code (also known as a Cyclic Redundancy code or CRC code) is widely
used. polynomial codes are based upon treating bit string as representations of polynomials
with coefficients of 0 and 1 only. A k-bit frame is regarded as the coefficient list for a
polynomial with k terms, ranging from x k-1 to x0. Such a polynomial is said to be of a
degree k-1. The high order (left most) bit is the coefficient of x k-1; the next bit is the
coefficient of x k-2 and so on. For example, 110001 has 6 bits and thus represents a six-term
polynomial with coefficients.1,1,0,0,0 and 1: x5+x4+1.
When the polynomial code method is employed, the centre and receiver must agree upon a
generator polynomial, G(x) in advanced, both the high and low order bits of the generator
must be one. To compute the checksum for some frame with m bits, corresponding to the
polynomial M(x) the frame must be longer than the generator polynomial. the idea is so to
append a checksum to the end of the frame in such a way that the polynomial represented by
the check summed frame is divisible by G(x).When the receiver gets the check summed
frame, it tries dividing it by G(x).If there is a remember there has been a transmission error.
Cyclic Redundancy Check is error checking technique it does error checking via polynomial
division.
Variant Type I:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N strlen(g)
char t[128],cs[128],g[]="1000100000010001";
int a,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++)
Department of E&CE, SVCE, Bengaluru Page 65
Computer Networks LAB (18ECL76) 2021-22
cs[c]=cs[c+1];
cs[c]=t[e++];
}while(e<=a+N-1);
}
int main(){
printf("\nEnter poly:");
scanf("%s",t);
printf("\nGenerating Polynomial is: %s",g);
a=strlen(t);
for(e=a;e<a+N-1;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("\nFinal Codeword is: %s",t);
printf("\nTest Error detection 0 (Yes) 1 (No) ? : ");
scanf("%d",&e);
if(e==0){
printf("Enter postion where error is to be inserted:");
scanf("%d",&e);
t[e]=(t[e]=='0')?'1':'0';
printf("Erroneous Data: %s\n",t);
}
crc();
for(e=0;(e<N-1)&&(cs[e]!='1');e++);
if(e<N-1)
printf("Error Detected");
else printf("No Error Detected");
return 0;
}
Execution:
[root@localhost code]# gcc 4.c
[root@localhost code]# ./a.out
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define degree 3
int res[30];
int getnext(int array[],int);
void crc(int len)
{
int cp[]={1,0,1,1};
int i=0,pos=0,newpos;
while(pos<len-degree)
{
for(i= pos;i<pos+degree+1;++i)
res[i]=res[i]^cp[i-pos];
newpos=getnext(res,pos);
if(newpos>pos+1)
pos= newpos-1;
++pos;
}
}
int getnext(int array[], int pos)
{
int i = pos;
while( array[i] ==0)
++i;
return i;
}
void main()
{
int array[30];
char ch;
int len,i=0;
puts("enter the data stream:");
while((ch =getche())!='\r')
array[i++] = ch-'0';
len=i;
for(i=0;i<degree; ++i)
array[i+len]=0;
len+= degree;
for(i=0;i<len;i++)
res[i]=array[i];
crc(len);
printf("\n the transmitted frame is: ");
for(i=0; i<len-degree; ++i)
printf("%d", array[i]);
for(i=len-degree; i<len;++i)
printf("%d", res[i]);
printf("\nEnter the stream for which crc to be checked");
i=0;
while((ch=getche())!='\r')
array[i++]= ch-'0';
len=i;
for(i=0;i<len;i++)
res[i]=array[i];
crc(len);
printf("\n checksum: ");
for(i=len-degree; i<len;i++)
printf("%d", res[i]);
}
OUTPUT:
Without error
Enter data stream 10011
Transmitted frame is 10011100
Enter the stream for which CRC to be checked 10011100
Checksum: 000
With error
Enter data stream 10011
Transmitted frame is 10011100
Enter the stream for which crc to be checked 10011101
Checksum: 001
#include<stdio.h>
char m[50],g[50],r[50],q[50],temp[50];
void caltrans(int);
void crc(int);
void calram();
void shiftl();
int main()
{
int n,i=0;
char ch,flag=0;
printf("Enter the frame bits:");
while((ch=getc(stdin))!='\n')
m[i++]=ch;
n=i;
for(i=0;i<16;i++)
m[n++]='0';
m[n]='\0';
printf("Message after appending 16 zeros:%s",m);
for(i=0;i<=16;i++)
g[i]='0';
g[0]=g[4]=g[11]=g[16]='1';g[17]='\0';
printf("\ngenerator:%s\n",g);
crc(n);
printf("\n\nquotient:%s",q);
caltrans(n);
printf("\ntransmitted frame:%s",m);
printf("\nEnter transmitted frame:");
scanf("\n%s",m);
printf("CRC checking\n");
crc(n);
printf("\n\nlast remainder:%s",r);
for(i=0;i<16;i++)
if(r[i]!='0')
flag=1;
else
continue;
if(flag==1)
printf("Error during transmission");
else
printf("\n\nReceived freme is correct");
}
void crc(int n)
{
int i,j;
for(i=0;i<n;i++)
temp[i]=m[i];
for(i=0;i<16;i++)
r[i]=m[i];
printf("\nintermediate remainder\n");
for(i=0;i<n-16;i++)
{
if(r[0]=='1')
{
q[i]='1';
calram();
}
else
{
q[i]='0';
shiftl();
}
r[16]=m[17+i];
r[17]='\0';
printf("\nremainder %d:%s",i+1,r);
for(j=0;j<=17;j++)
temp[j]=r[j];
}
q[n-16]='\0';
}
void calram()
{
int i,j;
for(i=1;i<=16;i++)
r[i-1]=((int)temp[i]-48)^((int)g[i]-48)+48;
}
void shiftl()
{
int i;
for(i=1;i<=16;i++)
r[i-1]=r[i];
}
void caltrans(int n)
{
int i,k=0;
for(i=n-16;i<n;i++)
m[i]=((int)m[i]-48)^((int)r[k++]-48)+48;
m[i]='\0';
}
Theory:
In computer networks sliding window protocol is a method to transmit data on a
network. Stop and wait protocol and Sliding window protocol are applied on the Data
Link Layer of OSI model. At data link layer data is in the form of frames. In
Networking, Window simply means a buffer which has data frames that needs to be
transmitted.
Flow Control:
Consider a situation in which the sender transmits frames faster than the receiver
can accept them. If the sender keeps pumping out frames at high rate, at some point the
receiver will be completely swamped and will start losing some frames. This problem
may be solved by introducing flow control. Most flow control protocols contain a
feedback mechanism to inform the sender when it should transmit the next frame.
Variant Type I:
#include<stdio.h>
#define w 1
int main()
{
int i,f,frames[50];
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("\nWith stop and wait 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);
printf("if error occur negative acknowledge is detected same frame is resend back\n");
for(i=1;i<=f;i++)
{
if((random()%2)==1)
{
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]);
}
else
{
sleep(3);
printf("negative acknowledge resend %d frame\n",i);
i=i-1;
sleep(1);
Department of E&CE, SVCE, Bengaluru Page 71
Computer Networks LAB (18ECL76) 2021-22
}
return 0;
}
Execution:
Enter 6 frames: 1
4
5
7
8
9
With stop and wait protocol the frames will be sent in the following manner (assuming no corruption
of frames)
After sending 1 frames at each stage sender waits for acknowledgement sent by the receiver
5
Acknowledgement of above frames sent is received by sender
7
Acknowledgement of above frames sent is received by sender
8
Acknowledgement of above frames sent is received by sender
rand();
noframes=rand()/200;
i=1;j=1;
noframes=noframes/8;
printf(“\n Number of frames is %d”,noframes);
while(noframes>0)
{
printf(“\n Sending frames %d”,i);
strand(x1++);
x=rand()%10;
if(x%2==0)
{
for(x2=1;x2<2;x2++)
{
Printf(“Waiting for %d seconds \n”,x2);
sleep(x2);
}
printf(“\n sending frame %d”,i);
strand(x1++);
x=rand()%10;
}
printf(“\n ack for frame %d”.j);
noframes-=1;
i++;j++;
}
printf(“\n end of stop and wait protocol”);
}
Type III:
# stop and wait protocol in normal situation
# features : labeling, annotation, nam-graph, and window size monitoring
set ns [new Simulator]
$ns at 0.0 "$ns trace-annotate \"Stop and Wait with normal operation\""
$ns at 0.05 "$ns trace-annotate \"FTP starts at 0.1\""
$ns at 0.11 "$ns trace-annotate \"Send Packet_0\""
$ns at 0.35 "$ns trace-annotate \"Receive Ack_0\""
$ns at 0.56 "$ns trace-annotate \"Send Packet_1\""
$ns at 0.79 "$ns trace-annotate \"Receive Ack_1\""
$ns at 0.99 "$ns trace-annotate \"Send Packet_2\""
$ns at 1.23 "$ns trace-annotate \"Receive Ack_2 \""
$ns at 1.43 "$ns trace-annotate \"Send Packet_3\""
$ns at 1.67 "$ns trace-annotate \"Receive Ack_3\""
$ns at 1.88 "$ns trace-annotate \"Send Packet_4\""
$ns at 2.11 "$ns trace-annotate \"Receive Ack_4\""
$ns at 2.32 "$ns trace-annotate \"Send Packet_5\""
$ns at 2.55 "$ns trace-annotate \"Receive Ack_5 \""
$ns at 2.75 "$ns trace-annotate \"Send Packet_6\""
$ns at 2.99 "$ns trace-annotate \"Receive Ack_6\""
$ns at 3.1 "$ns trace-annotate \"FTP stops\""
proc finish {} {
global ns nf
$ns flush-trace
close $nf
puts "running nam..."
exec nam stop.nam &
exit 0
}
$ns run
OUTPUT:
Variant Type I:
#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++)
Department of E&CE, SVCE, Bengaluru Page 75
Computer Networks LAB (18ECL76) 2021-22
scanf("%d",&frames[i]);
printf("\nWith sliding window protocol the frames will be sent in the following manner (assuming no
corruption of frames)\n\n");
printf("After sending %d frames at each stage sender waits for acknowledgement sent by the
receiver\n\n",w);
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;
}
Execution:
Enter 5 frames: 12 20 87 65 4
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 20 87
Acknowledgement of above frames sent is received by sender
65 4
Acknowledgement of above frames sent is received by sender
#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("\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:
Theory:
The leaky-bucket implementation is used to control the rate at which traffic is sent to the
network. A leaky bucket provides a mechanism by which bursty traffic can be shaped to
present a steady stream of traffic to the network, as opposed to traffic with erratic bursts of
low-volume and high-volume flows.
Traffic analogy an appropriate analogy for the leaky bucket is a scenario in which four lanes
of automobile traffic converge into a single lane. A regulated admission interval into the
single lane of traffic flow helps the traffic move. The benefit of this approach is that traffic
flow into the major arteries (the network) is predictable and controlled. The major liability is
that when the volume of traffic is vastly greater than the bucket size, in conjunction with the
drainage-time interval, traffic backs up in the bucket beyond bucket capacity and is
discarded. In Leaky bucket, each host is connected to the network by an interface containing
a leaky bucket, that is, a finite internal queue. If a packet arrives at the queue when it is full,
the packet is discarded.
Variant Type I:
#include<stdio.h>
#include<stdlib.h>
int bucket_size;
void bucket_input ( int pkt_sz, int op_rt )
{
if( pkt_sz > bucket_size )
Bucket overflow
Bucket overflow
Bucket overflow
Bucket overflow
#include<stdio.h>
#include<stdlib.h>
int trand(int a)
{
int rn;
rn=random()%10;
rn=rn%a;
if(rn==0)
rn=1;
return(rn);
}
int main()
{
int i,packet[5],psz,bsz,pszrn=0,clk,ptime,premain,orate,flag=0;
for(i=0;i<5;i++)
packet[i]=trand(6)*10;
printf("\nenter the o/p rate");
scanf("%d",&orate);
printf("\nenter the bucket size");
scanf("%d",&bsz);
for(i=0;i<5;i++)
{
if((packet[i]+pszrn)>bsz)
printf("\n incoming packet size %d is greater than bucket size_reject",packet[i]);
else
{
for(;;)
{
premain=4-i;
psz=packet[i];
pszrn+=psz;
printf("\nincoming packet size is %d",psz);
printf("\n no.of packets waiting for transmission= %d",pszrn);
ptime=trand(4)*10;
printf("\nnext packet will come at %d",ptime);
for(clk=0;clk<=ptime;clk++)
{
printf("\ntime left =%d",ptime-clk);
sleep(1);
if(pszrn)
{
if(pszrn==0)
printf("\nbucket is empty");
else
{
if(pszrn>=orate)
printf("%d bytes are tranmited",orate);
else
printf("\n %d bytes are transmitted",pszrn);
}
if(pszrn<=orate)
pszrn=0;
else
pszrn-=orate;
printf("\nbytes remaining %d ",pszrn);
}
else
printf("\nbytes remaing %d ",pszrn);
}
if(pszrn!=0)
flag=1;
break;
}
}
}
printf("\n\n");
return 0;
}
Output:
enter the o/p rate10
enter the bucket size5
incoming packet size 30 is greater than bucket size_reject
incoming packet size 10 is greater than bucket size_reject
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;
}
Department of E&CE, SVCE, Bengaluru Page 83
Computer Networks LAB (18ECL76) 2021-22
}
else
{
drop=0;
count=0;
}
printf(" \t %d \t %d \n",drop,count);
}
return 0;
}
Additional Programs
Experiment No: 1
TRANSMISSION OF PING MESSAGE
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab4.nam &
exit 0
}
$ns at 0.1 "$p1 send"
$ns at 0.2 "$p1 send"
$ns at 0.3 "$p1 send"
$ns at 0.4 "$p1 send"
$ns at 0.5 "$p1 send"
$ns at 0.6 "$p1 send"
$ns at 0.7 "$p1 send"
$ns at 0.8 "$p1 send"
$ns at 0.9 "$p1 send"
$ns at 1.0 "$p1 send"
$ns at 1.1 "$p1 send"
$ns at 1.2 "$p1 send"
$ns at 1.3 "$p1 send"
$ns at 1.4 "$p1 send"
$ns at 1.5 "$p1 send"
$ns at 1.6 "$p1 send"
$ns at 1.7 "$p1 send"
$ns at 1.8 "$p1 send"
$ns at 1.9 "$p1 send"
$ns at 2.0 "$p1 send"
$ns at 2.1 "$p1 send"
$ns at 2.2 "$p1 send"
$ns at 2.3 "$p1 send"
$ns at 2.4 "$p1 send"
$ns at 2.5 "$p1 send"
$ns at 2.6 "$p1 send"
$ns at 2.7 "$p1 send"
$ns at 2.8 "$p1 send"
$ns at 2.9 "$p1 send"
$ns at 0.1 "$p3 send"
$ns at 0.2 "$p3 send"
AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk”
extension)
BEGIN{
drop=0;
}
{
if($1= ="d" )
{
drop++;
}
}
END{
printf("Total number of %s packets dropped due to congestion =%d\n",$5,drop);
Experiment No: 2
Client-server socket programming
Socket characteristics
Sockets are characterized by their domain, type and transport protocol. Common domains
are:
➢ AF_UNIX: address format is UNIX pathname
➢ AF_INET: address format is host and port number
Use of sockets:
➢ Connection–based sockets communicate client-server: the server waits for a
connection from the client
➢ Connectionless sockets are peer-to-peer: each process is symmetric.
socket API
#include<sys/types.h>
#include<sys /socket.h>
Sockaddr :
listen
#include <sys / types.h>
#include <sys / socket.h>
int listen (int sid, int size) ;
Where size it the number of pending connection requests allowed (typically limited by Unix
kernels to 5). Returns the 0 on success, or -1 if failure.
accept
#include <sys / types.h>
#include <sys / socket.h>
int accept(int sid ,struct sockaddr *addrPtr , int *lenPtr )
Returns the socketId and address of client connecting to socket.
send
#include <sys / types.h>
#include <sys / socket.h>
int send(int sid ,const char *bufferPtr ,int len ,int flag)
Send a message. Returns the number of bytes sent or -1 if failure.
(Must be a bound socket).
flag is either
« 0: default
« MSG OOB: Out-of-band high priority communication
recv
#include <sys / types.h>
#include <sys / socket.h>
int recv ( int sid , char *bufferPtr , int len , int flags)
Receive up to len bytes in bufferPtr. Returns the number of bytes received or -1 on failure.
flags can be either
Shutdown:
include <sys / types.h>
#include <sys / socket.h>
Department of E&CE, SVCE, Bengaluru Page 89
Computer Networks LAB (18ECL76) 2021-22
Source Code:
Client Side:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<string.h>
#define SERV_TCP_PORT 6880
#define SERV_HOST_ADDR "127.0.0.1"
int main()
{
int sockfd;
struct sockaddr_in serv_addr,cli_addr;
char filename[100],buf[1000];
int n;
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(SERV_HOST_ADDR);
serv_addr.sin_port=htons(SERV_TCP_PORT);
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
printf("Client:cant open stream socket\n");
else
printf("Client:stream socket opened successfully\n");
if(connect(sockfd,(struct sockaddr *)&serv_addr,
sizeof(serv_addr))<0)
printf("Client:cant connect to server\n");
else
printf("Client:connected to server successfully\n");
printf("\n Enter the file name to be displayed :");
scanf("%s",filename);
write(sockfd,filename,strlen(filename));
printf("\n filename transfered to server\n");
n=read(sockfd,buf,1000);
if(n < 0)
printf("\n error reading from socket");
printf("\n Client : Displaying file content of %s\n",filename);
fputs(buf,stdout);
close(sockfd);
exit(0);
AT CLIENT SIDE
[root@localhost ]# cc tcpc.c
[root@localhost ]# ./a.out
Data Sent
File Content....
Sockets are a mechanism for exchanging data between processes. These processes can
either be on the same machine, or on different machines connected via a network. Once a socket
connection is established, data can be sent in both directions until one of the endpoints closes the
connection.
I needed to use sockets for a project I was working on, so I developed and refined a few
C++ classes to encapsulate the raw socket API calls. Generally, the application requesting the
data is called the client, and the application servicing the request is called the server. I created two
primary classes, ClientSocket and ServerSocket, that the client and server could use to exchange
data.
SERVER SIDE:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<string.h>
#define SERV_TCP_PORT 6880
#define SERV_HOST_ADDR "127.0.0.1"
int main()
{ int sockfd,newsockfd,clilen;
struct sockaddr_in cli_addr,serv_addr;
char filename[25],buf[1000];
int n,m=0;
int fd;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
printf("server:cant open stream socket\n");
else
printf("server:stream socket opened successfully\n");
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_addr.sin_port=htons(SERV_TCP_PORT);
if((bind(sockfd,(struct sockaddr *)
&serv_addr,sizeof(serv_addr)))<0)
printf("server:cant bind local address\n");
else
printf("server:bound to local address\n");
listen(sockfd,5);
printf("\n SERVER : Waiting for client...\n");
for(;;)
{
clilen=sizeof(cli_addr);
newsockfd=accept(sockfd,(struct sockaddr *) &cli_addr,&clilen);
if(newsockfd<0)
printf("server:accept error\n");
else
printf("server:accepted\n");
n=read(newsockfd,filename,25);
filename[n]='\0';
printf("\n SERVER : %s is found and ready to transfer
\n",filename);
fd=open(filename,O_RDONLY);
n=read(fd,buf,1000);
buf[n]='\0';
write(newsockfd,buf,n);
printf("\n transfer success\n");
close(newsockfd);
exit(0)
}
}
Output:
[root@localhost ]# cc tcps.c
[root@localhost ]# ./a.out
Received the file name : data.txt
File content sent.
Experiment No: 3
Client-Server Communication Using Message Queues or FIFO
Aim: C Program for CLIENT SERVER communication using message Queues or FIFOs as IPC
channels that client sends the file name and the server to send back the contents of the requested
file if present.
Source Code:
#SERVER*/
#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int main()
{
char filename[100],buf[300],buf1[300];
int num,num2,n,filesize,fl,fd,fd2;
mknod("fifo1",S_IFIFO | 0666,0);
mknod("fifo2",S_IFIFO | 0666,0);
printf("\n Server Online\n");
fd=open("fifo1",O_RDONLY);
printf("Client Online! Waiting for request...\n\n");
while(1)
{
num = read(fd,filename,100);
Department of E&CE, SVCE, Bengaluru Page 93
Computer Networks LAB (18ECL76) 2021-22
filename[num]='\0';
fl=open(filename,O_RDONLY);
printf("\n Sever: %s is found!\n transferring the contents\n",filename);
filesize=lseek(fl,0,2);
printf("\n File size is %d\n",filesize);
lseek(fl,0,0);
n=read(fl,buf1,filesize);
buf1[n]='\0';
fd2=open("fifo2",O_WRONLY);
write(fd2,buf1,strlen(buf1));
printf("\n SERVER :Transfer completed\n");
exit(1);
}
unlink("fifo1");
unlink("fifo2");
}
Output:
AT SERVER SIDE
[root@localhost ]# cc prg6s.c
[root@localhost ]# ./a.out
SERVER online!
CLIENT online!