ns2

Post on 22-Nov-2014

280 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Introduction to NS2-Network Simulator-

What is ns?Object-oriented, discrete event-driven network simulator Written in C++ and OTcl By VINT: Virtual InterNet Testbed

Overview

- Event driven network simulator

- Developed at UC Berkely

- Implements network protocols 1) TCP, UPD

2) Traffic source mechanism: FTP, TELNET, Web, CBR and VBR

3) Router Queue management mechanism: Drop Tail, RED, CBQ

4) Routing Algorithm: Dijkstra, and etc…

5) Multicasting, Mac layer protocols for LAN

CONTI...

Background on the ns Simulator

- based on two languages( an object-oriented simulator (C++), and OTcl (object-oriented Tcl) interpreter.

- has rich library of network and protocol object

- Compiled C++ hierarchy gives efficiency in simulation and faster execution times.

- With OTcl script provided by user, a network topology is simulated.

CONTI...

Ns2 is event simulator where the advance of time depends on the timing of events which are maintained by a scheduler.

Event – an object in C++ hierarchy.

unique ID, Scheduled time,

pointer to an objectScheduler – maintains ordered data structure

with the events to be executed and fires them one by one, invoking the handler of the event.

HOW TO WRITE PROGRAM

Node CreationNode linksNetwork AgentsTraffic ApplicationsTelnet, FTP, HTTPPingTracingRouting and Network dynamics

Node Creation

Event schedulingCreate scheduler -> set ns [new

Simulator]Schedule Event -> $ns at <time>

<event>Start scheduler -> $ns run

TO CREAT NODES

set n0 [$ns node]set n1 [$ns node]The following creates 5 nodes, with handles n0-n4 for {set i 0} {$i<5} {incr i} {Set n($i) [$ns node] }To set the colour of a node, the following code is used.$n0 color <colour>where <colour> is black, re, blue, seaGreen

Node links

A unidirectional link between the two nodes is created as follows

· A Simplex link (one way) -> $ns simplex-link $n0 $n1 <bandwidth>

<delay> <queue_type>A bi-directional link between the two nodes is

created as follows· A duplex link (both ways) ->$ns duplex-link

$n0 $n1<bandwidth> <delay> <queue_type>

NETWORK AGENTS

There are two types of agents in NS-2: UDP and TCP agents

· UDPset udp0 [new Agent/UDP]set null [new Agent/NULL]$ns attach-agent $n0 $udp0 # attach the udp0 agent#to node 0$ns attach-agent $n1 $null$ns connect $udp $null

To add a Loss Monitor to the agent the following OTcl code is used. The

Agent/LossMonitor can monitor number of packets transferred, as well as packets lost

set lossMonitor [new Agent/LossMonitor] · $ns_ connect $udp0 $lossMonitor

TCPset tcp [new Agent/TCP]set tcp_sink [new Agent/TCPSink]$ns attach-agent $n0 $tcp $ns attach-

agent $n1 $tcp_sink$ns connect $tcp $tcp_sink # connect the

2 agents

Traffic Applications

CBR (Constant Bit Rate)- A CBR traffic object generates traffic according to a deterministic rate

Exponential-Traffic is determined by an exponential distribution. Packets are a constant size

Pareto-The distribution for traffic generation is taken from a pareto on/off distribution-

TrafficTrace-Traffic is generated according to a trace file

CBR (Constant Bit Rate)

set my_cbr [new Application/Traffic/CBR]· $my_cbr attach-agent $udp· $ns at <time> “$my_cbr start”Parameters:· start: starts sending packets according to the

configuration parameters· stop: stops sending packetsConfiguration parameters:· PacketSize_: constant size of packets generated

e.g 48

rate_: sending rate e.g. 64kb· interval_: (optional) interval time

between packets e.g 0.05· random_: Flag to introduce noise in the

departure times, default is off, 1 for on· maxpkts_: the maximum number of

packets to send e.g 1000

Exponential

set my_exp [new Application/Traffic/Exponential]Configuration parameters· PacketSize_: constant size of packets generated

e.g 210· burst_time_: average on time for the generator

e.g. 500ms· idle_time_: average off time for the generator e.g

500ms· rate_: sending rate during the “on” time e.g. 100k

Pareto

set my_pareto [new Application/Traffic/Pareto]Configuration parameters · PacketSize_: constant size of packets generated e.g.

210 · burst_time_: average on time for the generator e.g.

500ms · idle_time_: average off time for the generator e.g.

500ms · rate_: sending rate during the “on” time e.g. 100kshape_: the shape parameter used by the pareto

distribution e.g. 1.5

TrafficTrace

set t_file [new Tracefile]· $t_file filename <file>· set src [ new Application/Traffic/Trace]· $src attach-tracefile $t_filewhere $t_file is a binary file and the two

fields in the file contain inter-packets times in

milliseconds and packet size in bytes.

Telnet, FTP, HTTP

Application/FTPand Application/TelnetFile Transfer Protocol (FTP- for simulating bulk data

transfer)OTCL Code for using FTP in a simulation: · set ftp [new Application/FTP] · $ftp attach-agent $tcp · $ns at <time> “$ftp start”

parameters

· attach-agent: attach-agent: attaches an Application/FTP agent to an agent

24 of 39 · start: start the Application/FTP to send data · stop: stop sending data · produce n: where n is the counter of packets to be sent · producemore n: where n is the new increased value of

packets to be sent · send n: similar to producemore, but sends n bytes

instead of packets

TelnetOTcl code for using Telnet in a simulation: · set telnet [new Application/Telnet] · $telnet attach-agent $tcpParameters · start; start producing packets · stop: stop producing packets · attach-agent: attaches a Telnet object to an agent

Configuration Parameters· interval_: The average inter-arrival time in

seconds for packets generated bythe Telnet objectif(interval_ == 0) Inter arrival times taken from

the tcplib distribution.if(interval_ != 0) Inter arrival times taken from the

exponential distribution,average is set to what interval_ is.

Ping

To ping a node from another node, ping agents must be set up on both nodes

set PingAgent1 [new Agent/Ping]$ns attach-agent $node0 $ PingAgent1set PingAgent2 [new Agent/Ping]$ns attach-agent $node1 $ PingAgent2The two ping agents are connected as follows$ns connect $pB $p3To ping a node the following code is used$ns at 0.1 "$PingAgent1 send"

Tracing

A Trace file contains all information needed for animation purposes- both on a static network layout an on dynamic events such as packet arrivals, departures, drops and linkfailures

Tracing in NS-2 is implemented with the following OTcl code.

To Trace packets on all links · set trace_file [open out.tr w] · $ns trace-all $trace_file · $ns flush-trace · close $trace_file

To trace a specific link · ns trace-queue $node0 $node1 $trace_fileTo trace up variable tracing in NS-2 · set cwnd_chan_ [open all.cwnd w] · $tcp trace cwnd_ # tcp tracing its own variablecwnd_chan_ · $tcp attach $ cwnd_chan_The variable sstthresh of $tcp is traced by a generic

$tracer

· Set tracer [new Trace/Var]· $tcp trace ssthresh_ $tracer

Routing and Network dynamics

NS-2 implements three different routing strategies:

static routing, session routing and DVrouting

$ns rttproto Static · $ns rttproto Session · $ns rttproto DVThe rtmodel-at provides the facility to dynamically bring links

down or bring them up. · $ns rtmodel-at 1.0 down $node1 $node2 · $ns rtmodel-at 2.0 up $node1 $node2This model can be extended using an exponential

distribution for manipulating links.

· $ns rtmodel Exponential 0.7 2.0 2.0 down $node1 $node2

OTcl – The User Language

NS2 is basically an OTcl interpreter with network simulation object libraries

Very simple syntax and easy integration with other languages.

Characteristics: - fast development - provide graphic interface - compatible with many platforms - flexible for integration - easy to use - free

OTcl – The User Language

Example

OTcl – The User Language

Proc: define a procedure, followed by an procedure name and arguments

Set: assign a value to a variable[expr …]: to make the interpreter calculate

the value of expression within the bracketTo assign to variable x the value that

variable a has, then write “set x $a”.Put: prints out

OTcl – The User Language

Event Scheduler

Main users of an event scheduler are network components that simulate packet-handling delay or that need time

Event Scheduler

Two different types of event schedulers

- real time: for emulation which allow the simulator to interact with a real network

- non-real time: three implementations are available (Heap, List, Calendar). The default is set as Calendar

Event Scheduler

Example . . .

set ns [new Simulator]$ns use-scheduler Heap. . .

. . .set ns [new Simulator]$ns use-scheduler Heap$ns at 300.5 "complete_sim". . .

proc complete_sim {} {. . .}

Packet

NS2 packet is composed of a stack of headers and optional dataspace.

Packet format is initialized when a Simulator object is created. So, a network object can access any header in the stack of a packet it processes using corresponding offset value.

Packet

Simple Simulation Implement

Simple Simulation Implement

Introduction to TCL

Component technologies: Tcl: embeddable scripting language – Tk: GUI toolkit and widgets based on Tcl. The principle: universal scripting language controls everything: functions, interfaces, communication. Results: Raise the level of X programming: simpler, 5-10x faster application development. – Greater power: more things programmable, applications work together. – Active objects: replace data with scripts

Tcl: Tool Command Language

Interactive programs need command languages: – Typically redone for each application. – Result: weak, quirky. • emacs and csh powerful, but can't reuse. Solution: reusable scripting language. – Interpreter is a C library. – Provides basic features: variables, procedures, etc. – Applications extend with additional features

Tcl: Tool Command Language

Simple syntax (similar to sh, C, Lisp):set a 47 47Substitutions:set b $a 47set b [expr $a+10] 57u Quoting:set b "a is $a’’ a is 47set b {[expr $a+10]} [expr $a+10]

Rich set of built-in commands: – Variables, associative arrays, lists. – C-like expressions. – Conditionals, looping: if "$x < 3" { puts "x is too small" } – Procedures. – Access to TCP/IP sockets, files, subprocesses. Only representation is strings: – Easy access from C. – Programs and data interchangeable

Language OverviewTwo parts to learning Tcl:1. Syntax and substitution rules:– Substitutions simple, but may be

confusing at first.2. Built-in commands:– Can learn individually as needed.– Control structures are commands, not

language syntax

BasicsTcl script =– Sequence of commands.– Commands separated by newlines, semi-colons.u Tcl command =– One or more words separated by white space.– First word is command name, others are arguments.– Returns string result.u Examples: • set a 22; set b 33 • set a 22set b 33

Arguments Parser assigns no meaning to arguments (quoting by default, evaluation is special): C: x = 4; y = x+10 y is 14 Tcl: set x 4; set y x+10 y is "x+10" u Different commands assign different meanings to their arguments: set a 122 expr 24/3.2 eval "set a 122" button .b -text Hello -fg red string length Abracadabra

Variable SubstitutionSyntax: $varNameVariable name is letters, digits, underscores.May occur anywhere in a word.Sample command Resultset b 66 66set a b bset a $b 66set a $b+$b+$b 66+66+66set a $b.3 66.3set a $b4 no such variable

Tcl Syntax Summary

Script = commands separated by newlines orsemicolons.Command = words separated by white space.$ causes variable substitution. [ ]causes command substitution."" quotes white space and semi-colons. {} quotes all special characters. \ quotes next character, provides C-like

substitutions.# for comments (must be at beginning of command).

Command Substitution

Syntax: [script]Evaluate script, substitute result.May occur anywhere within a word.Sample command Resultset b 8 8set a [expr $b+2] 10set a "b-3 is [expr $b-3]" b-3 is 5

Controlling Word StructureWords break at white space and semi-colons,

except:– Double-quotes prevent breaks:set a "x is $x; y is $y"– Curly braces prevent breaks and substitutions:set a {[expr $b*$c]}– Backslashes quote special characters:set a word\ with\ \$\ and\ spaceSubstitutions don't change word structure:

set a "two words"set b $a

Expressions C-like (int and double), extra support for string operations. Command, variable substitution occurs within expressions. Used in expr, other commands. Sample command Result set b 5 5 incr b -1 4 expr ($b*4) - 3 17 expr $b <= 2 0 expr $a * cos(2*$b) -5.03443 expr {$b * [fac 4]} 120 set a Bill Bill expr {$a < "Anne"} 0

Lists Zero or more elements separated by white space: red green blue Braces and backslashes for grouping: a b {c d e} f List-related commands: concat lindex llength lsearch foreach linsert lrange lsort lappend list lreplace Examples: lindex {a b {c d e} f} 2 c d e lsort {red green blue} blue green red Useful with eval and foreach

Control Structures C-like appearance. Just commands that take Tcl scripts as arguments. Example: list reversal. set b "" set i [expr [llength $a] - 1] while {$i >= 0} { lappend b [lindex $a $i] incr i -1 } Commands: If for switch break Foreach while eval continue

Advanced Tcl Features Autoloading: – unknown procedure invoked when command doesn't exist. – Loads procedures on demand from libraries. – Uses search path of directories. Others (Tcl 7.5+): – Dynamic loading of binaries: load command. – Security: Safe-Tcl, namespaces. – Event-driven I/O. – Socket support.

Additional Tcl Features

File I/O commands: open gets seek flushglob file pid close read tell cd puts source eof pwd Subprocesses with exec command: catch {exec grep foo << $input | wc} error Variable scoping: global uplevel upvar Access to Tcl internals: info rename trace

ConstantsIn Tcl, all free constants are stringsUpshot

abc is the same as “abc”“5” is the same as 5

<, >, == ,<= and >= compare numericallyIf any of the arguments are non-numbers, errors are thrown

Strings can also be compared literally:string compare string1 string2

Variables,“set” command

Usage: set <varname> <value>In most other languages, <varname> = <value>Artifact of basis on LISP-like PLs (define varname value)

Example:set a 5puts $a puts = putString – exactly like C’s

Will print out 5What’s with the $ ?

$<varname> is the value of a variable with name varname

Weird…set a a will set the string “a” to the variable a

In Tcl, all free constants are stringsUpshot

abc is the same as “abc”“5” is the same as 5

<, >, == ,<= and >= compare numericallyIf any of the arguments are non-numbers, errors are thrown

Strings can also be compared literally:string compare string1 string2

Output to screenputs lets the programmer send output to the screenExample:

puts 5puts $aputs “The value of variable a is $a”

Variables can be freely placed in a puts string

Any way to suppress the new line?puts –nonewline “Enter some number:”Caveat: Most Operating System implementations use \n to trigger a flush of the buffer. In most cases, after a puts –nonewline, adding flush stdout is necessary

CommentsComments are C-shell and Perl style, and start with a #. The rest of the line is part of the commentExample 1: comment on its own line

# I will now set the variable a to 5set a 5

Comments after a statement need a slight changeExample 2: comment after a statement

set a 5 ;# I just set the variable a to 5We are essentially ending the current statement with the ; The rest of the line is the comment.

Math expressionsexpr is used for evaluating math expressionsUsage: expr <expression>Examples:

expr 5+3 will evaluate to 8expr 5*(7+3) will evaluate to 50

General Rule of ThumbAnything in <expression> is exactly the same as it would appear in C. If an expression is valid in C, then it is valid after exprThe only thing to remember is replacing all variable names with $<varname>, but this is generally not an issue

Setting results of Evaluation

[<expression>] denotes the value after evaluation of an expression

Example:set a [expr 5+6] will set the “result” of the expr to aset b [SomeFunction 6] will set the “return value” of “SomeFunction” to b

Careful![set a [expr 5+6]] will result in a syntax error, because 11 is not a function!

Keyboard Input

gets is a built-in Tcl command which allows for keyboard input by userExample:

puts “Please enter your name: “set userName [gets stdin]puts “Your name is $userName”

Example:puts “Enter a number: “set input [gets stdin]set output [Add2 $input]puts “$input plus 2 is $output”

Conditionals - if

Syntax: if { condition } { action1 } else { action2 }Example:

if { $a > 2 } {puts “$a is greater than

2”} else {

puts “$a is not greater than 2”

}There is no option as far as bracket style is concerned – it is enforced like above

Conditionals – on the condition

A condition is exactly as it would appear in CAny nonzero number is taken to be trueExamples:

if { $a > 5 }if { $a > $b }if { ($a > 5) || ($b < 3) || ($c != $d) }if { $a }If { !$done }

C rule of thumb

The condition works exactly as in C

Conditionals - elseif

Used for chaining if statementsExample:

if { $a > 0 } {puts “$a is a positive

number”} elseif { $a < 0 } {

puts “$a is a negative number”

} else {puts “$a is zero”

}

Incr – Incrementing/Decrementing

incr is an overloaded version of C’s ++,--,+=,-=Syntax: incr varName ?offset=1Examples:

incr i ;# Will increase i by one, the default

incr i -1 ;# Will reduce i by oneincr i 3 ;# Will increase i by threeincr i 0 ;# Will not change I

Common mistake:incr $i 2 will cause a syntax error. We need to the variable name to incr, not the value of the variable!

Loops - while

The while loop is exactly the same as it is in C!Syntax: while { condition } { action }Example:

set i 1while { $i <= 10 } {

puts “On iteration $i of 10”

incr i}

Loops - for

The for loop is exactly the same as it is in C!Syntax: for { initCond } { condition } { update }Example:

for { set i 1 } { $i <= 10 } { incr i } {puts “On iteration $i of

10”}

Procedures

By example:proc Add2 { number } {

set a [expr $number+2]return $a

}“proc” is a reserved word, and it denotes the start of a procedure{ number } this is a list of variablesreturn $a will return the value stored in aA procedure MUST be defined before being called.

No prototypes! – Except in Itcl, more later

Lists in TclA list is declared using the list built-in function:Example:

set a [list 1 2 3 4]The same can also be written as:

set a { 1 2 3 4 }Retrieving an element within a list: lindexlindex is 0-based, just like C

set b [lindex $a 3] ;# b has the value 4set b [lindex $a end] ;# b will have value 4set b [lindex $b 0] ;# b will have the value 1

List Operationsconcat : Concatenate two lists

set b [concat [list 1 2 3 4] [list 5 6 7]]b will be { 1 2 3 4 5 6 7 }

lappend : Append value at the end of list – By Name

set a [list 1 2 3]lappend a 4Now a will be { 1 2 3 4 }Note: lappend takes a list Name, not a list

llength : Return the length of a listllength [list 1 2 3] will be 3llength [list] will be 0

Many others… Read any Tcl book

Thank You….

top related