CN Lab Manual 2023 24
CN Lab Manual 2023 24
Lab Experiments
1. Implement three nodes point – to – point network with duplex links between them for different
topologies. Set the queue size, vary the bandwidth and find the number of packets dropped for
various iterations.
2. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and
determine the performance with respect to transmission of packets.
3. Write a program for error detecting code using CRC-CCITT (16- bits).
4. Implement transmission of ping messages/trace route over a network topology consisting of 6
nodes and find the number of packets dropped due to congestion.
5. Write a program to find the shortest path between vertices using bellman-ford algorithm.
6. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
window for different source / destination.
7. Write a program for congestion control using leaky bucket algorithm.
Simulation
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!
NS Simulator Preliminaries.
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.
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 because it is
an instance of the Simulator class, so an object the code[new Simulator] is indeed the
installation of the class Simulator using the reserved word new.
In order to have output files with data on the simulation (trace files) or files used for
visualization (nam files), we need to create the files using “open” command:
The above creates a dta 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 begins with a # symbol.The second line open the file “out.tr” to be used for writing,declared
with the letter “w”.The third line uses a simulator method called trace-all that have as parameter
the name of the file where the traces will go.
The last line tells the simulator to record all simulation traces in NAM input format.It
also gives the file name that the trace will be written to later by the command $ns flush-trace.In
our case,this will be the file pointed at by the pointer “$namfile”,i.e the file “out.tr”.
The termination of the program is done using a “finish” procedure.
Proc finish { } {
$ns flush-trace
Close $tracefile1
Close $namfile
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:
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.
In NS, an output queue of a node is implemented as a part of each link whose input is that
node. The definition of the link then includes the way to handle overflow at that queue. In our
case, if the buffer capacity of the output queue is exceeded then the last packet to arrive is
dropped. Many alternative options exist, such as the RED (Random Early Discard) mechanism,
the FQ (Fair Queuing), the DRR (Deficit Round Robin), the stochastic Fair Queuing (SFQ) and
the CBQ (which including a priority and a round-robin scheduler).
In ns, an output queue of a node is implemented as a part of each link whose input is that
node. We should also define the buffer capacity of the queue related to each link. An example
We need to define routing (sources, destinations) the agents (protocols) the application that use
them.
TCP is a dynamic reliable congestion control protocol. It uses
FTP over TCP
Acknowledgements created by the destination to know whether packets are well
received.
There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno, Vegas.
The type of agent appears in the first line:
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.
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:
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 (eg 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
Awk- An Advanced
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
BEGIN {action}
END {action}
These two sections, when present, are delimited by the body of the awk program. You
can use them to print a suitable heading at the beginning and the average salary at the end.
Built-In Variables
Awk has several built-in variables. They are all assigned automatically, though it is also
possible for a user to reassign some of them. You have already used NR, which signifies the
record number of the current line. We‟ll now have a brief look at some of the other variable.
The FS Variable: as stated elsewhere, awk uses a contiguous string of spaces as the default field
delimiter. FS redefines this field separator, which in the sample database happens to be the |.
When used at all, it must occur in the BEGIN section so that the body of the program knows its
value before it starts processing:
BEGIN {FS=”|”}
This is an alternative to the –F option which does the same thing.
The OFS Variable: when you used the print statement with comma-separated arguments, each
argument was separated from the other by a space. This is awk‟s default output field separator,
and can reassigned using the variable OFS in the BEGIN section:
BEGIN { OFS=”~” }
When you reassign this variable with a ~ (tilde), awk will use this character for delimiting the
print arguments. This is a useful variable for creating lines with delimited fields.
The NF variable: NF comes in quite handy for cleaning up a database of lines that don‟t contain
the right number of fields. By using it on a file, say emp.lst, you can locate those lines not having
6 fields, and which have crept in due to faulty data entry:
$awk „BEGIN {FS = “|”}
NF! =6 {
Print “Record No “, NR, “has”, “fields”}‟ empx.lst
Experiment 1
1. Implement three nodes point – to – point network with duplex links between them for
different topologies. Set the queue size, vary the bandwidth and find the number of
packets dropped for various iterations.
Step1: Open text editor, type the below program and save with extention .tcl (prog1.tcl )
proc finish { } {
global ns nf nd
$ns flush-trace
close $nf
close $nd
exec nam prog1.nam &
exit 0
}
Step2: Open text editor, type the below program and save with extention .awk (prog1.awk )
BEGIN {
dcount = 0;
rcount = 0;
}
{
event = $1;
if(event == "d")
{
dcount++;
}
if(event == "r")
{
rcount++;
}
}
END {
printf("The no.of packets dropped : %d\n ",dcount);
printf("The no.of packets recieved : %d\n ",rcount);
}
Step3: Run the simulation program
[root@localhost~]# ns prog1.tcl
(Here “ns” indicates network simulator. We get the topology shown in the snapshot.)
Step 4: Now press the play button in the simulation window and the simulation will begins.
Step 5: After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f prog1.awk prog1.tr
Number of packets droped = 16
Experiment 2:
Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and
determine the throughput with respect to transmission of packets.
Step1: Open text editor, type the below program and save with extention .tcl (prog2.tcl )
-macTrace OFF \
-movementTrace ON
create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
$n0 set X_ 50
$n0 set Y_ 50
$n0 set Z_ 0
$n1 set X_ 100
$n1 set Y_ 100
$n1 set Z_ 0
$n2 set X_ 600
$n2 set Y_ 600
$n2 set Z_ 0
$ns at 0.1 "$n0 setdest 50 50 15"
$ns at 0.1 "$n1 setdest 100 100 25"
$ns at 0.1 "$n2 setdest 600 600 25"
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
set sink1 [new Agent/TCPSink]
$ns attach-agent $n1 $sink1
$ns connect $tcp0 $sink1
set tcp1 [new Agent/TCP]
$ns attach-agent $n1 $tcp1
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
set sink2 [new Agent/TCPSink]
$ns attach-agent $n2 $sink2
$ns connect $tcp1 $sink2
$ns at 5 "$ftp0 start"
$ns at 5 "$ftp1 start"
Step2: Open text editor, type the below program and save with extention .awk (prog4.awk )
BEGIN{
count1=0
count2=0
pack1=0
pack2=0
time1=0
time2=0
}
{if($1=="r"&& $3=="_1_" && $4=="AGT")
{count1++
pack1=pack1+$8
time1=$2 }
if($1=="r" && $3=="_2_" && $4=="AGT")
{count2++
pack2=pack2+$8
time2=$2}
}
END{
printf("The Throughput from n0 to n1: %f Mbps \n", ((count1*pack1*8)/(time1*1000000)));
printf("The Throughput from n1 to n2: %f Mbps", ((count2*pack2*8)/(time2*1000000)));
}
Step 4: Now press the play button in the simulation window and the simulation will begins
Step 5: After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f prog4.awk prog6.tr
Here “M” indicates mobile nodes, “AGT” indicates Agent Trace, “RTR” indicates Router
Write a program for error detecting code using CRC-CCITT (16 bits).
Theory
CRC(Cyclic Redundancy Check) is an error detecting technique used in digital networks and
storage devices to detect the accidental changes to raw data. It cannot be used for correcting
errors.
The CRC does error checking via polynomial division. The generated polynomial g(x) =
x +x +x5+x0
16 12
16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
17 bits.
1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1
Algorithm:
1. Given a bit string (message to be sent), append 16 0S to the end of it (the number of 0s is
the same as the degree of the generator polynomial) let this string + 0S be called as
modified string B
2. Divide B by agreed on polynomial g(x) and determine the remainder R(x). The 16-bit
remainder received is called as checksum.
3. The message string is appended with checksum and sent to the receiver.
4. At the receiver side, the received message is divided by generator polynomial g(x).
5. If the remainder is 0, the receiver concludes that there is no error occurred otherwise, the
receiver concludes an error occurred and requires a retransmission.
PROGRAM:
import java.io.*;
class crc_gen
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
int data_bits, divisor_bits, tot_length;
divisor_bits = 17;
divisor = new int[]{1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1};
tot_length=data_bits+divisor_bits-1;
div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];
/* CRC GENERATION */
for(int i=0;i<data.length;i++)
div[i]=data[i];
rem[j] = div[j];
}
rem=divide(divisor, rem);
System.out.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i]);
/* ERROR DETECTION */
System.out.println();
System.out.println("Enter CRC code of "+tot_length+" bits :
"); for(int i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.readLine());
rem=divide(divisor, rem);
if((rem.length-cur)<divisor.length)
break;
}
return rem;
}
}
OUTPUT:
Experiment 4:
Step1: Open text editor, type the below program and save with extention .tcl (prog2.tcl )
proc finish {} {
global ns nf nd
$ns flush-trace
close $nf
close $nd
exec nam prog2.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
Step2: Open text editor, type the below program and save with extention .awk (prog2.awk )
BEGIN {
count=0;
}
{
event=$1;
if(event=="d")
{
count++;
}
}
END {
printf("No of packets dropped : %d\n",count);
}
Step 4: Now press the play button in the simulation window and the simulation will begins.
Step 5: After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f prog2.awk prog2.tr
Experiment 5
Bellman-Ford algorithm
Problem Statement
Write a program to find the shortest path between vertices using bellman-ford algorithm.
Theory
Routing algorithm is a part of network layer software which is responsible for deciding which
output line an incoming packet should be transmitted on. If the subnet uses datagram internally,
this decision must be made anew for every arriving data packet since the best route may have
changed since last time. If the subnet uses virtual circuits (connection Oriented), routing
decisions are made only when a new established route is being set up.
Routing algorithms can be grouped into two major classes: adaptive and nonadaptive.
Nonadaptive algorithms do not base their routing decisions on measurement or estimates of
current traffic and topology. Instead, the choice of route to use to get from I to J (for all I and J)
is compute in advance, offline, and downloaded to the routers when the network ids booted. This
procedure is sometime called static routing.
Adaptive algorithms, in contrast, change their routing decisions to reflect changes in the
topology, and usually the traffic as well. Adaptive algorithms differ in where they get
information (e.g., locally, from adjacent routers, or from all routers), when they change the
routes (e.g., every ∆T sec, when the load changes, or when the topology changes), and what
metric is used for optimization (e.g., distance, number of hops, or estimated transit time).
Two algorithms in particular, distance vector routing and link state routing are the most
popular. 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.
The distance vector routing algorithm uses Bellman-Ford routing algorithm and Ford-
Fulkerson algorithm. In distance vector routing, each router maintains a routing table that
contains two parts: the preferred out going line to use for that destination, and an estimate of the
time or distance to that destination. The metric used might be number of hops, time delay in
milliseconds, total number of packets queued along the path, or something similar.
The Routing tables are shared among the neighbors, and the tables at the router are updated,
such that the router will know the shortest path to the destination.
Program
import java.io.*;
import java.util.Scanner;
class dist_vec
{
public static void main(String args[]) {
int dmat[][];
int dist[][];
int via[][];
int n=0,i=0,j=0,k=0,count=0;
Scanner in = new Scanner(System.in);
}
}
OUTPUT
Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.
Step1: Open text editor, type the below program and save with extention .tcl (prog3.tcl )
proc finish { } {
global ns nf nd
$ns flush-trace
close $nf
close $nd
exec nam prog3.nam &
exit 0
}
$ns make-lan "$n3 $n4 $n5 $n6 $n7 $n8" 512Kb 40ms LL Queue/DropTail Mac/802_3
Step2: Open text editor, type the below program and save with extention .awk (prog3.awk )
BEGIN {
}
{
if($6=="cwnd_") {
printf("%f\t%f\n",$1,$7);
}
}
END {
}
Step 4: Now press the play button in the simulation window and the simulation will begins.
Step 5: After simulation is completed run awk file and generate the graph ,
[root@localhost~]# awk –f prog3.awk cwnd.tr > a1
[root@localhost~]# awk –f prog3.awk cwnd2.tr > a2
[root@localhost~]#xgraph a1 a2
Experiment7
Leaky Bucket
Problem Statement
Write a program for congestion control using leaky bucket algorithm.
Theory
The congesting control algorithms are basically divided into two groups: open loop and closed
loop. Open loop solutions attempt to solve the problem by good design, in essence, to make sure
it does not occur in the first place. Once the system is up and running, midcourse corrections are
not made. Open loop algorithms are further divided into ones that act at source versus ones that
act at the destination.
In contrast, closed loop solutions are based on the concept of a feedback loop if there is any
congestion. Closed loop algorithms are also divided into two sub categories: explicit feedback
and implicit feedback. In explicit feedback algorithms, packets are sent back from the point of
congestion to warn the source. In implicit algorithm, the source deduces the existence of
congestion by making local observation, such as the time needed for acknowledgment to come
back.
The presence of congestion means that the load is (temporarily) greater than the resources (in
part of the system) can handle. For subnets that use virtual circuits internally, these methods can
be used at the network layer.
Another open loop method to help manage congestion is forcing the packet to be transmitted
at a more predictable rate. This approach to congestion management is widely used in ATM
networks and is called traffic shaping.
The other method is the leaky bucket algorithm. 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. In other words, if one or more process are already queued,
the new packet is unceremoniously discarded. This arrangement can be built into the hardware
interface or simulate d by the host operating system. In fact it is nothing other than a single
server queuing system with constant service time.
The host is allowed to put one packet per clock tick onto the network. This mechanism turns
an uneven flow of packet from the user process inside the host into an even flow of packet onto
the network, smoothing out bursts and greatly reducing the chances of congestion.
Program:
import java.lang.*;
import java.util.Random;
import java.io.*;
import java.util.Scanner;
class leaky_bucket
{
public static void main(String args[])
{
int drop=0,mini,nsec,p_remain=0;
int o_rate,b_size,i,packet[];
p_remain=p_remain-mini;
System.out.print(p_remain+" ");
System.out.print(drop+" ");
System.out.println();
drop=0;
}
}
while(p_remain!=0)
if(p_remain>b_size)
drop=p_remain-b_size;
p_remain=b_size;
mini=Math.min(p_remain,o_rate);
System.out.print("
"+p_remain+"
"+mini);
p_remain=p_remain-mini;
System.out.println(“ “+p_remain+"
"+drop);
drop=0;
Output: