Final Computer Network Lab Mannual (18ECL76)
Final Computer Network Lab Mannual (18ECL76)
Final Computer Network Lab Mannual (18ECL76)
SEMESTER-VII
COMPUTER NETWORK LABORATORY
(18ECL67)
Assistant Professor
CONTENTS
PART- A
1. 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 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
Write a program for a HLDC frame to perform the following i) Bit Stuffing ii) Character
1.
Stuffing.
Write a program for distance vector algorithm to find suitable path for transmission.
2.
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
5. Implementation of Stop and Wait Protocol and Sliding Window Protocol
The purpose of this is to acquaint the students with an overview of the Computer Networks from the
perspective how the information is transferred from source to destination and different layers in
networks. This course provides a basis for u. They can understand how the data transferred from
source to destination. They can come to know that how the routing algorithms worked out in network
layer understanding the networking techniques that can take place in computer. A computer network
is made of two distinct subsets of components
Distributed applications are programs running on interconnected computers; a web server, a remote
login server, an e-mail exchanger are examples. This is the visible part of what people call “the
Internet”. In this lecture we will study the simplest aspects of distributed applications. More
sophisticated aspects are the object of lectures called “Distributed Systems” and “Information
Systems”. The network infrastructure is the collection of systems which are required for the
interconnection of computers running the distributed applications. It is the main focus of this lecture.
The network infrastructure problem has itself two aspects: Distance: interconnect remote systems
that are too far apart for a direct cable connection Meshing: interconnect systems together; even in
the case of systems close to each other, it is not possible in non-trivial cases to put cables from all
systems to all systems (combinatorial explosion, cable salad management problem s etc.).
Intel based desktop PC with minimum of 2.6GHZ or faster processor with at least 1 GB RAM and
40 GB free disk space and LAN connected.
Operating system: Linux (Redhat Linux)
Software : Programming on Linux using GNU Compiler Collection: gcc
NS-2 Simulator
NS2 is an open-source object oriented, discrete, event-driven network simulator written in C++ and
Tool Command Language (Tcl) with Object Oriented extensions (OTcl). It implements network
protocols for network simulations. NS-2 includes a tool for viewing the simulation results, called
network animator (NAM). NAM is a Tool Command Language/Toolkit (Tcl/Tk) based animation
tool for viewing network simulation results and real-world packet trace data.
The first step in using NAM is to produce the trace file. The trace file should contain topology
information, for example, nodes, links, as well as packet traces. Usually, the trace file is generated
by ns. During an ns simulation, the user can produce topology configurations, layout information,
and packet traces using tracing events in ns. When the trace file is generated, it is ready to be animated
by NAM. Upon start-up NAM will read the trace file, create topology, pop-up a window, do layout
if necessary, and then pause at the time of the first packet in the trace file. Though its user interface,
NAM provides control over many aspects of animation.
To model a network simulation using NS-2, it is necessary to write a Tcl script describing the
topology (nodes, agents, applications, etc). NS2 provide users with an executable command “ns”
which takes one input argument which is the name of a Tcl simulation scripting file. A simulation
trace file is then created which can be used to plot graphs and/or to create animations. AWK is a
scripting language tool used for manipulating data and generating reports. It searches one or more
files to see if they contain lines that matches with the specified patterns and performs the associated
actions.
The Trace file contains 12 columns:Event type, Event time, From Node, To Node, Packet Type,
Packet Size, Flags (indicated by --------), Flow ID, Source address, Destination address, Sequence
ID, Packet ID
To visualize the result, use a NAM. You can either start a NAM with the command ‘nam <nam-file>’
where ‘<nam-file>’ is the name of a NAM trace file that was generated by ns or we can executeit
directly out of the Tcl simulation script for the simulation which we want to visualize.
Study of NS-2 Simulator
NS2 plays a very important role as a simulation tool for implementing different protocol like the
physical layer protocol (ETHERNET, DSL, MAC etc.), routing protocols (RIP, IGRP), Transport
layer protocol (TCP, UDP) and Network protocols(IP) of different types of network. NS2 is widely
used tool to simulate the behavior of wired and wireless networks.
NS2 supports for simulation of both wired and wireless network and is best suitable for the projects
related to networking as it works on packet transmission scenarios i.e. how packets can be transmitted
or received from source to destination which offers packet level inspection i.e. how it is dropped,
percentage of packet dropped and why it is dropped using various traffic generators which generates
traffic using different parameters.
In general, NS2 provides users with a way of specifying different network protocols and simulating
their corresponding behaviors.Various traffic generators are present for generating traffic at source
nodes in wired network simulation, for example, CBR, VBR, and Exponential etc. NAM stands for
Network Ani Mator window is a visualization tool used in NS2 to provide outputs on a Window
screen which shows the network scenarios like at what time and at how much rate data packets starts
dropping etc.
For detailed study of NS-2, please refer to the ns manual. The ns manual can be downloaded from
http://www.isi.edu/nsnam/ns/doc/ns-doc.pdf
Note: The NAM topology, Trace file and output plots (graphs) are shown at end of each part-A
experiment as a reference.
PART-A
Simulation Experiments
using NS2
Experiment No. -1
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 bandwidth.
Aim: To implement a point to point network using four nodes duplex links between them and also
analyse the network performance by setting the queue size and varying the bandwidth.
Theory:
ftp0
tcp0
BW=100MB D=20ms
N0 Q=20 sink3
BW=100MB
D=20ms
Q=20
N2 N3
BW=100MB sink2
D=20ms
N1 Q=20
tcp1
ftp1
❖ N0, N1, N2, N3 Nodes (N0 and N1 are Source Nodes, N2-Intermediate Node,
N3-Destination Node)
❖ tcp0, tcp1 Transmission Control Protocol (TCP)
❖ sink0, sink1 TCP Agent connected to ‘N3’ and it reacts to TCP Packets
Note:
A small wired network topology consisting of four nodes, initially the bandwidth, delay and queue
size of all three duplex links remains same, later the bandwidth is varied to 0.1, 0.01, 0.001 and
500MB and queue size to 3, 5, 10, 20. FTP is an application layer protocol, which generates packets
and transmits it through transport layer (TCP Protocol). Control and data packets are routed from
N0-N2-N3 and N1-N2-N3. First, the control packets are transmitted between source and destination
node to check the connectivity. The above network topology can also be created using NSG2.1 Tool.
Code:
#===================================
# Simulation parameters setup
#===================================
set val(stop) 50.0 ;# time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
$ns run
Awk Script (lab1.awk)
BEGIN{
a=0
b=0
}
{
if($1=="r"&&$3=="2"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
a++;
}
if($1=="d"&&$3=="2"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
b++;
}
}
END{
printf("\n total number of data packets received at Node 3: %d\n", a++);
printf("\n total number of packets dropped between Node 2 and Node 3: %d\n", b++);
}
Step 1: Type the above program in text editor and save it with the filename and extension “.tcl”
For Example, lab1.tcl
• tcl- Tool Command Language
Step 2: Run the program in terminal window
[root@localhost ~]# ns lab1.tcl
• ns-Network Simulator
Step 3: Once the simulation is completed, run awk file to observe the output
[root@localhost ~]# awk -f lab1.awk lab1.tr
• tr- trace file
Simulation Result
Terminal
NAM File
Experiment No. -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.
Aim: To implement a four node point to point network with links N0- N2, N1- N2 and N2-N3 by
applying TCP agent between N0-N3 and UDP between N1-N3. Also determine the number of
packets sent by TCP/UDP by changing the parameter.
Theory:
ftp0
tcp0
BW=100MB
D=20ms
N0 Sink3
Q=20
BW=100MB
D=20ms
Q=20
N2 N3
BW=100MB null2
D=20ms
N1 Q=20
udp1
cbr1
❖ null-Agent
This network consists of 4 nodes (N0, N1, N2, N3) as shown in above figure. The duplex links
between n0 and n2, n1 and n2, and n2 and n3 have 100 Mbps of bandwidth and 20 ms of delay. Each
node uses a DropTail queue with queue size is 20. A "tcp" agent is attached to n0, and a connection
is established to a tcp "sink" agent attached to n3. The packet size of a "tcp" agent will be of 1540Byte
and udp agent will be 1000Byte. A tcp "sink" agent generates and sends ACK packets to the sender
(tcp agent) and frees the received packets. A "udp" agent that is attached to n1 is connected to a "null"
agent attached to n3. A "null" agent just frees the packets received. A "ftp" and a "cbr" traffic
generator are attached to "tcp" and "udp" agents respectively. The "cbr" is set to start at 1.0 sec and
stop at 23.0 sec, and "ftp" is set to start at 24.0 sec and stop at 48.0 sec.
Code:
#===================================
# Simulation parameters setup
#===================================
set val(stop) 50.0 ;# time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
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(lab2.awk)
BEGIN{
a=0
b=0
}
{
if($1=="r"&&$4=="2"&&$5=="tcp"&&$6=="1040")
{
a++;
}
if($1=="r"&&$4=="2"&&$5=="cbr"&&$6=="1000")
{
b++;
}
}
END{
printf("\n total number of TCP data packets sent between Node 0 and Node 2: %d\n", a++);
printf("\n total number of UDP data packets sent between Node 1 and Node 2: %d\n", b++);
}
Simulation Result
Terminal
NAM File
Experiment No. -3
Aim: Implement Ethernet LAN using (6-10) nodes and also compare the throughput by changing
the error rate and data rate.
Theory:
cbr
udp
N0 N1 N2 N3
LAN1
LAN2
N5 N6 N7 N4
null
This network consists of 8 nodes (N0, N1, N2, N3, N4, N5, N6, N7) as shown in above figure. Four
nodes (N0, N1, N2, N3) are attached to LAN1 and other four nodes are attached to LAN2, which is
have 100 Mbps of bandwidth and 300 ms of delay and each node uses a DropTail queue. The agent
"udp" is attached to N1, and a connection is established to a "null" agent attached to N7 and the
packet size of udp agent will be 1000Byte. The packets are transmitted from node N1 to LAN1-N3-
N4-LAN2-N7 and an error model is introduced between the path of LAN1 and LAN2. The function
of error model is to drop the packets that are transmitted to it and higher the error rate more the
packets are dropped. Throughput is the performance parameter of the network which depends upon
packet received, packet size and simulation time.
Code:
set ns [new Simulator]
set tf [open lab3.tr w]
$ns trace-all $tf
$ns make-lan "$n0 $n1 $n2 $n3" 100Mb 300ms LL Queue/DropTail Mac/802_3
$ns make-lan "$n4 $n5 $n6 $n7" 100Mb 300ms LL Queue/DropTail Mac/802_3
# set error rate. Here Error Model is a class and it is single word and space should not be given
between Error and Model
# loss model is a command and it is single word. Space should not be given between loss and
model
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab3.nam &
exit 0
}
}
{
if($1=="r"&&$4=="7"&&$5=="cbr"&&$6=="1000")
{
a++;
}
}
END{
printf("\n total number of data packets at Node 7: %d\n", a++);
}
Note:
Packet Size: 1000Bytes
Simulation End Time: 3 Sec
Throughput=Packet received*Packet Size/Simulation End Time
Simulation Result
Serial Received at Throughput
Error Rate Data Rate
No. Node 7 (kbps)
1 0.1 0.001 68 22.67
Terminal
NAM File
Trace File
Experiment No. -4
Implement Ethernet LAN using N nodes and assign multiple traffic to the
nodes and obtain congestion window for different sources/ destinations
Aim: To implement Ethernet LAN using N nodes and assign multiple traffic to the nodes and obtain
congestion window for different sources and destinations
Theory:
This network consists of 4 nodes (N0, N1, N2, N3) connected to single LAN1 and, node N0 and N2
are connected to traffic generator (ftp) act as source. Node N1 and N3 are connected to TCP agent
sink, works as destination. Source node N2 and N0 sends the packets to N1 and N3 through common
channel LAN1. After the execution of this program, we will get two output files such as file1.tr and
file2.tr; these are attached to node N0 and N2. File1.tr and file2.tr consists of time period, congestion
window size, source and destination address and port number. Congestion window size keep on
increasing continuously till successful transmission and it resets window size to one, when source
node start getting negative acknowledge packets.
Code:
set ns [new Simulator]
set tf [open lab4.tr w]
$ns trace-all $tf
set nf [open lab4.nam w]
$ns namtrace-all $nf
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
$ns make-lan "$n0 $n1 $n2 $n3" 10mb 10ms LL Queue/DropTail Mac/802_3
set tcp0 [new Agent/TCP/Reno]
$ns attach-agent $n0 $tcp0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
set sink3 [new Agent/TCPSink]
$ns attach-agent $n3 $sink3
$ns connect $tcp0 $sink3
set tcp2 [new Agent/TCP]
$ns attach-agent $n2 $tcp2
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
set sink1 [new Agent/TCPSink]
$ns attach-agent $n1 $sink1
$ns connect $tcp2 $sink1
######To trace the congestion window##########
set file1 [open file1.tr w]
$tcp0 attach $file1
$tcp0 trace cwnd_
set file2 [open file2.tr w]
$tcp2 attach $file2
$tcp2 trace cwnd_
proc finish { } {
global nf tf ns
$ns flush-trace
exec nam lab4.nam &
close $nf
close $tf
exit 0
}
$ns at 0.1 "$ftp0 start"
$ns at 4.5 "$ftp0 stop"
$ns at 1.5 "$ftp2 start"
$ns at 4 "$ftp2 stop"
$ns at 5.0 "finish"
$ns run
Awk Script (lab4.awk)
BEGIN {
tcppack1=0
tcppack2=0
}
{
Step 1: Type the above program in text editor and save it with the filename and extension “.tcl”
• ns-Network Simulator
Step 3: Once the simulation is completed, run awk file to observe the output
NAM File:
Simulation Result:
Table 1: Above values are taken from file1.tr and file2.tr
20 TCP
10
0
1 2 3 4
Simulation Time
Experiment No. -5
Implement ESS with transmission nodes in Wireless LAN and obtain then
Performance Parameters.
Aim: To implement ESS with transmission nodes in Wireless LAN and obtain then performance
parameters.
Theory:
N7
N6
ftp0 ftp4
N0 N3
tcp0 tcp11
N1 N2 N4 N5
sink10 sink9
The above network consists of 8 nodes, among these nodes N1 and N4 acts as source and, N2 and
N5 as destination. Node N0 and N3 performs as access point 1 and 2, whereas N6 and N7 behaves
as router and server/gateway. This network has 2 BSS group (Basic Service Set) i.e N0, N1, N2 and
N3, N4, N5. Group of more than one BSS is called as ESS (Extended Service Set).
Node N1 sends tcp packets to N5 through N1-N0-N6-N3-N5 similarly N4 sends tcp packets to N2
through the path N4-N3-N6-N0-N2.
Code:
#===================================
# Simulation parameters setup
#===================================
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagation model
set val(netif) Phy/WirelessPhy ;# network interface type
set val(mac) Mac/802_11 ;# MAC type
set val(ifq) Queue/DropTail/PriQueue ;# interface queue type
set val(ll) LL ;# link layer type
set val(ant) Antenna/OmniAntenna ;# antenna model
set val(ifqlen) 50 ;# max packet in ifq
set val(nn) 8 ;# number of mobilenodes
set val(rp) AODV ;# routing protocol
set val(x) 2483 ;# X dimension of topography
set val(y) 2506 ;# Y dimension of topography
set val(stop) 6.0 ;# time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#===================================
# Mobile node parameter setup
#===================================
$ns node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-channel $chan \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON \
-movementTrace ON
#===================================
# Nodes Definition
#===================================
#Create 8 nodes
set n0 [$ns node]
$n0 set X_ 1752
$n0 set Y_ 1142
$n0 set Z_ 0.0
#===================================
# 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 3.0 "$ftp0 stop"
#Setup a FTP Application over TCP connection
set ftp4 [new Application/FTP]
$ftp4 attach-agent $tcp11
$ns at 3.5 "$ftp4 start"
$ns at 5.0 "$ftp4 stop"
#===================================
# Termination
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam lab5.nam &
exit 0
}
for {set i 0} {$i < $val(nn) } { incr i } {
$ns at $val(stop) "\$n$i reset"
}
$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 (lab5.awk)
BEGIN{
source1=0
source2=0
source3=0
source4=0
}
{
if($1=="s"&&$3=="_1_"&&$4=="AGT"&&$7=="tcp"&&$8=="1540")
{
source1++;
}
if($1=="s"&&$3=="_4_"&&$4=="AGT"&&$7=="tcp"&&$8=="1540")
{
source2++;
}
if($1=="r"&&$3=="_2_"&&$4=="AGT"&&$7=="tcp"&&$8=="1540")
{
source3++;
}
if($1=="r"&&$3=="_5_"&&$4=="AGT"&&$7=="tcp"&&$8=="1540")
{
source4++;
}
}
END{
printf("\n total number of data packets Sent by Node 1: %d\n", source1++);
printf("\n total number of data packets Sent by Node 4: %d\n", source2++);
printf("\n total number of data packets Received by Node 2: %d\n", source3++);
printf("\n total number of data packets Received by Node 5: %d\n", source4++);
}
Terminal:
NAM File:
Experiment No. -6
Theory:
udp0
cbr0
N0 N1
N2 N3
null1
N4
The above network consists of 5 nodes in which node N0 and N4 acts as source and destination and
other nodes behaves as intermediate nodes. There are five paths for sending cbr packets from N0 to
N4 such as,
• N0-NI-N3-N4
• N0-N2-N3-N4
• N0-N3-N4
• N0-N1-N2-N3-N4
• N0-N2-N1-N3-N4
Among these entire paths, link state algorithm will find out the shortest path based on cost assigned
to each link.
Code:
#===================================
# Simulation parameters setup
#===================================
set val(stop) 10.0 ;# time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
# 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
$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
$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
END{
printf("\n total number of data packets received at Node 4: %d\n", a++);
}
Simulation Results:
NAM File:
PART-B
Implement Experiments
using C/C++
Experiment No. -1
C Program for a HDLC frame to perform i) Bit stuffing ii) Character stuffing
Aim: To write a C program to implement bit stuffing for a given binary data. That is, stuff an extra
‘0’ bit after continuous five 1’s in the data
1. BIT STUFFING
Theory:
Bit Stuffing
Bit stuffing is the process of adding one extra 0 whenever five consecutive 1s follow a 0 in the data.
In a bit-oriented protocol, the data to send is a series of bits. In order to distinguish frames, most
protocols use a bit pattern of 8-bit length (01111110) as flag at the beginning and end of each frame.
Here also cause the problem of appearance of flag in the data part to deal with this an extra bit added.
This method is called bitstuffing. In bit stuffing, if a 0 and five successive 1 bits are encountered, an
extra 0 is added. The receiver node removes the extra-added zero.
Algorithm:
1. Read the character stream from the user.
2. Measure the length of the entered sequence.
3. Read the source delimiter characters from the
4. Check for character sequence with source and destination delimiters of the given pattern.
5. If characters are in the sequence equal to delimiter characters, attach the same characters
immediately after those characters.
6. Go to step-5 to repeat the process for the remaining.
7. Display the result.
Code:
Program: bitstuf.c
// Program for Bit stuffing
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char a[100],b[100];
int i,j,k,count,n,flag;
strcpy(a,""); strcpy(b,"");
for(;;){
flag=0;
printf("Enter input frame (0's & 1's only):");
scanf("%s",a);
n = strlen(a);
for(i=0; i<n; i++){
if ((a[i]=='0') || (a[i]=='1' )){
continue;
}
else{
flag=1; break;
}
}
if(flag){
printf ("Invalid Input frame\n:");
exit (0);
}
else{
printf ("Valid Input frame\n:");
printf ("Frame length = %d\n", n); break;
}
}
i=0; j=0; flag=0;
while(i<n)
{
if (a[i]=='1')
{
b[j] = a[i]; count=1;
for(k=i+1; a[k]=='1' && k<n && count<5; k++)
{
j++;
b[j]=a[k];
count++;
if(count==5)
{
j++;
b[j]='0'; count=0;
}
i=k;
}
if(k<n){
if(a[k]=='0'){
j++;
b[j] = a[k];
}
i=k;
}
else{ flag=1; break; }
}
else{
b[j] = a[i];
i++;
j++;
}
}
j++; b[i] = '\0';
Output:
Compile and run
[root@localhost ]# ./a.exe
2. Character Stuffing
Aim: Implement the data link layer framing methods such as character, character stuffing.
Theory:
The character-oriented protocols are popular only with text data. Use reserved characters to indicate
the start and end of a frame. For instance, use the two-character sequence DLE STX (Data-Link
Escape Start of TeXt) to signal the beginning of a frame, and the sequence DLEETX (End of TeXt)
to flag the frame’s end.
The framing method gets around the problem of resynchronization after an error by having each
frame starts with the ASCII character sequence DLESTX (Data Link Escape start of Text) and the
sequence DLEETX (Data Link Escape End of Text). If the destination loses the track of frame
boundaries all it has to do is look for DLESTX and DLEETX characters to figure out. The data link
layer on the receiving end removes DLE before the data are given to the network layer. This technique
is called byte stuffing or character stuffing.
Algorithm
1. Read the character stream from the user.
2. Measure the length of the entered sequence.
3. Read the source delimiter characters from the
4. Check for character sequence with source and destination delimiters of the given pattern.
5. If characters are in the sequence equal to delimiter characters, attach the same characters
immediately after those characters.
6. Go to step-5 to repeat the process for the remaining.
7. Display the result.
Code:
program: bytestuf.c
// Program for Character stuffing
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char c[80],d[80],ed[10],sd[10];
inti,j,m;
strcpy(c,"");
strcpy(sd,"dlestx");
strcpy(ed,"dleetx");
m = strlen(c);
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++;
i = i+3;
}
d[j] = c[i];
}
j++; d[j]='\0';
strcat (d,ed);
printf("\n\nAfter stuffing, transmitted data: %s",d);
return 0;
}
Output:
Compile and run
[root@localhost ]# gcc bytestuf.c
[root@localhost ]# ./a.exe
Enter the characters to be stuffed: javed
After stuffing, transmitted data: dlestxjaveddleetx
Experiment No. -2
Theory:
The name distance vector is derived from the fact that routes are advertised as vectors of (distance,
direction), where distance is defined in terms of a metric and direction is defined in terms of the next-
hop router.
Distance vector algorithm operates by having each router maintain a table (i.e., vectors) giving best
known distance to each destination and which line to get there. These tables are updated by
exchanging the information with the neighbours.
In distance vector routing, each router maintains a routing table indexed by, and containing one entry
for, each router in the subnet. This entry contains two parts: the preferred outgoing line to use for that
destination and a distance to that destination. The router is assumed to know the “distance” to each
of its neighbour.
Here each router depends on its neighbors for information, which the neighbors in turn may have
learned from their neighbors, and so on, distance vector routing is sometimes facetiously referred to
as "routing by rumor." The common Characteristics are
Periodic Updates
Periodic updates means that at the end of a certain time period, updates will be transmitted.
Neighbors
The starting assumption for distance-vector routing is that each node knows the cost of the link to
each of its directly connected neighborsIn the context of routers, neighbors always mean routers
sharing a common data link. Distance vector routing information may be, Network ID, Cost and
NextHop. These three essentials need to form a Distance vector’s routing table.
Design
Algorithm
1. Start the program.
2. Read the number of nodes in the given network.
3. Read the distance matrix from the user. It represents cost distance of each node which
connected directly.
4. By convention, the distance of the node to itself is assigned to zero and when a node is
unreachable the distance is accepted as 999.
5. Store above values in a suitable variable and display the complete routing table.
6. Enter the source node and destination node to find the shortest.
7. Calculate the minimum distance by iteration. If the distance cost between the two nodes is
smaller than the available cost, replace the existence distance with calculated distance.
8. Display the shortest path calculated and its cost between source node and destination node.
9. Go to step-7, to find other short route between other nodes or else goto next step.
10. End the program.
Code:
dist_vector.c
// Program for Distance Vector Routing algorithm
#include <stdio.h>
#include <stdlib.h>
#define nul 1000
#define nodes 10
int no=5;
struct node
{
int a[nodes][3];
}
router[nodes];
void init(int r)
{
int i;
void display(int r)
{
int i;
printf("\n\n The routing table for node %d is as follows", r);
printf("\n\t\tDest\t\tNext Hop\t\tDist");
for(i=1; i<=no; i++)
{
printf("\n\t\t%d\t%d \t\t%d", router[r].a[i][1],router[r].a[i]
[3],router[r].a[i][2]);
}
}
voiddv_algo(int r)
{
inti,j,z;
for(i=1; i<=no; i++)
{
if(router[r].a[i][2]!=999 && router[r].a[i][2]!=0)
{
for(j=1; j<=no; j++)
{
z=router[r].a[i][2]+router[i].a[j][2];
if(router[r].a[j][2]>z)
{
router[r].a[j][2]=z;
router[r].a[j][3]=i;
}
}
}
}
}
void find(int x, int y)
{
if(router[x].a[y][3]!=y)
{
find(x, router[x].a[y][3]);
printf("%d-->",router[x].a[y][3]);
find(router[x].a[y][3],y);
return;
}
}
int main()
{
int i,j,x,y,no;
int choice;
no = 5;
for(i=1; i<=no; i++)
{
init(i);
inp(i);
}
printf("\n The configuration of the nodes after initialization is as follows:");
for(i=1; i<=no; i++)
display(i);
while(1)
{
printf("\n\n Enter 1 to continue, 0 to quit:");
scanf("%d",&choice);
if(choice!=1)
break;
printf("\n Enter the nodes between which shortest path is to be found:");
scanf("%d%d",&x,&y);
printf("\n The shortest path is:");
printf("%d--->",x);
find(x,y);
printf("%d",y);
printf("\n The length of the shortest path is %d",router[x].a[y][2]);
}
return 0;
}
Output:
Compile and run
Experiment No. -3
Dijkstra’s Algorithm
Aim: To implement Dijkstra’s algorithm to compute the shortest path through a given graph using
C program.
Theory:
Dijkstra’s algorithm is a graph search algorithm that solves the single-source shortest path problem
for a graph with non-negative edge path costs, producing a shortest path tree. The Dijkstra algorithm
follows four steps to discover what is called the shortest path tree(routing table) for each router: The
algorithm begins to build the tree by identifying its roots. The root router’s trees the router itself. The
algorithm then attaches all nodes that can be reached from the root. The algorithm compares the tree’s
temporary arcs and identifies the arc with the lowest cumulative cost. This arc and the node to which
it connects are now a permanent part of the shortest path tree. The algorithm examines the database
and identifies every node that can be reached from its chosen node. These nodes and their arcs are
added temporarily to the tree. The last two steps are repeated until every node in the network has
become a permanent part of the tree.
Design:
Algorithm:
1. Assign to every node a tentative distance value: set it to zero for our initial node and infinity for
all other nodes.
2. Set the initial node as current. Mark all other nodes unvisited. Create a set of all the unvisited nodes
called the unvisited set.
3. For the current node, consider all of its neighbors and calculate their tentative distances. Compare
the newly calculated tentative distance to the current assigned value and assign the smaller one. For
example, if the current node A is marked with a distance of 6, and the edge connecting it with a
neighbour B has length 2, then the distance to B (through A) will be 6 +2 = 8. If B was previously
marked with a distance greater than 8 then change it to 8. Otherwise, keep the current value.
4. When we are done considering all of the neighbours of the current node, mark the current node as
visited and remove it from the unvisited set. A visited node will never be checked again.
5. If the destination node has been marked visited (when planning a route between two specific nodes)
or if the smallest tentative distance among the nodes in the unvisited set is infinity (when planning a
complete traversal; occurs when there is no connection between the initial node and remaining
unvisited nodes), then stop. The algorithm has finished.
6. Otherwise, select the unvisited node that is marked with the smallest tentative distance, set it as
the new “current node”, and go back to step 3.
Code:
program: dijkstra.c
scanf("%d", &G[i][j]);
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;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
printf("\nPath=%d", i);
j=i;
do{
j=pred[j];
printf("%d", j);
}while(j!=startnode);
}
}
Output:
Compile and run
[root@localhost ]# gcc dijkstra.c
[root@localhost ]# ./a.exe
Enter no. of vertices:5
0 1 03 10
1 0 50 0
05021
302 0 6
10 0 1 6 0
Enter the starting node:0
Distance of node1=1
Path=10
Distance of node2=5
Path=230
Distance of node3=3
Path=30
Distance of node4=6
Path=4230
Result: Hence Dijkstra‘s algorithm is implemented to compute the Shortest path through a graph.
Experiment No.- 4
Aim: To write a C Program for ERROR detecting code using CRC-CCITT (16bit).
Algorithm:
Code:
program: crc.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
if (mode) {
for ( i = 0; i < strlen(poly); i++)
strcat(op, "0");
}
/* Perform XOR on the msg with the selected polynomial */
for (j = 0; j < strlen(ip); j++) {
if (op[j] == '1') {
for (k = 0; k < strlen(poly); k++) {
if ((op[j + k] == '0') && (poly[k]=='0') || (op[j+k] == '1') && (poly[k] =='1'))
op[j + k] = '0';
else
op[j +k] = '1';
}
}
}
int main()
{
inti,n,flag;
charip[50], op[50], recv[50];
char poly[] = "10001000000100001";
}
}
if(flag){
printf ("Invalid input message\n:");
exit (0);
}
crc(ip, op, poly, 1);
printf("The transmitted message is: %s%s\n",ip,op/*+strlen(ip)*/);
printf("Enter the received message in binary\n");
scanf("%s", &recv);
if(!crc(recv, op, poly, 0))
printf("No error in data\n");
else
printf("Error in data transmission has occurred\n");
return 0;
}
Output:
Experiment No. -5
Theory:
Stop and wait is the fundamental technique to provide reliable transfer under unreliable packet
delivery system. After transmitting one packet, the sender waits for an acknowledgment (ACK) from
the receiver before transmitting the next one. In this way, the sender can recognize that the previous
packet is transmitted successfully and we could say "stop-n-wait" guarantees reliable transfer
between nodes. To support this feature, the sender keeps a record of each packet it sends. Also, to
avoid confusion caused by delayed or duplicated ACKs, "stop-n-wait" send each packet with unique
sequence numbers and receive that numbers in each ACK. If the sender doesn't receive ACK for
previous sent packet after a certain period of time, the sender times out and retransmit that packet
again. There are two cases when the sender doesn't receive ACK; one is when the ACK is lost and
the other is when the frame itself is not transmitted. To support this feature, the sender keeps timer
per each packet.
In this method single frame travels from source to destination and single acknowledgment travels
from destination to source. As a result each frame sent and received uses the entire time needed to
traverse the link. Moreover, if two devices are distance apart, a lot of time is wasted waiting for ACKs
that leads to increase in total transmission time.
Algorithm:
Step 2: Generate random that gives the total number of frames to be transmitted.
Step 7: If an acknowledgement is not received for a particular frame retransmit that frame alone
again.
Step 8: Repeat the steps 5 to 7 till the number of remaining frames to be sent becomes zero.
Code:
stopnwait.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,j,noframes;
int x,x1,x2;
x1=10; i=1; j=1;
printf("\n Enter number of frames\t:");
scanf("%d",&noframes);
while(noframes>0)
{
printf("\n Sending frame %d", i);
x = rand()%15;
if(x%5 == 0){
for(x2=1; x2<2; x2++)
{
printf("\n Waiting for %d seconds\n",x2);
sleep(x2);
}
printf(" Sending frame %d\n",i);
x = rand()%10;
}
printf("\n Acknowledgement received for frame %d\n",j);
noframes = noframes-1;
i++;
j++;
}
printf("\n End of stop and wait protocol");
return 0;
}
Output:
Compile and run
[root@localhost ]# gcc stopnwait.c
[root@localhost ]# ./a.exe
No of frames is 6
Sending frame 1
Acknowledgement for frame 1
Sending frame 2
Acknowledgement for frame 2
Sending frame 3
Acknowledgement for frame 3
Sending frame 4
[root@localhost ]#
Theory:
In computer networks sliding window protocol is a method to transmit data on a network. Sliding
window protocol is 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.
Both sender and receiver agree on some window size. If window size=w then after sending w frames
sender waits for the acknowledgement (ack) of the first frame.
As soon as sender receives the acknowledgement of a frame it is replaced by the next frames to be
transmitted by the sender. If receiver sends a collective or cumulative acknowledgement to sender
then it understands that more than one frames are properly received, for eg:- if ack of frame 3 is
received it understands that frame 1 and frame 2 are received properly.
In sliding window protocol the receiver has to have some memory to compensate any loss in
transmission or if the frames are received unordered.
tx = Transmission time
tp = Propagation delay
Sliding window works in full duplex mode it is of two types:-
1. Selective Repeat: Sender transmits only that frame which is erroneous or is lost.
2. Go back n: Sender transmits all frames present in the window that occurs after the error bit
including error bit also.
Algorithm:
1. Start the program
2. Read the window size
3. Read number of frames to transmit
4. Read randomly selected frames to transmit
5. Transfer the packet until it reaches the maximum defined size.
6. Reduce the window size and repeat the above two steps until packets in.
7. Stop the program
Code:
program: slidingwindow.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int w,i,f,frames[50];
scanf("%d",&w);
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:
Compile and run
[root@localhost ]# gcc slidingwindow.c
[root@localhost ]# ./a.exe
Output:
-------------------------------------------------------------------------------------------------------
Case-1: For Window Size < No. of Frames
Enter window size: 5
Enter number of frames to transmit: 10
Enter 10 frames: 1 2 3 4 5 6 7 8 9 10
With sliding window protocol the frames will be sent in the following manner (assuming no
corruption of frames)
After sending 5 frames at each stage sender waits for acknowledgement sent by the receiver
12345
Acknowledgement of above frames sent is received by sender
6 7 8 9 10
Acknowledgement of above frames sent is received by sender
Result: Stop and wait and Sliding Window Protocol is implemented using C.
Experiment No: -6
Congestion Control Using Leaky Bucket Algorithm
Aim: To write a C Program for Congestion control using Leaky Bucket Algorithm
Theory:
The main concept of the leaky bucket algorithm is that the output data flow remains constant despite
the variant input traffic, such as the water flow in a bucket with a small hole at the bottom. In case
the bucket contains water (or packets) then the output flow follows a constant rate, while if the bucket
is full any additional load will be lost because of spillover. The output will be zero.
Each host is connected to the network by an interface containing a leaky bucket that is a finite internal
queue where all the incoming packets are stored in case there is space in the queue, otherwise the
packets are discarded. This arrangement can be built into the hardware interface or simulated by the
host operating system. The host is allowed to put one packet per clock into the network. This
mechanism turns an uneven flow of packet from the user process inside the host into an even flow of
packets onto the network, smoothing out bursts and greatly reducing the chances of congestion.
In the following figure we can notice the main rationale of leaky bucket algorithm, for both the two
approaches (e.g. leaky bucket with water (a) and with packets (b)).
While leaky bucket eliminates completely bursty traffic by regulating the incoming data flow its main
drawback is that it drops packets if the bucket is full. Also, it doesn’t take into account the idle process
of the sender which means that if the host doesn’t transmit data for some time the bucket becomes
empty without permitting the transmission of any packet.
Algorithm:
Code:
program: leakybucket.c
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
int min(int x, int y)
{
if(x<y)
return x;
else
return y;
}
int main()
{
int drop=0, count=0, inp[25];
int mini, nsec, cap, i, process;
printf("\nSecond|PacketRecieved|PacketSent|PacketLeft|Packet Dropped|\n");
printf("--------------------------------------------------------------\n");
for(i=0;i<nsec;i++)
{
count+=inp[i];
if(count>cap)
{
drop=count-cap;
count=cap;
}
printf("%d",i+1);
printf("\t%d",inp[i]);
mini=min(count,process);
printf("\t\t%d",mini);
count=count-mini;
printf("\t\t%d",count);
printf("\t\t%d\n",drop);
drop=0;
}
for(;count!=0;i++)
{
if(count>cap)
{
drop=count-cap;
count=cap;
}
printf("%d",i+1);
printf("\t0");
mini=min(count, process);
printf("\t\t%d", mini);
count=count-mini;
printf("\t\t%d", count);
printf("\t\t%d\n", drop);
}
}
Output:
Compile and run
[root@localhost ]#
NS2 consists of two key languages: C++ and OTcl (Object-Oriented Tool Command Language).
C++ language defines theinternal/ backend mechanism of the simulation by assembling and
configuring the objects as well as scheduling the discrete/frontend events. Both C++ and OTcl are
linked with each other using TclCL. The combination of both languages interpretthe scripts line by
line the code written in gedit in Linux, ms-word or in the notepad in Windows etc. and saves the
interpreted file with .tcl extension. NS2provides a large number of built-in C++ classes which can be
used to set-up a simulation via a Tcl simulation script. One candevelop their own C++ classes and
can use a OTcl configuration interface to put together the objects originated from these class.
After simulation, NS2 provides output as a Text-Based simulation results which can be interpreted
graphically and interactivelyusing tools such as NAM (Network AniMator) and Xgraph. To analyze
a particular behavior of the network, user can transportthat Text-Based data into a more conceivable
presentation.
Introduction to NS-2:
• Widely known as NS2, is simply an event driven simulation tool.
• Useful in studying the dynamic nature of communication networks.
• Simulation of wired as well as wireless network functions and protocols (e.g., routing
algorithms, TCP, UDP) can be done using NS2.
• In general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviors.
Tcl scripting
• Tcl is a general purpose scripting language. [Interpreter]
• Tcl runs on most of the platforms such as UNIX, Windows, and Mac.
• The strength of Tcl is its simplicity.
• It is not necessary to declare a data type for variable prior to the usage.
Basics of TCL
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello, World!}
Hello, World!
Variables Command Substitution
set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]
Simple Arithmetic
expr 7.2 / 4
Procedures
procDiag {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.)
Which is thus 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 becauseit is an
instance of the Simulator class, so an object the code[new Simulator] is indeed an instance 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
The above creates a data 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”.
Proc finish {} {
global ns tracefile1 namfile
$ns flush-trace
Close $tracefile1
Close $namfile
Exec nam out.nam&
Exit 0
}
The word proc declares a procedure in this case called finish and without arguments. The word
global is used to tell that we are using variables declared outside the procedure. The simulator method
“flush-trace” will dump the traces on the respective files. The tcl command “close” closes the trace
files defined before and exec executes the nam program for visualization. The command exit will
ends the application and return the number 0 as status to the system. Zero is the default for a clean
exit. Other values can be used to say that is a exit because something fails.
At the end of ns program we should call the procedure “finish” and specify at what time the
termination should occur. For example,
$ns at 125.0 “finish”
will be used to call “finish” at time 125sec.Indeed,the at method of the simulator allows us to
schedule events explicitly.
The simulation can then begin using the command
$ns run
The node is created which is printed by the variable n0. When we shall refer to that node in the script
we shall thus write $n0.
Once we define several nodes, we can define the links that connect them. An example of a definition
of a link is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of propagation
delay and a capacity of 10Mb per sec for each direction.
There are number variants of the TCP protocol, such as Tahoe, Reno, New Reno, Vegas. The type of
agent appears in the first line:
settcp[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.
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.
TCP has many parameters with initial fixed defaults values that can be changed if mentioned
explicitly. For example, the default TCP packet size has a size of 1000bytes.This can be changed to
another value, say 552bytes, using the command $tcp set packetSize_ 552.
When we have several flows, we may wish to distinguish them so that we can identify them with
different colors in the visualization part. This is done by the command $tcp set fid_ 1 that assigns to
the TCP connection a flow identification of “1”.We shall later give the flow identification of “2” to
the UDP connection.
Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event should occur. The
initializing command set ns [new Simulator] creates an event scheduler, and events are then
scheduled using the format:
$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
1. The first field is the event type. 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 (e.g. CBR or TCP)
6. Gives the packet size
7. Some flags
8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script one can
further use this field for analysis purposes; it is also used when specifying stream color for the
NAM display.
9. This is the source address given in the form of “node.port”.
10. This is the destination address, given in the same form.
11. This is the network layer protocol’s packet sequence number. Even though UDP implementations
in a real network do not use sequence number, ns keeps track of UDP packet sequence number
for analysis purposes
12. The last field shows the unique id of the packet.
XGRAPH
The Xgraph program draws a graph on an x-display given data read from either data file or from
standard input if no files are specified. It can display upto 64 independent data sets using different
colors and line styles for each set. It annotates the graph with a title, axis labels, grid lines or tick
marks, grid labels and a legend.
Syntax:
Xgraph [options] file-name
NAM
Nam is a Tcl/TK based animation tool for viewing network simulation traces and real world packet
traces. It supports topology layout, packet level animation, and various data inspection tools.
The Network Animator (NAM) Tool
• The Network Animator (nam) is a completely separate program that is distributed with the
NS simulator
• This program is named nam and it shows the progression of the packets through the network.
• The nam program reads an input file (containing the packet transmission events) and draw
the network events graphically.
Running NAM
nam is a UNIX program and it is run as a command line.Example:
UNIX>> nam nam.input
nam.input is the file that contains network events
The key to making the animation input file is to tell NS to output network events into a file for nam
to use.
Make NS output network event information for NAM
Do the following:
1. Create an output file
2. Activate the NAM trace feature in NS before running the simulation (this will tell NS to write
NAM events outputs to the output file)
3. Close output file at the end of the simulation run
Then you can run nam with the output file (as input file for nam). Example:
Run the program using ns Reno1-nam.tcl; it will produce "out.nam" as output
When it finishes, run: nam out.nam to see the packets flow.
Making a better animation: If
1. The output does not look very good...
2. The nodes and links are placed very awkwardly
3. All packets (from all flows) are colored black.
Awk- An Advanced
awk is a programmable, pattern-matching, and processing tool available in UNIX. Itworks 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 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 there 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
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