0% found this document useful (0 votes)
403 views38 pages

ns2 Final Lab-1

The document discusses the goals of the NS2 network simulator software including supporting networking research and education through protocol design and traffic studies, and providing a collaborative environment. It also outlines the general workflow for a network simulation in NS2 which includes defining the topology, developing models, configuring objects, running the simulation, and analyzing output data.

Uploaded by

Nidhi Kushwaha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
403 views38 pages

ns2 Final Lab-1

The document discusses the goals of the NS2 network simulator software including supporting networking research and education through protocol design and traffic studies, and providing a collaborative environment. It also outlines the general workflow for a network simulation in NS2 which includes defining the topology, developing models, configuring objects, running the simulation, and analyzing output data.

Uploaded by

Nidhi Kushwaha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

University Institute of Technology

Rajiv Gandhi Proudyogiki Vishwavidyalaya


Department of Computer Science & Engineering

Session 2016-2017

LAB Manual
Program : B.E.
Semester : IV
Course Code : CS-407
Lab Name : Network & Communication Workshop

Prepared By-
Mr. Satyendra Rajput

HOD, CSE Director, UIT


LAB NAME : NETWORK & COMMUNICATION WORKSHOP
COURSE : CS-407
SEM : IV
S.NO. NAME OF EXPERIMENT Page
Number

1
Introduction and History of NS-2 software in network.
2 Study Goal and different area of Simulation workflow in
NS2.
3 Study the Installation of NS-2 and Installation steps of NS-
2 in Ubuntu.
4 Study the Installation of NS-2 and Installation steps of NS-
2 in Ubuntu.
5 Study to run TCL script in ns-2 environment.
6 Write a Tcl script and understand basic syntax for variable,
basic operations and if-else.
7 In Tcl script: To study loop, Array, procedure and file
handling.
8 Write a OTCL program, Run program in terminal and
Analyze trace file using gawk.
9 Write a OTCL program Using constructor, destructor and
inheritance.
10 Create Node and Link between Nodes using node and link
class using NS-2.
11 Practical: simulate three nodes point to point networks
with a duplex link between them. set the queue size and
vary the bandwidth and find the number of packets.
12 PracticPractical: To implement Topology with using TCP
and UDP protocol.al:
Exp.1: Introduction and History of NS2 software in network.
Objective: To understand about network Simulation software and History of
NS2 simulator software.
● Developed by UC Berkeley
● Maintained by USC
● Popular simulator in scientific environment
● Other popular network simulators
➢ Glomosim: UCLA, CMU; ParseC, Mobile Simulation
mostly
➢ OPNET: commercial software, graphical interface, not
free;
➢ Others: commercial ones, not free, e.g. IBM TPNS
NS (from network simulator) is a name for a series of discrete event network simulators,
specifically ns-1, ns-2 and ns-3. All of them are discrete-event computer network simulators,
primarily used in research and teaching. ns-3 is free software, publicly available under the GNU
GPLv2 license for research, development, and use.
The goal of the ns-3 project is to create an open simulation environment for computer
networking research that will be preferred inside the research community
● It should be aligned with the simulation needs of modern networking research.
● It should encourage community contribution, peer review, and validation of the
software.
NS-1
The first version of ns, known as ns-1, was developed at Lawrence Berkeley National
Laboratory (LBNL) in the 1995-97 timeframe by Steve McCanne, Sally Floyd, Kevin Fall, and
other contributors. This was known as the LBNL Network Simulator, and derived from an
earlier simulator known as REAL by S. Keshav.
NS-2
Ns began as a variant of the REAL network simulator in 1989 and has evolved substantially
over the past few years. In 1995 ns development was supported by DARPA through the VINT
project at LBL, Xerox PARC, UCB, and USC/ISI. Currently ns development is support through
DARPA with SAMAN and through NSF with CONSER, both in collaboration with other
researchers including ACIRI. Ns has always included substantial contributionswireless code
from the UCB Daedelus and CMU Monarch projects and Sun Microsystems. For documentation
on recent changes, see the version 2 change log.
NS-3
A team led by Tom Henderson, George Riley, Sally Floyd, and Sumit Roy, applied for and
received funding from the U.S. National Science Foundation (NSF) to build a replacement for
ns-2, called ns-3. This team collaborated with the Planete project of INRIA at Sophia Antipolis,
with Mathieu Lacage as the software lead, and formed a new open source project.
In the process of developing ns-3, it was decided to completely abandon backward-compatibility
with ns-2. The new simulator would be written from scratch, using the C++ programming
language. Development of ns-3 began in July 2006.
The first release, ns-3.1 was made in June 2008, and afterwards the project continued making
quarterly software releases, and more recently has moved to three releases per year. ns-3 made
its twenty first release (ns-3.21) in September 2014.

Current status of the three versions is:


● ns-1 is no longer developed nor maintained,
● ns-2 is not actively maintained (active development stopped in 2010 but volunteers in
user community are still developing it )
● ns-3 is actively developed (but not compatible for work done on ns-2).

1. INTRODUCTION
Network Simulator Version 2, widely known as NS2, is an event driven simulation tool that is 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. Due to its flexibility and modular nature, NS2 has gained constant
popularity in the networking research community since its birth in 1989. Ever since, several
revolutions and revisions have marked the growing maturity of the tool, thanks to substantial
contributions from the players in the field. Among these are the University of California and Cornell
University who developed the REAL network simulator,1 the foundation which NS is based on.
Since 1995 the Defense Advanced Research Projects Agency (DARPA) supported development of
NS through the Virtual InterNetwork Testbed (VINT) project.Currently the National Science
Foundation (NSF) has joined the ride in development. Last but not the least, the group of researchers
and developers in the community are constantly working to keep NS2 strong and versatile.

BASIC ARCHITECTURE OF NS2:


Figure given below shows the basic architecture of NS2. NS2 provides users with an executable
command ns which takes on input argument, the name of a Tcl simulation scripting file. Users are
feeding the name of a Tcl simulation script (which sets up a simulation) as an input argument of an
NS2 executable command ns. In most cases, a simulation trace file is created, and is used to plot
graph and/or to create animation.
NS2 consists of two key languages: C++ and Object-oriented Tool Command Language (OTcl).
While the C++ defines the internal mechanism (i.e.,a back end) of the simulation objects, the OTcl
sets up simulation by assembling and configuring the objects as well as scheduling discrete events
(i.e.,a front end). The C++ and the OTcl are linked together using TclCL. Mapped to a C++ object,
variables in the OTcl domains are sometimes referred to as handles. Conceptually, a handle (e.g., n
as a Node handle) is just a string (e.g.,o10) in the OTcl domain, and does not contain any
functionality. Instead, the functionality(e.g., receiving a packet) is defined in the mapped C++ object
(e.g., of class Connector). In the OTcl domain, a handle acts as a front end which interacts with users
and other OTcl objects. It may defines its own procedures and variables to facilitate the interaction.
Note that the member procedures and variables in the OTcl domain are called instance
procedures(instprocs) and instance variables(instvars), respectively. Before proceeding further, the
readers are encouraged to learn C++ and OTcl languages and we include it on our previous posts.

NS2 provides a large number of built in C++ objects. It is advisable to use these C++ objects to set
up a simulation using a Tcl simulation script. However, advance users may find these objects
insufficient. They need to develop their own C++ objects, and use a OTcl configuration interface to
put together these objects. After simulation, NS2 outputs either text-based or animation-based
simulation results. To interpret these results graphically and interactively, tools such as NAM
(Network AniMator) and XGraph are used. To analyze a particular behavior of the network, users
can extract a relevant subset of text-based data and transform it to a more conceivable presentation.
Exp.2: Study Goal and different area of Simulation workflow in
NS2.
Objective: To understand about the Goal and different area in network
where simulation is used.
➢ NS2 Goals
● To support networking research and education
Protocol design, traffic studies, etc.
Protocol comparison;

New architecture designs are also supported.


● To provide collaborative environment
Freely distributed, open source;
Increase confidence in result

2. Simulation workflow:
The general process of creating a simulation can be divided into several steps:

1. Topology definition: To ease the creation of basic facilities and define their
interrelationships, ns-3 has a system of containers and helpers that facilitates this
process.
2. Model development: Models are added to simulation (for example, UDP, IPv4,
point-to-point devices and links, applications); most of the time this is done using
helpers.
3. Node and link configuration: models set their default values (for example,
the size of packets sent by an application or MTU of a point-to-point link); most of the
time this is done using the attribute system.
4. Execution: Simulation facilities generate events, data requested by the user is
logged.
5. Performance analysis: After the simulation is finished and data is available as a
time-stamped event trace. This data can then be statistically analyzed with tools
like R to draw conclusions.
6. Graphical Visualization: Raw or processed data collected in a simulation can
be graphed using tools like Gnuplot, matplotlib or XGRAPH.
Criticism
ns-2 is often criticized[by whom?] because modelling is a very complex
and time-consuming task, since it has no GUI and one needs to learn
scripting language, queuing theory and modelling techniques. Also, of late,
there have been complaints that results are not consistent (probably because
of continuous changes in the code base) and that certain protocols have
unacceptable bugs.[citation needed]

ns-3 is often criticized[by whom?] for its lack of support for protocols (like
WSN, MANET etc.) which were supported in ns-2, as well as for the lack
of backward compatibility with ns-2. As with ns-2, ns-3 is also time-
consuming to learn and use compared to GUI-based simulators.
Exp. 3: Installation of NS-2 and Installation steps of NS-2 in
Ubuntu.

Objective: To understand how to install NS-2 software on Ubuntu


operating system.
We first require root privileges and then we can run the install script. Use the
following steps:
STEP 1: Download and Extract ns2 using terminal by using given commands:
cd ~/
sudo wget http://softlayer-sng.dl.sourceforge.net/project/nsnam/allinone/ns-allinone-
2.35/ns-allinone-2.35.tar.gz
tar -xvzf ns-allinone-2.35.tar.gz
STEP 2: Ns2 requires some packages including GCC- version 4.4 to work correctly. So
install all of them by using the following command:
sudo apt-get install build-essential autoconf automake libxmu-dev
sudo apt-get install gcc-4.4
STEP 3: After installation of packages, we have to make a change in the “ls.h” file.
Navigate to the folder “linkstate” which is assumed be in the ns folder extracted and is in
the home folder of your system.
cd ~/ns-allinone-2.35/ns-2.35/linkstate
STEP 4: Open the file named “ls.h” by using given command and scroll to the 137th
line. You will find the word “error”; change that to “this->error”. To open the file use the
following command:
gedit ls.h

STEP 5: Now, we need to inform ns which version of GCC will be used. To do so, go to
your ns folder and type the following command. Here, change CC= @CC@ to CC=gcc-
4.4, as shown in the image below, then save
and exit.
Sudo gedit ns-allinone-2.34/otcl-1.13/Makefile.in
STEP 6: Now we are ready to install ns2. Run the install script using the following
commands:
sudo su cd ~/ns-allinone-2.35/./install
STEP 7: The final step is to tell the system, where the files for ns2 are installed or
present. Open the .bashrc file using the given command. Add the given lines but be sure
that the path you are giving is the same where the folder ns is present. For example, if
you have installed it in a folder “/home/abc”, then replace “/home/pcquest/ns-allinone-
2.35/otcl-1.14” with “/home/abc/ns-allinone-2.35/otcl-1.14”.
sudo gedit ~/.bashrc

Lines to be added:
# LD_LIBRARY_PATH
OTCL_LIB=/home/pcquest/ns-allinone-2.35/otcl-1.14
NS2_LIB=/home/pcquest/ns-allinone-2.35/lib
X11_LIB=/usr/X11R6/lib
USR_LOCAL_LIB=/usr/local/lib
export
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$OTCL_LIB:$NS2_LIB:$X11_LIB:$
USR_LOCAL_LIB
# TCL_LIBRARY
TCL_LIB=/home/pcquest/ns-allinone-2.35/tcl8.5.10/library
USR_LIB=/usr/lib
export TCL_LIBRARY=$TCL_LIB:$USR_LIB
# PATH
XGRAPH=/home/pcquest/ns-allinone-2.35/bin:/home/pcquest/ns-allinone-
2.35/tcl8.5.10/unix:/home/pcquest/ns-allinone-2.35/tk8.5.10/unix
#the above two lines beginning from xgraph and ending with unix should come on the
same line
NS=/home/pcquest/ns-allinone-2.35/ns-2.35/
NAM=/home/pcquest/ns-allinone-2.35/nam-1.15/
PATH=$PATH:$XGRAPH:$NS:$NAM
Once the changes have been made, save the file and restart the system.
STEP 8: Once the system has restarted, open a terminal and start ns2 by using the
command ns.
Exp.4 Study the Installation of NS-2 and Installation steps of NS-2
in windows operating system.

Objective: To understand how to install NS-2 software on windows


operating system.

Procedure 1:

How to Install NS-2 on Windows using VMware

Steps:

1. Install Vmware-http://www.filesonic.com/file/36283655/Vmware.Workstation.7.1.3.rar
2. Install fedora or any other Linux flavor on VMware
3. Install NS-2.34 on Linux-http://sourceforge.net/projects/nsnam/files/allinone/ns-allinone-2.34/
4. Type ./install on terminal to compile the source after extracting NS-2
5. Type gedit ~/.bashrc on terminal to set the environment variables.Append the following text to
opened file (Please note that the path contains the path in my system, replace "usman" in the
path with your username)

6. # .bashrc
7. export PATH=$PATH:/home/usman/ns-allinone-2.34/bin:/home/usman/ns-allinone-
2.34/tcl8.4.18/unix:/home/usman/ns-allinone-2.34/tk8.4.18/unix
8. export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/usman/ns-allinone-2.34/otcl-
1.13:/home/usman/ns-allinone-2.34/lib
9. export TCL_LIBRARY=$TCL_LIBRARY:/home/usman/ns-allinone-2.34/tcl8.4.18/library
10. # User specific aliases and functions
11.
12. alias rm='rm -i'
13. alias cp='cp -i'
14. alias mv='mv -i'
15.
16. # Source global definitions
17. if [ -f /etc/bashrc ]; then
18.
19. . /etc/bashrc
Exp.5: Study to run TCL script in ns-2 environment.
Objective: To understand how to run TCL program on NS-2
I. Ubuntu Platform:

● Open gedit
Open gedit in Ubuntu Application --> Accessories --> gedit Text editor

● Save file with .tcl extension


Save your file with .tcl extension. For example save on Desktop.

● Open terminal
Open your terminal in ubuntu ( Application --> Accessories --> terminal )
Change your present directory
Our tcl file is stored on desktop so we have to change directory in terminal.

● Run Following command


Use ns2 simulator for running tcl program.
II. On windows Platform:
● Save with .tcl extension

Write tcl program in text editor and save it with .tcl extension. For simplicity save it on Desktop.

● Open command interpreter

Open command interpreter and change directory by running cd desktop command. After it run following
command

Tchsh86 <file-name>
Exp.6: Write a Tcl script and understand basic syntax for variable,
basic operations and if-else.
Objective: To understand basic syntax for creating variable, basic
operations and if-else.
TCL is an interpreted language. Each instruction is a command in tcl program. TCL programming is
used to write simulation script in ns2.
Following are the topics which you need to learn in order to write simulation script.
Topics: Variables in TCL
Basic Operations
If-else

Variables in TCL
set command is used to make a variable and assign value to them. This command is also used to
fetch value of variable.
Syntax :
set <variable_name> <variable_value>

Above command will create a variable with given name and assign value. If value is not specified
then above command will show value stored in variable. Let's take one example
Example :
?
1set x 10
2set name "john"
3set price 12.2

First command creating a variable with name x and value 10. In second command string "john" is
assigned to variable name. Third command assigning float value to variable price.
IMPORTANT !if value is not specified in set command then it will return value of variable.

Exmaple :
set x ;# this command will return value of x

For deleting variable unset command is used.


Unset command :
unset x

Print/Use variable's value


Value of any variable can be used by using $ symbol. Let's say we want to assign value of x variable
to another variable y.
Command :
set y $x

Above command first replace $x by it's value which is 10 then 10 will be assigned to variable y.
For printing purpose put command is used.

put command :
1puts "hello world"

2# Output: helloworld

Above command will print hello world message on the screen and take cursor to new line. If we
want to print next message on the same line then -nonewline option has to be specified. # symbol is
used to provide comments.
Program :
?
1puts "hello world"
2puts -nonewline "welcome"
3puts " to TCL"

4
5# Output:
6# hello world
7# Welcome to TCL

In above code we have three commands. First command will print hello world on screen and then
move cursor to next line. Second command will print welcome on screen only. Third command will
print to TCL message at the end of second line.
Program :
1set x 10
2set y 20

3puts "value of x is $x"


4puts "value of y is $y"
5
6# Output:

7# value of x is 10
8# value of y is 20

Performing basic operations


In tcl expr command used to perform operations. expr command takes entire expression as
arguments. Let's say we want to add two variable x and y
Program :
1set x 10
2set y 20

3expr $x + $y
4
5#Output:
6# 30

expr command in above code add both variable and print their value.
In above code to assign result of addition to third variable z, brackets are used. Command written in
bracket replaced by it's result. For assiging result to variable z set command has to be used.
So command will be like
Syntax :
set z <result must be here>

For placing result of addition in set command we use brackets.


Program :
1set x 10

2set y 20
3set z [expr $x + $y]
4puts "result of addition: $z"
5

6# Output:
7# result of addition: 30

one more example for use of expr command to calculate area of circle
Example :
1set radius 7

2set pie [expr 22.0/7]


3set area [expr $pie*$radius*$radius]
4puts "Area of circle: $area"
5

6# Output:
7# Area of circle: 154.0

If-else
TCL also has construct for if-else. Syntax for if-else is given below.
Syntax :

if {condition} {
if-body
}

# Another syntax
if [ expr condition] {
if-body
}

Let's take one example for checking whether number is less than 10 or not.
Program :

1 set x 10
2 if { $x < 50 } {
3 puts "x is less than 50"
4 }
5

6
7 if [ expr $x == 20 ] {
8 puts "x is equal to 20"
9 } else {

10puts " x is not equal to 20"


11}
12# Output:
13x is less than 50

14x is not equal to 20

NOTE: Opening brace for if-body must be in same line of if-condition. If you place opening brace at new line
it will create error.
Program :
1 # Program to Calculate division of student.
2 set english 4
3 set maths 60
4 set science 60

5 set total [ expr $maths+$english+$science ]


6 set per [expr $total/3]
7 if { $per >60 } {
8 puts "first Division "

9 } elseif { $per >50} {


10puts "Second division "
11} elseif { $per > 33} {
12puts "third division "

13} else {
14puts "Failed "
15}
16#Output:
17# Second division
Exp.7: Tcl script: To study loop, Array, procedure and file
handling.
Objective: To understand basic syntax for creating loop, Array,
procedure and file handling.

Loop
In TCL while loop has similar syntax as in c. Only different is in condition specification.

● While Loop

Syntax :

while { condition } {
while-body
}

IMPORTANT !Note:Opening brace for while must be in same line of while-condition. If you place
opening brace at new line it will create error.

Example of printing event values form 0 to 100 :


1set s 0
2while { $s < 100 } {
3puts $s
4set s [expr $s+2]

5}

● For loop

For loop in tcl also has three parts initialisation, condition and increment or decrement.
Syntax :
for { initialisation} { condition} {increment/decrement} {
loop-body}

Example:
1 for {set i 0} { $i < 10} { incr i} {
2 puts $i
3 }
4 # Output:
5 #0
6 #1
7 #2
8 #3
9 #4

10#5
11#6
12#7
13#8
14#9

In the above program first part of for loop setting value of i as 0. second part has a condtion that
value of i must be less than 10. Third part increasing value of i. incr is special instruction of tcl
which increase i by 1.

Array
Array is a collection of homogeneous data. TCL also support named array in which string is given as
named variable.
Example :
1set a(0) 10
2 set a(1) 30
3 puts $a(0)
4###############Another Way

5array set b {10,30}


6puts $b(0)
7
8 # Output:

9 10

Procedure
Multiple commands can be combined to make a new command. This can be done by making a
procedure. Procedure is similar to function in 'c'.
Syntax:
proc <procedure name> { } {
procedure-body
}
Let's take one example of factorial to understand this concept.
Program :
1 # Program to make procedure for factorial

2 proc fact { a } {
3 set fact 1
4 for {set i 1} {$i <= $a} {incr i} {
5 set fact [expr $fact * $i]
6 }
7 puts $fact
8 }
9 # Calling procedure

10fact 5
11
12#Output:
13# 120

In above program we have created one fact procedure with one argument. In this procedure we have
used loop to calculate factorial. For calling a procedure procedure name and arguments need to be
specified.

Global Variable in Procedure


In procedure all variable known as local. If you wants to access some variable which are created
outside of procedure then global command is used.
Program :
1set x 20
2proc demo { } {
3global x
4set x 30
5}
6demo
7puts $x
8#Output:

9#20

In procedure we have specified that x is not a local variable. So now it will access variable x which
is created outside of procedure.
File Handling
Before performing any operation on file, that file need to be opened. In tcl open command is used to
open a channel with file to perform read/write operation. File can be opened in various mode which
allow which operation is allowed. These modes are
● Read only Mode (r)

● Write Only Mode(w)

● Append Mode (a)

● Read and Write (r+)

● Write and Read (w+)

Program :
1# For opening file
2# open <file_name> <acc_type>
3
4open one.txt r

5
6# For assigning open file handle to variable.
7set f_in [open one.txt r]

Above code will open "one.txt" file in read mode. It means only read operation can be performed on
this file. Last command in above code open "one.txt" in read mode and then assign it to variable
f_in, which can be used further for file processing.
puts command is used for writing data in file.
Syntax :
# Syntax for writing in file.

# puts <file_handle> <data|variable_value>

1
2set f [open one.txt w]
3puts $f "welcome to tcl"

4
5close $f
6
7
gets command is used for reading data from file.
Syntax :
1# Syntax for reading from file.
2# gets <file_handle> <variable_value>
3

4set f [open one.txt r]


5gets $f data
6
7puts $data
8close $f
Exp.8: Write OTCL program, Run program in terminal and
Analyze trace file using gawk.
Objective: To understand OTCL programing and how to run otcl
program on terminal and understand trace file using gawk tool.
OTCL is extension of TCL with object oriented feature. OTcl is short for MIT Object Tcl.

Otcl Topics:
Defining class
Defining data member of class
Defining methods in class

Defining a Class in OTcl


Objects are instances of class. Class can be thought as used defined data type and objects as variable
of that data type. In OTcl new class can be created by using Class command.
Syntax:
Class <class_name>

Example: Accound Class


1Class Account

Above command will create a class without any attributes and methods. Now variables of this class
can be created by using following command.
Example : Creating Object
1# object of Account class created.
2 Account john

Defining class' data member


class' data member can be defined by using set command with object name. These data members
have public visibility.
Syntax:
<object-name> set <attribute-name> <attribute-value>

If attribute value not specified in that case value of given attribute will be returned. Let's take
previous example of Account class. we have already created one object john. Let's add some
attributes to it.
Example :
1 # Create a new class Account

2 Class Account
3 # Create object of Account class
4 Account john
5 # Attach some attributes with object john

6 john set name "john"


7 john set balance 20000
8 john set ac_no 12322
9 john set type "saving"
10# Fetch value of attributes
puts [john set balance]
11
12
#Output
13
20000
14

In above program a new class Account is created. This class is instantiated by making a object of it.
Next we have attached some attributes with object john. These attributes are name, balance, ac_no
and type.
In last command brackets are used. These bracket replace command written within, by it's result.

Defining methods in class


Method or functions can be defined for a class with use of instproc command.
Syntax:
<class-name> instproc <function-name> { arguments } {
function-body
}

Let's define a method for above created class Account. Earlier we have created a object john of class
Account.
Example :
1Account instproc show {}
2{

3puts "show method is called"


4}

Access class' attributes inside methods


Attributes can be accessed by using instvar command. In member function data variable first need to
be declared with following command.
Syntax :
$self instvar <variable-name> <variable-name>

Before accessing data member in function/methods first it need to be declared that those members
are instance' variable of calling object. In previous program Object john is created with three
attributes. Now let's say we want to print details of john. Now we define a method show for class
Account.
Example :
1 Class Account
2 Account instproc show { } {
3 $self instvar name balance type
4 puts "Name:$name"
5 puts "Balance:$balance"
6 puts "Type:$type"
7 }
8 Account john
9 john set name "john"
10 john set balance 12000
11 john set type "saving"
12

13 john show
14 #Output:
15 #Name:john
16 #Balance:12000
17 #Type:saving
Exp.9: Write a OTCL Script and use constructor, destructor and
inheritance.
Objective: To understand OTCL programing concept like constructor,
destructor and inheritance.

Define Constructor
Constructor is special function get automatically called at time of object creation. Constructor is
useful when we want to assign some default values to data members. Let's define a constructor in
class Account. In order to defined constructor init function need to be defined in class.
Example:
1 Class Account
2 Account instproc init { } {

3 $self instvar name balance type


4 $self set balance 0
5 $self set type "saving"
6 }
7
8 # Create object of class Account
9 Account john
10puts [john set balance]

11puts [john set type]


12
13#Output:
14#0
15#saving

Above program has a constructor which assigning default values to data members. Now if we create
object of this class then that object will be having balance zero and type of account saving. It's also
possible to define parameterized constructor so that object can be initialised with given values.
Let's take example for better understanding
Example:
1 Class Account

2 Account instproc init {n b t } {


3 $self instvar name balance type
4 $self set name $n
5 $self set balance $b
6 $self set type $t
7 }

8
9 # Create object of class Account
10Account john "rocky" 54000 current
11puts [john set name]
12puts [john set balance]
13puts [john set type]
14
#Output:
15
#rocky
16
#54000
17
#current
18
19

Define Destructor
Destructor's name in OTcl not same as class name. In OTcl destructor remove object from
interpreter and release it's memory. destroy instproc works as destructor.
Example:
1 Class Account
2
3 Account instproc destroy { } {
4 puts "destructor called"
5 }
6 Account john
7 john destroy
8

9 #Output:
10# destructor called

Inheritance
OTcl also has commands to inherit a existing class. Inheritance feature allows programmer to create
new class by using existing one. Existing class is known as Parent class or super class and new class
is known as child class or sub class.
Syntax:
Class <sub-class-name> -superclass <super-class-name>

Example:
1 Class Vehicle
2 Vehicle instproc init { arg } {

3 $self instvar name


4 $self set name $arg
5 }
6

7 Class Two_wheeler -superclass Vehicle


8 Two_wheeler instproc init { arg } {
9 $self next $arg
10}

11
12Two_wheeler tw
13puts [tw set name]
Exp.10: Create Node and Link between Nodes using node and link
class using NS-2.
Objective: To understand, how to create a simulated nodes and link
between them nodes.

In ns2 node is a class which has many methods. This class used to simulate a computer in a
network.

Creating wired node


Simulator class has a procedure node which return a node.
command:
[simulator-instance] node
1 set ns [new Simulator] set n0 [$ns node]

Attach label to node


Label can be attached to node in NAM for better understanding.
Sytanx:
[node-instance] label [label]

Example :
1$n0 label "first Node"

Fetch next available port number


alloc-port is used to access available port number on a node for new agents.
Sytanx:
[node-instance] alloc_port null_agent

Example :
1$n0 alloc-port null_agent

Fetch list of neighbors


Every node maintain list of neighbors which are connected to that node.
Syntax:
[node-instance] neighbor

Example :
$n0 neighbors

Link

In ns2 nodes can be connected in two ways, simplex and duplex. Simplex connection allows one-
way communication and duplex connection allow two-way communication. Each type require
bandwidth, delay and type of queue for configuration.
Bandwidth is specified in Mbps(Mb) and delay is specified in milli seconds (ms).
Type of Queue available in ns2:DropTail, RED, CBQ, FQ, SFQ, DRR.
Syntax:
$ns simplex-link/duplex-link [node-instance1] [node-instance2] bandwidth delay Q-Type

Example:
# Connect nodes for two-way communication
$ns duplex-link $n0 $n1 2Mb 5ms DropTail

# Connect nodes with asymmetric channel capacity


$ns simplex-link $n0 $n1 3Mb 2ms DropTail
$ns simplex-link $n1 $n0 2Mb 5ms DropTail

Setting orientation of links in NAM


Position of links can be defined for better representation of network in NAM(Network AniMator).
Syntax :
$ns simplex-link-op/duplex-link-op [node-instance1] [node-instance2] orient [orientation]

Orientation can be right, left, up, down, up-right, up-left etc.


Note: Specified orientation applied to second node position respect to first
Exp.11: Practical: simulate three nodes point to point networks
with a duplex link between them. set the queue size and vary the
bandwidth and find the number of packets.
Aim: To understand point to point duplex communication between three
nodes. this practical cover queue size and different bandwidth between
nodes and number of packet in the network.

#Create simulator

set ns [new Simulator]

set ntrace [open 1.tr w]

$ns trace-all $ntrace

set file2 [open out.nam w]

$ns namtrace-all $file2

proc finish {} {

global ns ntrace

$ns flush-trace

close $ntrace

exit 0

#create node

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]


#create link

$ns duplex-link $n0 $n1 10Mb 10ms DropTail

$ns duplex-link $n1 $n2 10Mb 10ms DropTail

#Set Queue Size

$ns queue-limit $n0 $n1 10

$ns queue-limit $n1 $n2 10

#setup tcp connection

set tcp0 [new Agent/TCP]

$ns attach-agent $n0 $tcp0

#set sink to node

set sink [new Agent/TCPSink]

$ns attach-agent $n2 $sink

#connect tcp src and sink

$ns connect $tcp0 $sink

$tcp0 set window_ 1

set cbr [new Application/Traffic/CBR]

$cbr attach-agent $tcp0

$cbr set type_ CBR

$cbr set packetSize_ 100

$cbr set rate_ 0.1Mb

$cbr set random_ false

$ns at 0.0 "$cbr start"

$ns at 5.0 "finish"

$ns run
Exp.12: Practical: To implement Topology with using TCP and
UDP protocol.
Objective: To Simulate following Topology.

Topology Description
1. Network consists of 4 nodes (n0, n1, n2, n3).
2. The duplex links between n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10 ms of
delay.
3. The duplex link between n2 and n3 has 1.7 Mbps of bandwidth and 20 ms of delay.
4. Each node uses a DropTail queue, of which the maximum size is 10.
5. A “tcp” agent is attached to n0, and a connection is established to a tcp “sink” agent attached
to n3.
6. As default, the maximum size of a packet that a “tcp” agent can generate is 1KByte.
7. A tcp “sink” agent generates and sends ACK packets to the sender (tcp agent) and frees the
received packets.
8. A “udp” agent that is attached to n1 is connected to a “null” agent attached to n3.
9. A “null” agent just frees the packets received.
10. A “ftp” and a “cbr” traffic generator are attached to “tcp” and “udp” agents respectively,
11. The “cbr” is configured to generate 1 KByte packets at the rate of 1 Mbps.
12. The “cbr” is set to start at 0.1 sec and stop at 4.5 sec, and “ftp” is set to start at 1.0 sec and
stop at 4.0 sec.

Procedure:
1. Create a file called simple.tcl in ns2 directory which is in all-in-one package directory.
2. Place the following code in simple.tcl file.
3. Go to ns prompt
4. type: ns simple.tcl

Code:
1 #Create a simulator object
2 set ns [new Simulator]
3
4 #Define different colors for data flows (for NAM)
5 $ns color 1 Blue
6 $ns color 2 Red
7
8
#Open the NAM trace file
9
set nf [open out.nam w]
10
$ns namtrace-all $nf
11
12 #Define a 'finish' procedure
13 proc finish {} {
14 global ns nf
15 $ns flush-trace
16 #Close the NAM trace file
17 close $nf
18 #Execute NAM on the trace file
19 exec nam out.nam &
20 exit 0
21 }
22
23
#Create four nodes
24
set n0 [$ns node]
25
set n1 [$ns node]
26
set n2 [$ns node]
27
set n3 [$ns node]
28
29
30 #Create links between the nodes
31 $ns duplex-link $n0 $n2 2Mb 10ms DropTail
32 $ns duplex-link $n1 $n2 2Mb 10ms DropTail
33 $ns duplex-link $n2 $n3 1.7Mb 20ms DropTail
34
35 #Set Queue Size of link (n2-n3) to 10
36 $ns queue-limit $n2 $n3 10
37
38 #Give node position (for NAM)
39 $ns duplex-link-op $n0 $n2 orient right-down
40 $ns duplex-link-op $n1 $n2 orient right-up
41 $ns duplex-link-op $n2 $n3 orient right
42
43
#Monitor the queue for link (n2-n3). (for NAM)
44
$ns duplex-link-op $n2 $n3 queuePos 0.5
45
46
47 #Setup a TCP connection
48 set tcp [new Agent/TCP]
49 $tcp set class_ 2
50 $ns attach-agent $n0 $tcp
51 set sink [new Agent/TCPSink]
52 $ns attach-agent $n3 $sink
53 $ns connect $tcp $sink
54 $tcp set fid_ 1
55
56 #Setup a FTP over TCP connection
57 set ftp [new Application/FTP]
58 $ftp attach-agent $tcp
59 $ftp set type_ FTP
60
61 #Setup a UDP connection
62 set udp [new Agent/UDP]
63 $ns attach-agent $n1 $udp
64 set null [new Agent/Null]
65 $ns attach-agent $n3 $null
66 $ns connect $udp $null
67 $udp set fid_ 2
68
69
#Setup a CBR over UDP connection
70
set cbr [new Application/Traffic/CBR]
71
$cbr attach-agent $udp
72
$cbr set type_ CBR
73
$cbr set packet_size_ 1000
74
$cbr set rate_ 1mb
75
76 $cbr set random_ false
77
78 #Schedule events for the CBR and FTP agents
79 $ns at 0.1 "$cbr start"
80 $ns at 1.0 "$ftp start"
81 $ns at 4.0 "$ftp stop"
82 $ns at 4.5 "$cbr stop"
83
84
#Detach tcp and sink agents (not really necessary)
85
$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"
86
87
88 #Call the finish procedure after 5 seconds of simulation time
89 $ns at 5.0 "finish"
90
91 #Print CBR packet size and interval
92 puts "CBR packet size = [$cbr set packet_size_]"
puts "CBR interval = [$cbr set interval_]"

#Run the simulation


$ns run

You might also like