CNS Lab Programs
CNS Lab Programs
PART-A
1.1 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.
1.2Tcl 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.
Simple Arithmetic
o expr 7.2 / 4
Procedures
proc Diag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
o 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
o while{$i < $n} { for {set i 0} {$i < $n} {incr i} {
... ...
}
1.2.2 Wired TCL Script Components
Steps to write the TCL script for wired network:
1. Create the event scheduler
2. Open new files & turn on the tracing
3. Create the nodes
4. Setup the links
5. Configure the traffic type (e.g., TCP, UDP, etc)
6. Set the time of traffic generation (e.g., CBR, FTP)
7. Terminate the simulation
1.3 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:
Open new files & turn on the tracing
#Open the Trace file
set tracefile1 [open out.tr w]
Proc finish { } {
$ns flush-trace
Close $tracefile1
Close $namfile
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,
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
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of
propagation delay and a capacity of 10Mb per sec for each direction.
To define a directional link instead of a bi-directional one, we should replace “duplex-link” by
“simplex-link”.
In NS, an output queue of a node is implemented as a part of each link whose input is that
node. The definition of the link then includes the way to handle overflow at that queue.In our case, if
the buffer capacity of the output queue is exceeded then the last packet to arrive is dropped. Many
alternative options exist, such as the RED (Random Early Discard) mechanism, the FQ (Fair
Queuing), the DRR (Deficit Round Robin), the stochastic Fair Queuing (SFQ) and the CBQ (which
including a priority and a round-robin scheduler).
In ns, an output queue of a node is implemented as a part of each link whose input is that
node. We should also define the buffer capacity of the queue related to each link. An example would
be:
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command
set sink [new Agent /TCPSink]
Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.
#Setup a UDP connection
set udp [new Agent/UDP]
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
Even Time From To PKT PKT Flags Fi Src Dest Seq Pkt
t Node Node Type Size d Addr Add Num id
r
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.
1.6 XGRAPH
The xgraph program draws a graph on an x-display given data read from either data file or
from standard input if no files are specified. It can display upto 64 independent data sets using
different colors and line styles for each set. It annotates the graph with a title, axis labels, grid lines or
tick marks, grid labels and a legend.
Syntax:
Xgraph [options] file-name
Options are listed here
/-bd <color> (Border)
This specifies the border color of the xgraph window.
/-bg <color> (Background)
This specifies the background color of the xgraph window.
/-fg<color> (Foreground)
This specifies the foreground color of the xgraph window.
/-lf <fontname> (LabelFont)
All axis labels and grid labels are drawn using this font.
/-t<string> (Title Text)
Here, selection_criteria filters input and select lines for the action component to act upon. The
selection_criteria is enclosed within single quotes and the action within the curly braces. Both the
selection_criteria and action forms an awk program.
Example: $ awk ‘/manager/ {print}’ emp.lst
Variables
Awk allows the user to use variables of their choice. You can now print a serial number, using
the variable kount, and apply it those directors drawing a salary exceeding 6700:
$ awk –F”|” ‘$3 == “director” && $6 > 6700 {
count =count+1
printf “ %3f %20s %-12s %d\n”, count,$2,$3,$6 }’ empn.lst
THE –f OPTION: STORING awk PROGRAMS INA FILE
You should holds large awk programs in separate file and provide them with the awk
extension for easier identification. Let’s first store the previous program in the file empawk.awk:
$ cat empawk.awk
Observe that this time we haven’t used quotes to enclose the awk program. You can now use
awk with the –f filename option to obtain the same output:
processing the first line, for example, a heading, then the BEGIN section can be used gainfully.
Similarly, the end section useful in printing some totals after processing is over.
The BEGIN and END sections are optional and take the form
BEGIN {action}
END {action}
These two sections, when present, are delimited by the body of the awk program. You can use
them to print a suitable heading at the beginning and the average salary at the end.
BUILT-IN VARIABLES
Awk has several built-in variables. They are all assigned automatically, though it is also
possible for a user to reassign some of them. You have already used NR, which signifies the record
number of the current line. We’ll now have a brief look at some of the other variable.
The FS Variable: as stated elsewhere, awk uses a contiguous string of spaces as the default field
delimiter. FS redefines this field separator, which in the sample database happens to be the |. When
used at all, it must occur in the BEGIN section so that the body of the program knows its value before
it starts processing:
BEGIN {FS=”|”}
This is an alternative to the –F option which does the same thing.
The OFS Variable: when you used the print statement with comma-separated arguments, each
argument was separated from the other by a space. This is awk’s default output field separator, and
can reassigned using the variable OFS in the BEGIN section:
BEGIN { OFS=”~” }
When you reassign this variable with a ~ (tilde), awk will use this character for delimiting the print
arguments. This is a useful variable for creating lines with delimited fields.
The NF variable: NF comes in quite handy for cleaning up a database of lines that don’t contain the
right number of fields. By using it on a file, say emp.lst, you can locate those lines not having 6 fields,
and which have crept in due to faulty data entry:
$awk ‘BEGIN {FS = “|”}
NF! =6 {
Print “Record No “, NR, “has”, “fields”}’ empx.lst
The FILENAME Variable: FILENAME stores the name of the current file being processed. Like
grep and sed, awk can also handle multiple filenames in the command line. By default, awk doesn’t
print the filename, but you can instruct it to do so:
‘$6<4000 {print FILENAME, $0 }’
With FILENAME, you can device logic that does different things depending on the file that is
processed.
1.8 NS2 Installation
The next two lines are already present the file “export PATH” and “unset USERNAME”
Save the program ( ESC + shift : wq and press enter )
Now in the terminal where we have opened .bash_profile file, type the following command
to check if path is updated correctly or not
[root@localhost ~] # vi .bash_profile
[root@localhost ~] # source .bash_profile
If path is updated properly, then we will get the prompt as shown below
[root@localhost ~] #
Now open the previous terminal where you have installed ns
[root@localhost ns-allinone-2.33] #
Here we need to configure three packages “ns-2.33”, “nam-1.13” and “xgraph-12.1”
First, configure “ns-2.33” package as shown below
[root@localhost ns-allinone-2.33] # cd ns-2.33
[root@localhost ns-2.33] # ./configure
[root@localhost ns-2.33] # make clean
[root@localhost ns-2.33] # make
[root@localhost ns-2.33] # make install
[root@localhost ns-2.33] # ns
%
If we get “%” symbol it indicates that ns-2.33 configuration was successful.
Second, configure “nam-1.13” package as shown below
[root@localhost ns-2.33] # cd . .
[root@localhost ns-allinone-2.33] # cd nam-1.13
[root@localhost nam-1.13] # ./configure
[root@localhost nam-1.13] # make clean
[root@localhost nam-1.13] # make
[root@localhost nam-1.13] # make install
[root@localhost nam-1.13] # ns
%
If we get “%” symbol it indicates that nam-1.13 configuration was successful.
Third, configure “xgraph-12.1” package as shown below
[root@localhost nam-1.13] # cd . .
[root@localhost ns-allinone-2.33] # cd xgraph-12.1
[root@localhost xgraph-12.1] # ./configure
[root@localhost xgraph-12.1] # make clean
[root@localhost xgraph-12.1] # make
[root@localhost xgraph-12.1] # make install
[root@localhost xgraph-12.1] # ns
1.Implement three nodes point – to – point network with duplex links between them.
Program
set ns [new Simulator]
set nf [open lab1.nam w]
$ns namtrace-all $nf
set tf [open lab1.tr w]
$ns trace-all $tf
proc finish {} {
global ns nftf
$ns flush-trace
close $nf
close $tf
exec nam lab1.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
#hello
$ns duplex-link $n0 $n2 10Mb 1ms DropTail
$ns duplex-link $n1 $n2 10Mb 1ms DropTail
$ns duplex-link $n2 $n3 10Mb 1ms DropTail
$ns duplex-link $n3 $n4 10Mb 1ms DropTail
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set udp0 [new Agent/UDP]
AWK FILE :-
BEGIN{
udp = 0;
tcp = 0;
}
{
if($1 == "r" && $5 == "cbr")
{
udp++;
}
else if($1 == "r" && $5 == "tcp")
{
tcp++;
}
}
END{
printf("the no of packets send by udp = %d\n",udp);
printf("the no of packets send by tcp = %d\n",tcp);
}
output:
tcp = 692 udp = 107
#create nodes
set n0 [$ns node]
set n1 [$ns node]
set lan0 [$ns newLan "$n0 $n1 $n2 $n3 $n4" 0.5Mb 40ms LL Queue/DropTail
MAC/Csma/Cd Channel]
2-Star
set ns [new Simulator]
#open new file for namtrace
set nf [open out.nam w]
#create 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]
Output:
3-Ring:
set ns [new Simulator]
#open new file for namtrace
set nf [open out.nam w]
$ns namtrace-all $nf
#create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
Awk file:-
BEGIN{
drop = 0;
}
{
if($1 == "d")
{
drop++;
}
printf("%d\t%d\n",$5,drop);
}
END{
printf("total no.of %s packet dropped due to congestion =%d\n",$5,drop);
}
output:-
total no.of ping packet dropped due to congestion = 58
4- Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.
Program:
set ns [new
Simulator]
set nf [open
eth.nam w]
$ns namtrace-all
$nf
set tf [open eth.tr
w]
$ns trace-all $tf
set n0 [$ns node]
$n0 color "red"
$ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/DropTail Mac/802_3
$ns duplex-link $n4 $n5 1Mb 1ms DropTail
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ftp0 set packetSize_ 500
$ftp0 set interval_ 0.0001
set sink5 [new Agent/TCPSink]
$ns attach-agent $n5 $sink5
$ns queue-limit $n4 $n5 2
$ns connect $tcp0 $sink5
Set tcp2[newAgent/TCP]
$ns attach-agent $n2 $tcp2
set ftp2 [new Application/FTP]
$ns run
eth.awk
BEGIN{
pkt = 0;
time = 0;
}
{
if($6 == "cwnd_")
{
printf("%d\t%d\n",$1,$7)
}
}
END{
}
Output:
proc finish {} {
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec namout.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]
Output:
proc finish {} {
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec namout.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]
$ns run
Output:
$tcptracevarcwnd_
10-Sliding Window
Program
set ns [new Simulator]
set n0 [$ns node]
set n1 [$ns node]
$ns at 0.0 "$n0 label Sender"
$ns at 0.0 "$n1 label Receiver"
set nf [open stop.nam w]
$ns namtrace-all $nf
set tf [open stop.tr w]
$ns trace-all $tf
$tcptracevarcwnd_
proc finish {} {
global ns nftf
$ns flush-trace
close $nf
close $tf
puts " running nam--"
exec namstop.nam&
exit 0
}
$ns run
Output:
import java.math.*;
import java.util.*;
class RSA1 {
public static void main(String args[])
{
int p, q, n, z, d = 0, e, i;
int x = 1 + (i * z);
class DES{
public static void main(String[] args) throws IOException, NoSuchAlgorithmException,
InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException {
//Generating Key
KeyGeneratorMygenerator = KeyGenerator.getInstance("DES");
SecretKeymyDesKey = Mygenerator.generateKey();
13-Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
// Java program to calculate SHA-1 hash value
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
// Driver code
public static void main(String args[]) throws
NoSuchAlgorithmException
{