Sunteți pe pagina 1din 258

Introduction to ns-2

3/29/2007

NCKU

Outline
An introduction to ns-2

What is ns-2
Fundamentals
Writing ns-2 codes
Wireless support
Traces support and visualization
Emulation
Related work

3/29/2007

NCKU

What is ns-2
History
What does it support

3/29/2007

NCKU

Ns Goals
Support networking research and education
Protocol design, traffic studies, etc
Protocol comparison

Provide a collaborative environment


Freely distributed, open source
Share code, protocols, models, etc

Allow easy comparison of similar protocols


Increase confidence in results
More people look at models in more situations
Experts develop models

Multiple levels of detail in one simulator


3/29/2007

NCKU

Alternatives
Experimentation

Operational details,
but

Private lab
Public testbed (e.g.
Planetlab)
Shared labs (e.g.
Utah Emulab)

Limited scale
Expensive, limited
flexibility
Higher overhead

Analysis
Other simulator

Can provide
understanding, but

Custom simulators
Other general
simulators
3/29/2007

Limited details

Important niches
Limited re-use
NCKU

History of ns-2
History

Cornell REAL simulator -1989


VINT project (UCB, Xerox ,USC/ISI) 1995
USC/ISI SAMAN/CONSER project 1999

Size

~220K lines of codes

45% C++
31% OTcl
23% test suite/example/documents

~400 pages of mannual

Very steep learning curve for a new user!

The most popular non-commercial discrete event packet-level


simulator

Used by 10000+ users from 1000+ institutes from 50+ countries


300+ posts to ns-users@isi.edu every month

3/29/2007

NCKU

ns-2 support
Platform
FreeBSD, Linux, Solaris, Windows and Mac

Release
Periodical release: ~6 months
current release: ns-2.27, Jan 18, 2004

Daily snapshot

Validation
~100 test suites and 100+ examples

3/29/2007

NCKU

What ns-2 can simulate


Wired network
Traffic model and applications
Transport protocol
Routing and Queuing
QoS
LANs

Wireless network
Ad hoc routing and mobile IP
Sensor network
Propagation model/Energy model
WLAN (802.11)
Satellite

Error modules
Tracing, visualization, emulation, various utilities
3/29/2007

NCKU

Wired network
Application
HTTP, web caching
telnet, FTP, RealAudio
CBR, on-off source

Transport
UDP, TCP (almost all variants of TCP), RTP
SRM, PLM, LMS, PGM

Routing
Unicast (DV, LM, etc) and multicast routing (PIM etc)
Hierarchical routing
Manual routing
Broadcasting
MPLS

Queuing
RED, FIFO, FQ, SFQ, DRR, CBQ
Diffserv and IntServ
ECN
3/29/2007

NCKU

Wireless network
Ad-hoc network routing

AODV, DSR, TORA, DSDV

Mobile IP
ARP
Radio propagation model

Friss-space attenuation
Two-ray ground reflection model
Shadowing model

Sensor network

Direct diffusion
SMAC

WLAN

Ad-hoc mode
Infrastructure mode

Satellite

Geostationary
LEO

Energy model
Omni-directional antenna with unity gain
3/29/2007

NCKU

10

NsComponent
s
Ns, the simulator itself
Nam, the network animator
Visualize ns (or other) output
Nam editor: GUI interface to generate ns scripts

Pre-processing:
Traffic and topology generators

Post-processing:
Simple trace analysis, often in Awk, Perl, or Tcl

3/29/2007

NCKU

11

Installation
Getting the pieces
Tcl/TK 8.x
http://dev.scriptics.com

OTcl, TclCL, ns-2, nam-1:


http://www.isi.edu/nsnam/dist

Other utilities
http://www.isi.edu/nsnam/ns/ns-build.html
Tcl-debug, GT-ITM, xgraph,
3/29/2007

NCKU

12

Getting Help
ns-2 build questions
http://www.isi.edu/nsnam/ns/ns-build.html

ns-users@isi.edu
ns-users-request@isi.edu

s
ubs
c
r
i
bens
-us
er
s
i
nbody
Archive: http://www.isi.edu/nsnam/ns

3/29/2007

NCKU

13

Resources
Tcl (Tool Command Language)
http://dev.scriptics.com/scripting

OTcl (MIT Object Tcl)


~otcl/doc/tutorial.html (in distribution)

ns manual
Latex sources are included in distribution: ~ns/doc
http://www.isi.edu/nsnam/ns/ns-documentation.html

3/29/2007

NCKU

14

Cautions
Abstraction of the real world is necessary
for a simulator
You must justify the usage of the
simulator based on your research goals

3/29/2007

NCKU

15

Question?

3/29/2007

NCKU

16

Outline
An introduction to ns-2

What is ns-2
Fundamentals
Writing ns-2 codes
Wireless support
Traces support and visualization
Emulation
Related work

3/29/2007

NCKU

17

Prerequisite
Some programming experience of
object-oriented language (such as C++,
Java)

3/29/2007

NCKU

18

Discrete Event Simulation


Model world as events
Simulator has list of events
Scheduler: take next one, run it, until done
Each event happens in an instant of virtual
(simulated) time, but takes an arbitrary amount of
real time

Ns uses simple model: single thread of


control => no locking or race conditions to
worry about
3/29/2007

NCKU

19

Discrete Event Examples


Consider two nodes
on an Ethernet:

3/29/2007

simple
queuing
model:

t=1, A enqueues pkt on LAN


t=1.01, LAN dequeues pkt
and triggers B

t=1.0: A sends pkt to NIC


A
s NIC starts carrier sense
detailed
t=1.005: A
s NIC concludes cs,
CSMA/CD
starts tx
model:
t=1.006: B
s NIC begins reciving pkt
t=1.01: B
s NIC concludes pkt
B
s NIC passes pkt to app
NCKU

20

Ns Architecture
Object-oriented (C++, OTcl)

Lots of code reuses (e.g. TCP + TCP variants)


Use TclCl to bind C++ and OTcl together

Modular approach

Fine-grained object composition

From the simulator to a single event

TclCL
OTcl
Tcl

Event
Scheduler

Reusability
Maintenance
Performance (speed and memory)
Careful planning of modularity

Network
Components

C++

ns-2
3/29/2007

NCKU

21

C++ and OTcl Separation

dat
a/c
ont
r
ols
epar
at
i
on
C++ f
or
dat
a
:
per packet processing, core of ns
fast to run, detailed, complete control

OTcl for control:


Simulation scenario configurations
Periodic or triggered action
Manipulating existing C++ objects
fast to write and change

+ running vs. writing speed


Learning and debugging (two languages)
3/29/2007

NCKU

22

Control vs. Data


Create topology
Setup routing
Create transport
connection
Create traffic

Details of links and


nodes
Details of a routing
protocol
Details of TCP
implementation
Details of a packet
C++

OTcl
3/29/2007

NCKU

23

Otcl and C++: The Duality


C++
user
simulation
scripts

C++/OTcl
split objects

otcl
ns

OTcl (object variant of Tcl) and C++ share class


hierarchy
TclCL is glue library that makes it easy to share
functions, variables, etc
3/29/2007

NCKU

24

Basic Tcl
variables:
set x 10
put
s
xi
s$x

functions and expressions:


set y [pow x 2]
set y [expr x*x]
control flow:
if {$x > 0} { return $x } else {
return [expr -$x] }
while { $x > 0 } {
puts $x
incr x 1
}
3/29/2007

procedures:
proc pow {x n} {
if {$n == 1} { return $x }
set part [pow x [expr $n-1]]
return [expr $x*$part]
}
Also lists, associative arrays,
etc.
=> can use a real
programming language to
build network topologies,
traffic models, etc.

NCKU

25

Compare Otcl to C++


Object oriented extension of Tcl
C++ constructor/destructor => OTcl
init/destroy method

C++ this => OTcl $self


OTcl met
hodsal
waysvirtual
C++ static variable => OTcl class
variable
Multiple inheritance is supported

3/29/2007

NCKU

26

Basic otcl
Class Person
# constructor:
Person instproc init {age} {
$self instvar age_
set age_ $age
}
# method:
Person instproc greet {} {
$self instvar age_
puts
$age_y
ear
sol
d:How
ar
ey
oudoi
ng?
}

# subclass:
Class Kid -superclass Person
Kid instproc greet {} {
$self instvar age_
puts
$age_y
ear
sol
dki
d:
What

sup,dude?
}
set a [new Person 45]
set b [new Kid 15]
$a greet
$b greet

=> can easily make variations of existing things (TCP, TCP/Reno)


3/29/2007

NCKU

27

Using ns
Problem
Result
analysis

Simulation
model

Modify
ns

Setup/run
simulation
with ns
3/29/2007

NCKU

28

C++/OTcl Linkage
Root of ns-2 object hierarchy
TclObject

bind(): link variable values between


C++ and OTcl
command(): link OTcl methods to C++
implementations

TclClass
Tcl

Cr
eat
eandi
ni
t
i
al
i
z
eTc
l
Obj
ec
t

s
C++ methods to access Tcl interpreter

TclCommand Standalone global commands


EmbeddedTcl ns script initialization
3/29/2007

NCKU

29

TclObject
Basic hierarchy in ns for split objects
Mirrored in both C++ and OTcl
Example
set tcp [new Agent/TCP]
$tcp set packetSize_ 1024
$tcp advanceby 5000

3/29/2007

NCKU

30

TclObject: Hierarchy and


Shadowing
C++ class
hierarchy

TclObject OTcl class


hierarchy

TclObject

Agent

Agent

Agent/TCP

TcpAgent
*tcp

_o123
Agent/TCP OTcl
shadow object
3/29/2007

Agent/TCP C++
object
NCKU

31

TclObject::bind()
Link C++ member variables to OTcl
object variables
C++
TcpAgent::TcpAgent() {
bind(window_, &wnd_);

OTcl
set tcp [new Agent/TCP]
$tcp set window_ 200
3/29/2007

NCKU

32

TclObject::command()
Implement OTcl methods in C++
Trap point: OTcl method cmd{}
Access the shadow object

Send all arguments after cmd{} call to


TclObject::command()

3/29/2007

NCKU

33

TclObject::command()
$tcp send

OTcl space

no such
procedure

TclObject::unknown{}

$tcp cmd send

C++ space
TcpAgent::command()

Yes

match

s
end
?

Invoke parent:
return Agent::command()

process and return

3/29/2007

No

NCKU

34

TclObject::command()
OTcl
set tcp [new Agent/TCP]
$tcp send 10

C++
int TcpAgent::command(int argc,
const char*const* argv) {
if (argc == 3) {
if (strcmp(argv[1], send) == 0) {
int newseq = atoi(argv[2]);

return(TCL_OK);
}
}
return (Agent::command(argc, argv);
}
3/29/2007

NCKU

35

TclObject: Creation and


Deletion
Global procedures: new{}, delete{}
Example
set tcp [new Agent/TCP]

delete $tcp

3/29/2007

NCKU

36

TclObject: Creation and


Deletion
Agent/TCP
constructor
invoke parent
constructor
complete
initialization

Parent(Agent)
constructor
invoke parent
constructor
complete
which
C++
initialization
object
to create?

TclObject
constructor
create C++
object
create OTcl
shadow object

TclClass

TclObject (C++)
constructor

parent (Agent)
constructor

AgentTCP
constructor

do nothing,
return

invoke parent
constructor
bind variables
and return

invoke parent
constructor
bind variables
and return

3/29/2007

NCKU

OTcl
C++

37

TclClass
C++
TclObject
NsObject
Agent
TcpAgent

3/29/2007

mirroring
OTcl
Static
::public
Static class
class TcpClass
TcpClass
public TclClass
TclClass {{
public:
public:
TclObject
TcpClass()
::TclClass(

Agent/TCP
)
{
}
TcpClass()
TclClass(

Agent/TCP
)
{
}
TclObject*
TclObject*create(int,
create(int,const
const char*const*)
char*const*) {{
return
return(new
(newTcpAgent());
TcpAgent());
??
}}
}} class_tcp;
class_tcp;
Agent
Agent/TCP

NCKU

38

NsObject
Other important objects:
NsObject: has recv() method
Connector: has target() and drop()
BiConnector: uptarget() &
downtarget()
Class hierarchy

PRESENTATION
SESSION
TRANSPORT
NETWORK

NsObject
Connector
PingAgent
BiConnector
Mac802_11

3/29/2007

APPLICATION

MAC
PHY

NCKU

39

Class Tcl
Singleton class with a handle to Tcl interpreter
Tcl& tcl = Tcl::instance();

Usage

Invoke OTcl procedure


tcl.evalc(

callbackX
)
;

Obtain OTcl evaluation results


clock_ = atof(tcl.result());

Pass a result string to OTcl


tcl.resultf(%g, clock())
Return success/failure code to OTcl
tcl.error(command not found);

3/29/2007

NCKU

40

Class Tcl
Tcl& tcl = Tcl::instance();
if (argc == 2) {
if (strcmp(argv[1], now) == 0) {
tcl.resultf(%g, clock());
return TCL_OK;
}
tcl.error(command not found);
return TCL_ERROR;
} else if (argc == 3) {
tcl.eval(argv[2]);
clock_ = atof(tcl.result());
return TCL_OK;
}
3/29/2007

NCKU

41

Class TclCommand
How to implement an OTcl c
ommand
ns
-r
andomi
n
C++
class RandomCommand : public TclCommand {
public:
RandomCommand() : TclCommand("ns-random") {}
virtual int command(int argc, const char*const* argv);
};
int RandomCommand::command(int argc, const char*const* argv)
{
Tcl& tcl = Tcl::instance();
if (argc == 1) {
sprintf(tcl.buffer(), "%u", Random::random());
tcl.result(tcl.buffer());
}
3/29/2007

NCKU

42

Brief summary
TclObject
Unified interpreted (OTcl) and compiled
(C++) class hierarchies
Seamless access (procedure call and variable
access) between OTcl and C++

TclClass
Establish interpreted hierarchy
Shadowing objects

Tcl: primitives to access Tcl interpreter


3/29/2007

NCKU

43

Question?

3/29/2007

NCKU

44

Ns programming
Create the event scheduler
Turn on tracing
Create network
Setup routing
Insert errors
Create transport connection
Create traffic
Transmit application-level data
3/29/2007

NCKU

45

Creating Event Scheduler


Create event scheduler
set ns [new Simulator]

Schedule events
$ns at <time> <event>
<event>: any legitimate ns/tcl commands

$nsat5.
0
f
i
ni
s
h

Start scheduler
$ns run
3/29/2007

NCKU

46

Event Scheduler
Event: at-event and packet
List scheduler: default (FIFO)

Heap: good for many events (O(log n)


Calendar queue

A priority queue having N buckets each with width w. An item with


priority p goes in bucket (p/w)%N

Real-time scheduler

Synchronize with real-time


Network emulation
set ns_ [new Simulator]
$ns_ use-scheduler Heap
$ns
_at300.
5
$s
el
fhal
t

3/29/2007

NCKU

47

Some scheduler-related
commands
Set now [$ns now]
$ns cancel <event>
$ns after <delay> <event>
Execute <event> after <delay>

$ns dumpq
Dump all events in the scheduler queue

3/29/2007

NCKU

48

Discrete Event Scheduler


time_, uid_, next_, handler_
head_ ->
head_ ->

handler_ -> handle()


insert

3/29/2007

time_, uid_, next_, handler_

NCKU

49

Hello World - Interactive


Mode
Interactive mode:
swallow 71% ns
% set ns [new Simulator]
_o3
% $ns at 1 puts \Hello
World!\
1
% $ns at 1.5 exit
2
% $ns run
Hello World!
swallow 72%

3/29/2007

Batch mode:
simple.tcl
set ns [new Simulator]
$ns at 1 puts \Hello
World!\
$ns at 1.5 exit
$ns run

swallow 74% ns simple.tcl


Hello World!
swallow 75%

NCKU

50

Tracing and Monitoring I


Packet tracing:
On all links: $ns trace-all [open out.tr w]
On one specific link: $ns trace-queue $n0 $n1$tr
<Event> <time> <from> <to> <pkt> <size> -- <fid> <src> <dst> <seq>
<attr>

+ 1 0 2 cbr 210 ------- 0 0.0 3.1 0 0


- 1 0 2 cbr 210 ------- 0 0.0 3.1 0 0
r 1.00234 0 2 cbr 210 ------- 0 0.0 3.1 0 0

Event tracing (support TCP currently)


Rec
or
d
ev
ent
i
nt
r
ac
ef
i
l
e:$ns eventtrace-all
E 2.267203 0 4 TCP slow_start 0 210 1

3/29/2007

NCKU

51

Tracing and Monitoring II


Queue monitor
set qmon [$ns monitor-queue $n0 $n1 $q_f $sample_interval]

Get statistics for a queue


$qmon set pdrops_

Record to trace file as an optional

Flow monitor
set fmon [$ns_ makeflowmon Fid]
$ns_ attach-fmon $slink $fmon
$fmon set pdrops_

3/29/2007

NCKU

52

Tracing and Monitoring III


Visualize trace in nam
$ns namtrace-all [open test.nam w]
$ns namtrace-queue $n0 $n1

Variable tracing in nam


Agent/TCP set nam_tracevar_ true
$tcp tracevar srtt_
$tcp tracevar cwnd_

Monitor agent variables in nam


$ns add-agent-trace $tcp $tcp
$ns monitor-agent-trace $tcp
$srm0 tracevar cwnd_

$ns delete-agent-trace $tcp


3/29/2007

NCKU

53

Ns Internals
Tcl commands translates into
series of object creation
plumbing of these objects

3/29/2007

NCKU

54

Creating Network
Nodes
set n0 [$ns node]
set n1 [$ns node]

Links and queuing


$ns <link_type> $n0 $n1 <bandwidth>
<delay> <queue_type>
<link_type>: duplex-link, simplex-link
<queue_type>: DropTail, RED, CBQ, FQ, SFQ,
DRR, diffserv RED queues
3/29/2007

NCKU

55

Network Topology: Node


n0
Port
Classifier
Addr
Classifier
Node entry

entry_
classifier_

dmux_

n1
Unicast
Node

Multicast
Node classifier_
Node entry

entry_

dmux_

Multicast
Classifier
multiclassifier_

set n0 [ns_ node]

Set ns_ [new Simulator multicast on]


Set n1 [ns_ node]

Node Addressing
Two basic address styles available: flat
and hierarchical
Default flat address: 32 bits each for node
and port id
Default hier address:
3 levels of hierarchy
10 11 11 or 1 9 11 11 if mcast specified

Different bit allocation possible for specific


hier addresses
3/29/2007

NCKU

57

Hierarchical Node
n2

Address
classifier
Node
entry

To Port
demux
Level 3

Level 1

Level 2

ns_ node-config addressing hier


58

Classifiers
Table of n slots
When a packet is received
classify() identifies the slot to forward the packets

Address Classifiers
Parse address in packet

Methods
Install{}:
Elements{}
Clear{}
3/29/2007

NCKU

59

Network Topology: Link


n0

n1
duplex link

head_

enqT_
tracing

queue_
drophead_

deqT_

link_

drpT_

[ns_ duplex-link $n0 $n1 5Mb 2ms drop-tail]

ttl_
simplex link

n1
entry_

Connectors
Connectors

Receive incoming packets, and transmit them to their target_

Different types of connectors


Queue

Holds a certain number of packets. Packets exceeding their


queue-s
i
z
ear
es
entt
ot
hequeue
sdrop-target_

LinkDelay

Model delay/bandwidth of the link

TTLChecker

Decrements TTL on each packet, drops the packet if the TTL


becomes 0

DynaLink

Transmit packets if the link is up, drop packet otherwise

Trace
3/29/2007

NCKU

61

Creating Network: LAN


$ns make-lan <node_list> <bandwidth>
<delay> <ll_type> <ifq_type>
<mac_type> <channel_type>
<ll_type>: LL
<ifq_type>: Queue/DropTail,
<mac_type>: MAC/802_3
<channel_type>: Channel
3/29/2007

NCKU

62

Setup Routing
Unicast
$ns rtproto <type>
<type>: Static, Session, DV, cost, multi-path

Multicast
$ns multicast (right after [new Simulator])
$ns mrtproto <type>
<type>: CtrMcast, DM, ST, BST

Other types of routing supported: source routing,


hierarchical routing
3/29/2007

NCKU

63

Routing..
n0

n1

Port
Classifier
Addr
Classifier
Node entry
entry_

0
1

dmux_

enqT_

classifier_

3/29/2007

n1
entry
_

head_
queue_
drophead_

NCKU

deqT_

link_

ttl_

drpT_

64

..Routing
n0

n1

Port
Classifier

Port
Classifier

Addr
Classifier

entry_

0
1

Addr
Classifier
dmux_

Link n0-n1
entry_

classifier_

1
0

dmux_

classifier_

Link n1-n0

3/29/2007

NCKU

65

Class RouteLogic
Route configuration
rtproto{} -> configure{} -> compute-routes{}

Query nexthop
[$ns get-routelogic] lookup $n1 $2

Recompute route on topology change


[$ns get-routelogic] notify

3/29/2007

NCKU

66

Inserting Errors
Creating Error Module
set loss_module [new ErrorModel]
$loss_module set rate_ 0.01
$loss_module unit pkt
$loss_module ranvar [new RandomVariable/Uniform]
$loss_module drop-target [new Agent/Null]

Inserting Error Module


$ns lossmodel $loss_module $n0 $n1

3/29/2007

NCKU

67

Network Dynamics
Link failures
Hooks in routing module to reflect routing
changes

Four models
$ns
$ns
$ns
$ns

rtmodel Trace <config_file> $n0 $n1


rtmodel Exponential {<params>} $n0 $n1
rtmodel Deterministic {<params>} $n0 $n1
rtmodel-at <time> up|down $n0 $n1

Parameter list
[<start>] <up_interval> <down_interval> [<finish>]

3/29/2007

NCKU

68

Creating Connection and


Traffic I
UDP

CBR

set udp [new Agent/UDP] set src [new


Application/Traffic/CBR]
set null [new Agent/Null]
$ns attach-agent $n0 $udp Exponential or Pareto
on-off
$ns attach-agent $n1 $null
set src [new
$ns connect $udp $null

Application/Traffic/Exponential]
set src [new
Application/Traffic/Pareto]
$src attach-agent $udp

3/29/2007

NCKU

69

Creating Connection and


Traffic II
TCP

FTP

set tcp [new Agent/TCP]


set tcpsink [new
Agent/TCPSink]
$ns attach-agent $n0 $tcp
$ns attach-agent $n1
$tcpsink
$ns connect $tcp $tcpsink

set ftp [new Application/FTP]


$ftp attach-agent $tcp

3/29/2007

NCKU

Telnet
set telnet [new
Application/Telnet]
$telnet attach-agent $tcp

70

Creating Traffic: Trace


Driven
Trace driven
set tfile [new Tracefile]
$tfile filename <file>
set src [new Application/Traffic/Trace]
$src attach-tracefile $tfile
<file>:
Binary format (native!)
inter-packet time (msec) and packet size (byte)

3/29/2007

NCKU

71

Transport
n0

n1

Port
Classifier

Port
Classifier

Addr
Classifier

dmux_

entry_

dst_=1.0
Agent/TCP
agents_

Addr
Classifier

dmux_

dst_=0.0
Agent/TCPSink
agents_

entry_
classifier_

classifier_

set tcp [new Agent/TCP]


set tcpsink [new Agent/TCPSink]
ns_ attach-agent $n0 $tcp
ns_ attach-agent $n1 $tcpsink
ns_ connect $tcp $tcpsink

Application
n0

n1
Application/FTP
dst_=1.0

Port
Classifier
Addr
Classifier

Port
Classifier
Addr
Classifier

Agent/TCP
agents_

dmux_

entry_

dst_=0.0
Agent/TCPSink
agents_

dmux_

entry_
classifier_

classifier_

set ftp [new Application/FTP]


$ftp attach-agent $tcp
$nsat1.
2
$f
t
pst
ar
t

73

Packet Flow
n0

n1

Port
Classifier
Addr
Classifier

entry_

0
1

Application/FTP
dst_=1.0

Port
Classifier
Addr
Classifier

Agent/TCP

Link n0-n1
entry_

dst_=0.0
Agent/TCPSink

1
0

Link n1-n0

3/29/2007

NCKU

74

Application objects I
Exponential

packetSize_
burst_time_
idle_time_
rate_

CBR

packetSize_
rate_
interval_
random_
maxpkts_

3/29/2007

NCKU

75

Application objects II
Pareto

packetSize_
burst_time_
idle_time_
rate_
shape_

Telnet

interval_

FTP

maxpkts_

All above are virtual applications

f
oc
usonl
yon
s
i
z
eand
t
i
mewhendat
aar
et
r
ans
f
er
r
ed

3/29/2007

NCKU

76

Application-Level
Simulation
Simulate applications that actually transfer their
own data
e.g. simulate various webcaching algorithms

Features
Build on top of existing transport protocol
Transmit user data, e.g., HTTP header

Two different solutions


TCP: Application/TcpApp
UDP: Agent/Message
3/29/2007

NCKU

77

Compare to Real World


More abstract (much simpler):
No addresses, just global variables
Connect them rather than name
lookup/bind/listen/accept

Easy to change implementation


Set tsrc2 [new agent/TCP/Newreno]
Set tsrc3 [new agent/TCP/Vegas]

3/29/2007

NCKU

78

Summary: Generic Script


Structure
set ns [new Simulator]
# [Turn on tracing]
# Create topology
# Setup packet loss, link dynamics
# Create routing agents
# Create:
#
- multicast groups
#
- protocol agents
#
- application and/or setup traffic sources
# Post-processing procs
# Start simulation
3/29/2007

NCKU

79

Question?

3/29/2007

NCKU

80

Two examples
Multicast
Web traffic

3/29/2007

NCKU

81

Example: Multicast
Routing
Dynamic group membership
time
time G1
G2
1.3s
1.25s
1.35s
1.2s G2

n2

1.5Mb, 10ms

n0

1.5Mb, 10ms

n1

G1

1.5Mb, 10ms

G2
3/29/2007

n3
NCKU

82

Multicast: Step 1
Scheduler, tracing, and topology
# Create scheduler
set ns [new Simulator]
# Turn on multicast
$ns multicast
# Turn on Tracing
set fd [new mcast.nam w]
$ns namtrace-all $fd
3/29/2007

NCKU

83

Multicast: Step 2
Topology
# Create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
# Create links
$ns duplex-link
$ns duplex-link
$ns duplex-link
3/29/2007

$n0
$n0
$n0

$n1
$n2
$n3

1.5Mb
1.5Mb
1.5Mb

NCKU

10ms
10ms
10ms

DropTail
DropTail
DropTail
84

Multicast: Step 3
Routing and group setup
# Routing protocol: lets run distance vector
$ns mrtproto DM
# Allocate
set group1
set group2

3/29/2007

group
[Node
[Node

addresses
allocaddr]
allocaddr]

NCKU

85

Multicast: Step 4
Sender 0
# Transport agent for the traffic source
set udp0 [new Agent/UDP]
$ns attach-agent $n1 $udp0
$udp0 set dst_addr_ $group1
$udp0 set dst_port_ 0
# Constant Bit Rate source #0
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
# Start at time 1.0 second
$ns at 1.0 "$cbr0 start"
3/29/2007

NCKU

86

Multicast: Step 5
Sender 1
# Transport agent for the traffic source
set udp1 [new Agent/UDP]
$ns attach-agent $n3 $udp1
$udp1 set dst_addr_ $group2
$udp1 set dst_port_ 0
# Constant Bit Rate source #0
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1
# Start at time 1.1 second
$ns at 1.1 "$cbr1 start"
3/29/2007

NCKU

87

Multicast: Step 6
Receiver with dynamic membership
# Can also be Agent/Null
set rcvr [new Agent/LossMonitor]
# Assign it to node $n2
$ns at 1.2 "$n2 join-group $rcvr $group2"
$ns at 1.25 "$n2 leave-group $rcvr $group2"
$ns at 1.3 "$n2 join-group $rcvr $group2"
$ns at 1.35 "$n2 join-group $rcvr $group1"

3/29/2007

NCKU

88

Multicast: Step 7
End-of-simulation wrapper (as usual)
$ns at 2.0 "finish"
proc finish {} {
global ns fd
close $fd
$ns flush-trace
puts "running nam..."
exec nam mcast.nam &
exit 0
}
$ns run
3/29/2007

NCKU

89

Example: Web traffic


8

3
10Mb, 20ms

10

11

3/29/2007

1.5Mb, 40ms

NCKU

90

Web traffic: Step 1


Scheduler and tracing
# Create scheduler
set ns [new Simulator]
# instantiate web traffic class
set pool [new PagePool/WebTraf]

# Turn on Tracing
set fd [new web.nam w]
$ns namtrace-all $fd
3/29/2007

NCKU

91

Web traffic: Step 2


Topology
# Create nodes

for {set i 0} {$i < 12} {incr i} {


set n($i) [$ns node]
}
$ns set src_ [list 2 3 4 5 6]
$ns set dst_ [list 7 8 9 10 11]

# Create links
$ns duplex-link $n(0) $n(1) 1.5Mb 40ms DropTail
$ns duplex-link $n(0) $n(2) 10Mb 20ms DropTail
$ns duplex-link $n(0) $n(3) 10Mb 20ms DropTail
3/29/2007

NCKU

92

Web traffic: Step 3


Set up client and server nodes
$pool set-num-client [llength [$ns set src_]]

$pool set-num-server [llength [$ns set dst_]]


set i 0
foreach s [$ns set src_]
$pool set-client $i
incr i
}
set i 0
foreach s [$ns set dst_]
$pool set-server $i
incr i
}

3/29/2007

{
$n($s)

{
$n($s)

NCKU

93

Web traffic: Step 4


Specify the distributions for page arrival,
page size, object arrival, object size
set interPage [new RandomVariable/Exponential]
$interPage set avg_ 1
set pageSize [new RandomVariable/Constant]
$pageSize set val_ 1
set interObj [new RandomVariable/Exponential]
$interObj set avg_ 0.01
set objSize [new RandomVariable/ParetoII]
$objSize set avg_ 10
$objSize set shape_ 1.2

3/29/2007

NCKU

94

Web traffic: Step 5


Schedule web sessions
# Lets schedule two sessions
$pool set-num-session 2
# Lets have 10 pages per session
set numPage 10
# session 1 starts at time 0.1s
$pool create-session 0 $numPage 0.1 $interPage $pageSize
$interObj $objSize
# session 2 starts at time 1.2s
$pool create-session 1 $numPage 1.2 $interPage $pageSize
$interObj $objSize

3/29/2007

NCKU

95

Web traffic: Step 6


End-of-simulation wrapper (as usual)
$ns at 10.0 "finish"
proc finish {} {
global ns fd
close $fd
$ns flush-trace
puts "running nam..."
exec nam web.nam &
exit 0
}
$ns run
3/29/2007

NCKU

96

Question?

3/29/2007

NCKU

97

Outline
An introduction to ns-2

What is ns-2
Fundamentals
writing ns-2 codes
Wireless support
Traces support and visualization
Emulation
Related work

3/29/2007

NCKU

98

Writing ns-2 codes


Extending ns
In OTcl
In C++

Debugging

3/29/2007

NCKU

99

ns Directory Structure
ns-allinone
Tcl8.3

TK8.3

OTcl

tclcl
...

tcl
ex
examples

test

lib

validation tests
ensure new changes do not

ns-2

nam-1

C++ code

mcast

...

OTcl code

break the old codes


3/29/2007

NCKU

100

Extending ns in OTcl
I
fy
oudon
twantt
oc
ompi
l
e
source your changes in your simulation
scripts

Otherwise
Modifying code; recompile
Adding new files
Change Makefile (NS_TCL_LIB), tcl/lib/ns-lib.tcl
Recompile
3/29/2007

NCKU

101

Example: Agent/Message

n2

cross
traffic

n0

128Kb, 50ms

10Mb, 1ms

n4

n5

n1
10Mb, 1ms

n3

message agent

3/29/2007

NCKU

102

Agent/Message
pkt: 64 bytes
of arbitrary
string

Receiver-side
processing

An UDP agent (without UDP header)


Up to 64 bytes user message
Good for fast prototyping a simple idea
Usage requires extending ns functionality
3/29/2007

NCKU

103

Agent
A protocol endpoint/enity
Provide
a local and destination address (like an IP-layer sender)
Functions to generate or fill in packet fields

To create a new agent


Decide its inheritance structure
Create recv function (and timeout if necessary) to
process the packets
Define OTcl linkage if necessary
Create new header if necessary

3/29/2007

NCKU

104

Exercise
Def
i
neanew c
l
as
s
Sender
andanew c
l
as
s

Rec
ei
ver
whi
c
har
ebas
edonc
l
as
sAgent
/
Mes
s
age
Sender
Send a message to the Receiver every 0.1 sec
Message contains its address and a sequence number

Receiver
Receive message from the Sender
Acknowledge the receive message to the sender
The acknowledgement contains its address and the
sequence number of received message

3/29/2007

NCKU

105

Agent/Message: Step 1
Define sender
class Sender superclass Agent/Message
# Message format: Addr Op SeqNo
Sender instproc send-next {} {
$self instvar seq_ agent_addr_
$self send $agent_addr_ send $seq_
incr seq_
global ns
$ns at [expr [$ns now]+0.1] "$self send-next"
}

3/29/2007

NCKU

106

Agent/Message: Step 2
Define sender packet processing
Sender instproc recv msg {
$self instvar agent_addr_
set sdr [lindex $msg 0]
set seq [lindex $msg 2]
puts "Sender gets ack $seq from $sdr"
}

3/29/2007

NCKU

107

Agent/Message: Step 3
Define receiver packet processing
Class Receiver superclass Agent/Message
Receiver instproc recv msg {
$self instvar agent_addr_
set sdr [lindex $msg 0]
set seq [lindex $msg 2]
puts Receiver gets seq $seq from $sdr
$self send $addr_ ack $seq
}

3/29/2007

NCKU

108

Agent/Message: Step 4
Scheduler and tracing
# Create scheduler
set ns [new Simulator]
# Turn on Tracing
set fd [new message.tr w]
$ns trace-all $fd

3/29/2007

NCKU

109

Agent/Message: Step 5
Topology
for {set i 0} {$i < 6} {incr i} {
set n($i) [$ns node]
}
$ns duplex-link $n(0) $n(1) 128kb 50ms DropTail
$ns duplex-link $n(1) $n(4) 10Mb 1ms DropTail
$ns duplex-link $n(1) $n(5) 10Mb 1ms DropTail
$ns duplex-link $n(0) $n(2) 10Mb 1ms DropTail
$ns duplex-link $n(0) $n(3) 10Mb 1ms DropTail
$ns queue-limit $n(0) $n(1) 5
$ns queue-limit $n(1) $n(0) 5

3/29/2007

NCKU

110

Agent/Message: Step 6
Routing
# Packet loss produced by queueing
# Routing protocol: lets run distance vector
$ns rtproto DV

3/29/2007

NCKU

111

Agent/Message: Step 7
Cross traffic
set
$ns
set
$ns
$ns

udp0 [new Agent/UDP]


attach-agent $n(2) $udp0
null0 [new Agent/NULL]
attach-agent $n(4) $null0
connect $udp0 $null0

set exp0 [new Application/Traffic/Exponential]


$exp0 set rate_ 128k
$exp0 attach-agent $udp0
$ns at 1.0 $exp0 start

3/29/2007

NCKU

112

Agent/Message: Step 8
Message agents
set sdr [new Sender]
$sdr set seq_ 0
$sdr set packetSize_ 1000
set rcvr [new Receiver]
$rcvr set packetSize_ 40
$ns attach-agent
$ns attach-agent
$ns connect $sdr
$ns at 1.1 $sdr
3/29/2007

$n(3) $sdr
$n(5) $rcvr
$rcvr
send-next
NCKU

113

Agent/Message: Step 9
End-of-simulation wrapper (as usual)
$ns at 2.0 finish
proc finish {} {
global ns fd
$ns flush-trace
close $fd
exit 0
}
$ns run
3/29/2007

NCKU

114

Agent/Message: Result
Example output
> ./ns msg.tcl
Receiver gets seq
Sender gets ack 0
Receiver gets seq
Sender gets ack 1
Receiver gets seq
Sender gets ack 2
Receiver gets seq
Sender gets ack 3
Receiver gets seq
Sender gets ack 4
Receiver gets seq
3/29/2007

0 from
from 5
1 from
from 5
2 from
from 5
3 from
from 5
4 from
from 5
5 from

3
3
3
3
3
3
NCKU

115

Add Your Changes into ns


ns-allinone
Tcl8.3

TK8.3

OTcl

tclcl
...

tcl
ex
examples

3/29/2007

test
validation tests

mysrc
msg.tcl

NCKU

ns-2

lib

nam-1

C++ code

mcast

...

OTcl code

116

Add Your Change into ns


tcl/lib/ns-lib.tcl
Class Simulator

source ../mysrc/msg.tcl

Makefile
NS_TCL_LIB = \
tcl/mysrc/msg.tcl \

Or: change Makefile.in, make distclean, then


./configure --enable-debug ,
make depend and make
3/29/2007

NCKU

117

Writing ns-2 codes


Extending ns
In OTcl
In C++
New components

3/29/2007

NCKU

118

Extending ns in C++
Modifying code
make depend
Recompile

Adding code in new files


Change Makefile
make depend
recompile

3/29/2007

NCKU

119

Creating New Components


Guidelines
Two styles
New agent based on existing packet headers
Add new packet header

3/29/2007

NCKU

120

Guidelines
Decide position in class hierarchy
I.e., which class to derive from?

Create new packet header (if necessary)


Create C++ class, fill in methods
Define OTcl linkage (if any)
Write OTcl code (if any)
Build (and debug)
3/29/2007

NCKU

121

New Agent, Old Header


Exercise: TCP jump start
Wide-open transmission window at the
beginning
From cwnd_ += 1 To cwnd_ = MAXWIN_

3/29/2007

NCKU

122

TCP Jump Start Step 1


TclObject

Handler

NsObject
Connector
Queue

Delay Agent

DropTail RED

TCP

Reno
3/29/2007

SACK

Classifier
Trace

AddrClassifier McastClasifier

Enq Deq

Drop

JS
NCKU

123

TCP Jump Start Step 2


New file: tcp-js.h
class JSTCPAgent : public TcpAgent {
public:
virtual void set_initial_window() {
cwnd_ = MAXWIN_;
}
private:
int MAXWIN_;
};
3/29/2007

NCKU

124

TCP Jump Start Step 3


New file: tcp-js.cc
static JSTcpClass : public TclClass {
public:
JSTcpClass() : TclClass("Agent/TCP/JS") {}
TclObject* create(int, const char*const*) {
return (new JSTcpAgent());
}
};
JSTcpAgent::JSTcpAgent() {
bind(MAXWIN_, MAXWIN_);
}

3/29/2007

NCKU

125

TCP Jump Start Step 4


Create an instance of jump-start TCP in
your tcl script tcp-js.tcl
Set MAXWIN_ value in tcl
Add tcp-js.o in Makefile.in
Re-configure, make depend and recompile
Run yr tcl script tcp-js.tcl

3/29/2007

NCKU

126

Packet Format
cmn header
header
data

ip header
tcp header
rtp header
trace header

ts_
ptype_
uid_
size_
iface_

...
3/29/2007

NCKU

127

New Packet Header


Create new header structure
Create static class for OTcl linkage (packet.h)
Enable tracing support of new header(trace.cc)
Enable new header in OTcl (tcl/lib/ns-packet.tcl)
This does not apply when you add a new field
into an existing header!

3/29/2007

NCKU

128

How Packet Header Works


Packet
PacketHeader/Common

next_
hdrlen_
bits_

size determined
at simulator
startup time
(PacketHeaderManager)

hdr_cmn
size determined
at compile time PacketHeader/IP
size determined
at compile time
size determined
at compile time

hdr_ip
PacketHeader/TCP

hdr_tcp

3/29/2007

NCKU

129

Example: Agent/Message
New packet header for 64-byte message
New transport agent to process this new
header

3/29/2007

NCKU

130

New Packet Header


Step 1
Create header structure
struct hdr_msg {
char msg_[64];
static int offset_;
inline static int& offset() { return offset_; }
inline static hdr_msg* access(Packet* p) {
return (hdr_msg*) p->access(offset_);
}
/* per-field member functions */
char* msg() { return (msg_); }
int maxmsg() { return (sizeof(msg_)); }
};

3/29/2007

NCKU

131

New Packet Header


Step 2
Otcl linkage: PacketHeader/Message
static class MessageHeaderClass :
public PacketHeaderClass {
public:
MessageHeaderClass() :
PacketHeaderClass("PacketHeader/Message",
sizeof(hdr_msg)) {
bind_offset(&hdr_msg::offset_);
}
} class_msghdr;

3/29/2007

NCKU

132

New Packet Header


Step 3
Enable tracing (packet.h):
enum packet_t {
PT_TCP,
,
PT_MESSAGE,
PT_NTYPE // This MUST be the LAST one
};
class p_info {

name_[PT_MESSAGE] = message;
name_[PT_NTYPE]= "undefined";

};
3/29/2007

NCKU

133

New Packet Header


Step 4
Register new header (tcl/lib/ns-packet.tcl)
foreach prot {
{ Common off_cmn_ }

{ Message off_msg_ }
}
add-packet-header $prot

3/29/2007

NCKU

134

Packet Header: Caution


Some old code, e.g.:
RtpAgent::RtpAgent() {

bind(off_rtp_, &off_rtp);
}

hdr_rtp* rh = (hdr_rtp*)p->access(off_rtp_);

Don
tf
ol
l
ow t
hi
sex
ampl
e!

3/29/2007

NCKU

135

Agent/Message Step 1
TclObject
NsObject
Connector
Queue

Delay Agent

DropTail RED

TCP

Reno
3/29/2007

Classifier
Trace

AddrClassifier McastClasifier

Message Enq Deq

Drop

SACK
NCKU

136

Agent/Message Step 2
C++ class definition
// Standard split object declaration
static
class MessageAgent : public Agent {
public:
MessageAgent() : Agent(PT_MESSAGE) {}
virtual int command(int argc, const char*const*
argv);
virtual void recv(Packet*, Handler*);
};

3/29/2007

NCKU

137

Agent/Message Step 3
Packet processing: $msgAgent s
end
dat
a1
int MessageAgent::command(int, const char*const* argv)
{
Tcl& tcl = Tcl::instance();
if (strcmp(argv[1], "send") == 0) {
Packet* pkt = allocpkt();
hdr_msg* mh = hdr_msg::access(pkt);
// We ignore message size check...
strcpy(mh->msg(), argv[2]);
send(pkt, 0);
return (TCL_OK);
}
return (Agent::command(argc, argv));
}

3/29/2007

NCKU

138

Agent/Message Step 4
Packet processing: receive
void MessageAgent::recv(Packet* pkt, Handler*)
{
hdr_msg* mh = hdr_msg::access(pkt);
// OTcl callback
char wrk[128];
sprintf(wrk, "%s recv {%s}", name(), mh->msg());
Tcl& tcl = Tcl::instance();
tcl.eval(wrk);
Packet::free(pkt);
}

3/29/2007

NCKU

139

Writing ns-2 codes


Extending ns
In OTcl
In C++
Debugging: OTcl/C++, memory
Pitfalls

3/29/2007

NCKU

140

Debugging C++ in ns
C++/OTcl debugging
Memory debugging
purify
dmalloc

3/29/2007

NCKU

141

C++/OTcl Debugging
Usual technique
Break inside command()
Cannot examine states inside OTcl!

Solution
Execute tcl-debug inside gdb

3/29/2007

NCKU

142

C++/OTcl Debugging
(gdb) call Tcl::instance().eval(debug 1)
15: lappend auto_path $dbg_library
dbg15.3> w
*0: application
15: lappend auto_path $dbg_library
dbg15.4> Simulator info instances
_o1
dbg15.5> _o1 now
0
dbg15.6> # and other fun stuff
dbg15.7> c
(gdb) where
#0 0x102218 in write()
......
3/29/2007

NCKU

143

Memory Debugging in ns
Purify
Set PURIFY macro in ns Makefile
Usually, put -colloctor=<ld_path>

Gr
ayWat
s
on
sdmalloc library
http://www.dmalloc.com
make distclean
./configure --with-dmalloc=<dmalloc_path>
Analyze results: dmalloc_summarize
3/29/2007

NCKU

144

dmalloc: Usage
Turn on dmalloc
alias dmalloc
eval
\dmalloc C \!
*`
dmalloc -l log low

dmalloc_summarize ns < logfile


ns must be in current directory
Itemize how much memory is allocated in
each function

3/29/2007

NCKU

145

Pitfalls
Scalability vs flexibility
Or, how to write scalable simulation?

Memory conservation tips


Memory leaks

3/29/2007

NCKU

146

Scalability vs Flexibility
I
t

st
empt
i
ngt
owr
i
t
eal
l
-OTcl simulation
Benefit: quick prototyping
Cost: memory + runtime

Solution
Control the granularity of your split object by
migrating methods from OTcl to C++

3/29/2007

NCKU

147

THE Merit of OTcl


high

Program size, complexity

low

OTcl

C/C++
split objects

Smoothly adjust the granularity of scripting to


balance extensibility and performance
With complete compatibility with existing
simulation scripts
3/29/2007

NCKU

148

Object Granularity Tips


Functionality
Per-packet processing C++
Hooks, frequently changing code OTcl

Data management
Complex/large data structure C++
One-time configuration variables OTcl

3/29/2007

NCKU

149

Memory usage
Simulator
Unicast node
Multicast node
Duplex link
Packet

3/29/2007

NCKU

268KB
2KB
6KB
9KB
2KB

150

Memory Conservation Tips


Remove unused packet headers
Avoid trace-all
Use arrays for a sequence of variables
Instead of n$i,
n$i say n($i)

Avoid OTcl temporary variables


temp=A; B=temp

Use dynamic binding


delay_bind() instead of bind()
See object.{h,cc}

Use different routing strategies


Computing routing tables dominate the simulation setup time

Run on FreeBSD
use less memory for malloc()

Memory Leaks
Purify or dmalloc, but be careful about split
objects:
for {set i 0} {$i < 500} {incr i} {

set a [new RandomVariable/Constant]


}

I
tl
eaksmemor
y
,butc
an
tbedet
ec
t
ed!

Solution
Explicitly delete EVERY split object that was new-ed

3/29/2007

NCKU

152

Final Word
My extended ns dumps OTcl scripts!
Find the last 10-20 lines of the dump
I
st
heer
r
orr
el
at
edt
o
_o***cmd ?
Check your command()

Otherwise, check the otcl script pointed by


the error message

3/29/2007

NCKU

153

Questions?

3/29/2007

NCKU

154

Outline
An introduction to ns-2

What is ns-2
Fundamentals
Writing ns-2 codes
Traces support and visualization
Wireless support
Emulation
Related work

3/29/2007

NCKU

155

nsnam Interface
Color
Node manipulation
Link manipulation
Topology layout
Protocol state
Misc

3/29/2007

NCKU

156

nam Interface: Color


Color mapping
$ns
$ns
$ns

color
color
color

40
41
42

red
blue
chocolate

Color flow id association


$tcp0 set fid_ 40 ;# red packets
$tcp1 set fid_ 41 ;# blue packets

3/29/2007

NCKU

157

nam Interface: Nodes


Color
$node color red

Shape(
c
an
tbec
hangedaf
t
ersim starts)
$node shape box

;# circle, box, hexagon

Mar
k
s(
c
onc
ent
r
i
c
s
hapes

)
$ns at 1.0 $n0 add-mark m0 blue box
$ns at 2.0 $n0 delete-mark m0

Label (single string)

$ns at 1.1 $n0 label \web cache 0\


$node label-at up
$node label-color blue

3/29/2007

NCKU

158

nam Interfaces: Links


Color
$ns duplex-link-op $n0 $n1 color "green"

Label
$ns
$ns
$ns

duplex-link-op
duplex-link-op
duplex-link-op

$n0
$n1
$n1

$n1
$n2
$n2

label "abced
label-color blue
label-at down

Queue position
$ns duplex-link-op queuePos right

Dynamics (automatically handled)


$ns rtmodel Deterministic {2.0 0.9 0.1} $n0 $n1

Asymmetric links not allowed


3/29/2007

NCKU

159

nam Interface: Topology


Layout

Manual
l
ay
out
:s
pec
i
f
yev
er
y
t
hi
ng
$ns
$ns
$ns
$ns

duplex-link-op
duplex-link-op
duplex-link-op
duplex-link-op

$n(0)
$n(1)
$n(2)
$n(3)

$n(1)
$n(2)
$n(3)
$n(4)

orient
orient
orient
orient

right
right
right
60deg

If anything missing automatic


layout
3/29/2007

NCKU

160

nam Interface: Misc


Packet color
$ns color $n blue
$agent set fid_ $n

Annotation
Add textual explanation to your simulation
$ns at 3.5 "$ns trace-annotate \packet drop\"

Control playback
$ns at 0.0 "$ns set-animation-rate 0.1ms"

3/29/2007

NCKU

161

The nam user interface

3/29/2007

NCKU

162

Summary of nam
Turn on nam tracing in your Tcl script
As easy as turning on normal tracing
$ns namtrace $file

Specify color/shape/label of node/link


$ns duplex-link-op $node1 $node2 orient left

Execute nam
exec nam $filename

3/29/2007

NCKU

163

A live demo

3/29/2007

NCKU

Cmd.exe

164

namgraph
Display a graph showing when packets
are received/dropped.
Enabling namgraph
Run the namfilter script on your nam trace
file:
exec tclsh /path/to/namfilter.tcl out.nam

3/29/2007

NCKU

165

namgraph

3/29/2007

NCKU

166

The nam editor


Create simple scenarios graphically
Goodf
ort
hos
ewhodon
twantt
ol
ear
n
Tcl, but only a limited subset of ns is
currently available

3/29/2007

NCKU

167

The nam editor

3/29/2007

NCKU

168

Topology generator
Inet
GT-ITM
TIERS
BRITE

3/29/2007

NCKU

169

Inet topology generator


from University of Michigan
AS level Internet topology
Create topologies with accurate degree
distributions
Conversion of Inet output to ns-2 format
inet2ns < inet.topology > ns.topology

3/29/2007

NCKU

170

GT-ITM
Installation
Comes with ns-allinone
Requi
r
eKnut
h
scweb and SGB

Usage
itm <config_file>

Three graph models


Flat random: Waxman
n-level hierarchy
Transit-stub

3/29/2007

NCKU

171

GT-ITM: Transit-Stub
Model
transit
domains
sit link
n
a
r
t
it
s
t ra n

stub-stub link

stub
domains
3/29/2007

NCKU

172

Converters for GT-ITM


sgb2ns
Convert SGB format to ns config file
sgb2ns <SGB_file> <OTcl_file>

ts2ns:
ts2ns output lists of transit and stub nodes

sgb2hier
Convert transit-stub information into
hierarchical addresses
sgb2hierns <SGB_file> <OTcl_file>

3/29/2007

NCKU

173

Tiers topology generator


3-level hierarchy
Conversion of Tiers output to ns-2 format
an awk script tiers2ns.awk is included in
~ns-2/bin to convert the output of tiers into
ns-2 scripts.

3/29/2007

NCKU

174

BRITE
From Boston University
Supports multiple generation models
flat AS
flat Router
hierarchical topologies

Object-oriented design to allow the flexibility to


add new topology models
Can import from Inet, GT-ITM, Skitter,..
Can export to ns-2, JavaSim, SSFNET format
Written in Java and C++
GUI support
3/29/2007

NCKU

175

Summary
http://www.isi.edu/nsnam/ns/ns-topogen.html
Packages

Graphs

Edge Method

NTG

n-level

probabilistic

RTG

Flat random
Flat random, nlevel, Transit-stub

Waxman

3-level

spanning tree

GT-ITM
TIERS
3/29/2007

NCKU

various

176

A case study: class webtraf

3/29/2007

NCKU

177

Outline
An introduction to ns-2

What is ns-2
Fundamentals
Writing ns-2 codes
Traces support and visualization
Wireless support
Emulation
Related work

3/29/2007

NCKU

178

Wireless support in ns-2


Introduction
Wireless basics
Wireless internals

Ad hoc routing
Mobile IP
Satellite networking
Directed diffusion
3/29/2007

NCKU

179

Contributions to wireless
in ns
Original wireless model in ns contributed
byCMU
sMonar
c
hgr
oup
Other major contributions from UCB, Sun
microsystems, univ of cincinnati, ISI etc
Other contributed models (not integrated)
in wireless ns includes Blueware, BlueHoc,
Mobiwan, GPRS, CIMS etc
3/29/2007

NCKU

180

Wireless model
Mobilenode at core of mobility model
Mobilenodes can move in a given topology,
receive/transmit signals from/to wireless
channels
Wireless network stack consists of LL, ARP,
MAC, IFQ etc
Allows simulations of multi-hop ad hoc
networks, wireless LANs, sensor networks etc
3/29/2007

NCKU

181

Wireless Example
for ad hoc routing
Scenario
3 mobile nodes
moving within 670mX670m flat topology
using DSDV ad hoc routing protocol
Random Waypoint mobility model
TCP and CBR traffic

ns-2/tcl/ex/wireless-demo-csci694.tcl
3/29/2007

NCKU

182

An Example Step 1
# Define Global Variables
# create simulator
set ns [new Simulator]
# create a flat topology in a 670m x 670m
area
set topo [new Topography]
$topo load_flatgrid 670 670

3/29/2007

NCKU

183

An Example Step 2
# Define standard ns/nam trace
# ns trace
set tracefd

[open demo.tr w]

$ns trace-all $tracefd


# nam trace
set namtrace [open demo.nam w]
$ns namtrace-all-wireless $namtrace 670 670

3/29/2007

NCKU

184

GOD

(General Operations Director)


An omniscient observer
Stores smallest number of hops from one
node to another
Optimal case to compare routing protocol
performance
Automatically generated by scenario file
set god [create-god <no of mnodes>]
$god set-dist <from> <to> <#hops>
3/29/2007

NCKU

185

Example Step 3
Create God
set god [create-god 3]
$nsat900.
00
$gods
et
-di
s
t231

3/29/2007

NCKU

186

An Example Step 4
# Define how a mobile node is configured
$ns node-config \
-adhocRouting DSDV \
-llType LL \
-macType Mac/802_11 \
-ifqLen 50 \
-ifqType Queue/DropTail/PriQueue \
-antType Antenna/OmniAntenna \
-propType Propagation/TwoRayGround \
-phyType Phy/WirelessPhy \
-channelType Channel/WirelessChannel \
-topoInstance $topo
-agentTrace ON \
-routerTrace OFF \
-macTrace OFF
3/29/2007

NCKU

187

An Example Step 5
# Next create a mobile node, attach it to the
channel

set node(0) [$ns node]


# disable random motion

$node(0) random-motion 0
# Use for loop to create 3 nodes:

for {set i < 0} {$i < 3} {incr i} {


set node($i) [$ns node]
$node($i) random-motion 0
}
3/29/2007

NCKU

188

Mobilenode Movement
Node position defined in a 3-D model
However z axis not used
$node set X_ <x1>
$node set Y_ <y1>
$node set Z_ <z1>
$node at $time setdest <x2> <y2>
<speed>

Node movement may be logged


3/29/2007

NCKU

189

Scenario Generator:
Movement
Mobile Movement Generator
setdest -n <num_of_nodes> -p pausetime -s
<maxspeed> -t <simtime> -x <maxx> -y
<maxy>
Source: ns-2/indep-utils/cmu-scengen/setdest/

Random movement
$node random-motion 1
$node start
3/29/2007

NCKU

190

A Movement File
$node_(2) set Z_ 0.000000000000
$node_(2) set Y_ 199.373306816804
$node_(2) set X_ 591.256560093833
$node_(1) set Z_ 0.000000000000
$node_(1) set Y_ 345.357731779204
$node_(1) set X_ 257.046298323157
$node_(0) set Z_ 0.000000000000
$node_(0) set Y_ 239.438009831261
$node_(0) set X_ 83.364418416244
$ns_ at 50.000000000000 "$node_(2) setdest 369.463244915743
170.519203111152 3.371785899154"
$ns_ at 51.000000000000 "$node_(1) setdest 221.826585497093
80.855495003839 14.909259208114"
$ns_ at 33.000000000000 "$node_(0) setdest 89.663708107313
283.494644426442 19.153832288917"
3/29/2007

NCKU

191

Scenario Generator: Traffic


Generating traffic pattern files
CBR/TCP traffic
ns cbrgen.tcl [-type cbr|tcp] [-nn nodes] [-seed
seed] [-mc connections] [-rate rate]
CBR traffic
ns cbrgen.tcl type cbr nn 20 seed 1 mc 8 rate 4
TCP traffic
ns cbrgen.tcl type tcp -nn 15 -seed 0 mc 6

Source: ns-2/indep-utils/cmu-scen-gen/

3/29/2007

NCKU

192

A Traffic Scenario
set udp_(0) [new Agent/UDP]
$ns_ attach-agent $node_(0) $udp_(0)
set null_(0) [new Agent/Null]
$ns_ attach-agent $node_(2) $null_(0)
set cbr_(0) [new Application/Traffic/CBR]
$cbr_(0) set packetSize_ 512
$cbr_(0) set interval_ 4.0
$cbr_(0) set random_ 1
$cbr_(0) set maxpkts_ 10000
$cbr_(0) attach-agent $udp_(0)
$ns_ connect $udp_(0) $null_(0)
$ns_ at 127.93667922166023 "$cbr_(0) start"
.

3/29/2007

NCKU

193

An Example Step 6
# Define node movement model
source <movement-scenario-files>
# Define traffic model
source <traffic-scenario-files>

3/29/2007

NCKU

194

An Example Step 7
# Define node initial position in nam
for {set i 0} {$i < 3 } { incr i} {
$ns initial_node_position $node($i) 20
}
# Tell ns/nam the simulation stop time
$ns at 200.0 $ns nam-end-wireless 200.0
$ns at 200.0 $ns halt
# Start your simulation
$ns run
3/29/2007

NCKU

195

Energy Extension
Node is energy-aware
Define node by adding new options:
$ns_ node-config \
energyModel EnergyModel
-initialEnergy
100.0
-txPower
0.6
-rxPower
0.2

3/29/2007

NCKU

196

nam Visualization
Use nam to visualize:
Mobile node position
Mobile node moving direction and speed
Energy consumption at nodes (color keyed)

3/29/2007

NCKU

197

nam Visualization
Replace
$ns namtrace-all $fd

with
$ns namtrace-all-wireless $fd

At the end of simulation, do


$ns nam-end-wireless [$ns now]
3/29/2007

NCKU

198

Wireless support in ns-2


Introduction
Wireless basics
Wireless internals

Ad hoc routing
Mobile IP
Satellite networking
Directed diffusion
3/29/2007

NCKU

199

Wireless Internals
Mobilenode
Basic node that has address and port demuxes, routing agent etc
Stack of network components consisting of
LL, MAC, NetIF radio-model etc

Wireless channel

3/29/2007

NCKU

200

Portrait of A Mobile Node


Node

port
classifier

protocol
agent

Classifier: Forwarding

255
addr
classifier defaulttarget_

LL

Agent: Protocol Entity

routing
agent

Node Entry

ARP

LL

IFQ
IFQ

IFQ: Interface queue

MAC

MAC: Mac object

PHY

PHY: Net interface

MAC
PHY

MobileNode

Propagation
and antenna
models

CHANNEL

3/29/2007

Prop/ant

NCKU

LL: Link layer object

Radio propagation/
antenna models
201

Mobile Node : Components


Classifiers
defaulttarget_ points to routing agent object
255 is the port id assigned for rtagent_

Routing agent
May be ad hoc routing protocol like AODV,
DSDV or directed diffusion

3/29/2007

NCKU

202

Mobile Node: Components


Link Layer
Same as LAN, but with a separate ARP module
Sends queries to ARP

ARP
Resolves IP address to hardware (MAC) address
Broadcasts ARP query

Interface queue
Gives priority to routing protocol packets
Has packet filtering capacity
3/29/2007

NCKU

203

Mobile Node: Components


MAC
802.11
IEEE RTS/CTS/DATA/ACK for unicast
Sends DATA directly for broadcast

SMAC (for sensor network)

Network interface (PHY)


Used by mobilenode to access channel
Stamps outgoing pkts with meta-data
Interface with radio/antenna models
3/29/2007

NCKU

204

Mobile Node: Components


Radio Propagation Model

Friss-space model attenuation at near


distance (1/r2)
Two-ray ground reflection model for far
distance (1/r4)
Shadowing model -probabilistic

Antenna

Omni-directional, unity-gain

3/29/2007

NCKU

205

Wireless Channel
Duplicate packets to all mobile nodes
attached to the channel except the sender
I
ti
st
her
ec
ei
v
er

sr
es
pons
i
bi
l
i
t
yt
odec
i
de
if it will accept the packet
Collision is handled at individual receiver
O(N2) messages grid keeper, referencecopying etc

3/29/2007

NCKU

206

Grid-keeper: An
Optimization

3/29/2007

NCKU

207

Mobile Node: Misc.


Energy consumption model for sensor
networks
Visualization of node movement,
reachability, and energy
Validation test suites

3/29/2007

NCKU

208

Wireless Trace Support


Original cmu trace format
A separate wireless trace format
developed later at ISI
Current ongoing effort to have ONE
format to combine all wired and wireless
formats

3/29/2007

NCKU

209

Ad Hoc Routing
Four routing protocols currently supported:
DSDV

Contributed by CMU

DSR

Contributed by CMU

AODV

Recently updated version from univ. of cincinnati;

TORA

Contributed by CMU
Examples under tcl/test/test-suitewireless- { lan-newnode.tcl, lan-aodv.tcl,
lan-tora.tcl }
3/29/2007

NCKU

210

A Brief on MobileIP Support


Developed by Sun
Require a different Node structure than MobileNode
Originally implemented for wired nodes

Wired-cmu-wireless extension
Originally CMU wireless model only supports ad-hoc
and wireless LAN
Base-stations, support hier-rtg

Standard MobileIP
Home Agent, Foreign Agent, MobileHosts

Example
Under tcl/test/test-suite-wireless-lannewnode.tcl (tests: DSDV-wired-cum-wireless and
DSDV-wireless-mip)

A Brief on Satellite
Networking
Developed by Tom Henderson (UCB)
Supported models
Geostationary satellites: bent-pipe and
processing-payload
Low-Earth-Orbit satellites

Example: tcl/ex/sat-*.tcl and


tcl/test/test-suite-satellite.tcl

3/29/2007

NCKU

212

Simulate sensor network


with ns-2
Currently support
Routing
Direct diffusion

MAC
SMAC

3/29/2007

NCKU

213

Sensor network
Wireless sensor network
Special ad hoc wireless network
Large number of nodes w/ sensors & actuators
Battery-powered nodes
energy efficiency
Unplanned deployment
self-organization
Node density & topology change
robustness

Sensor-net applications
Nodes cooperate for a common task
In-network data processing
3/29/2007

NCKU

214

Introduction to Direct
Diffusion
Properties of Sensor Networks
Data centric, but not node centric
Have no notion of central authority
Are often resource constrained

Nodes are tied to physical locations, but:


They may not know the topology
They may fail or move arbitrarily

Problem: How can we get data from the


sensors?
3/29/2007

NCKU

215

Basic idea of Directed


Diffusion
Data centric nodes are unimportant
Request driven:
Sinks place requests as interests
Sources are eventually found and satisfy interests
Intermediate nodes route data toward sinks

Localized repair and reinforcement


Multi-path delivery for multiple sources, sinks,
and queries
3/29/2007

NCKU

216

A toy example
Sensor nodes are monitoring a flat space
for animals
We are interested in receiving data for all
4-legged creatures seen in a rectangle
area
We want to specify the data rate

3/29/2007

NCKU

217

Interest and Event Naming


Sink: Query/interest:

Type=four-legged animal
Interval=20ms (event data rate)
Duration=10 seconds (time to cache)
Rect=[-100, 100, 200, 400]

Source: Reply:

Type=four-legged animal
Instance = elephant
Location = [125, 220]
Confidence = 0.85
Timestamp = 01:20:40

Attribute-Value pairs, no advanced naming


scheme

3/29/2007

NCKU

218

Diffusion (High Level)


Sinks broadcast interest to neighbors
Interests are cached by neighbors
Gradients are set up pointing back to
where interests came from at low data
rate
Once a source receives an interest, it
routes measurements along gradients
3/29/2007

NCKU

219

Gradients
Gradients from Source (S) to Sink (N) are
initially small
Increased during reinforcement to find the
best path
How gradients are increased/decreased
based on only local rules
Application-specfic
3/29/2007

NCKU

220

Interest Propagation
Flooding
Constrained or Directional flooding based on location.
Directional Propagation based on previously cached data.
Gradient

Source

Interest

Sink
3/29/2007

NCKU

221

Directed Diffusion (Data)


The source matches signature waveforms from
codebook against observations
The source matches data against interest cache,
compute highest event rate request from all gradients,
and (re) sample events at this rate
Intermediate node:
Finds matching entry in interest cache, no match silent drop
Checks and updates data cache (loop prevention, aggregation)
Retrieve all gradients, and resend message, doing frequency
conversion if necessary

3/29/2007

NCKU

222

Data Propagation
Reinforcement to single path delivery.
Multipath delivery with probabilistic forwarding.
Multipath delivery with selective quality along different path.
Gradient

Source

Data

Sink
3/29/2007

NCKU

223

Directed Diffusion
(Reinforcement)
Reinforcement:
Sink/intermediate nodes pick a neighbor based on
some local rules and increase the gradient (e.g.
higher event rates)
This neighbor, in turn, reinforces upstream nodes
Passive reinforcement handling (timeout) or active
(weights)
Multiple sinks: Exploit prior setup (i.e., use cache)
Intermediate nodes use reinforcement for local repair

3/29/2007

NCKU

224

Local rules
Reinforce one of the neighbor after receiving initial data.

Which neighbor ?
Neighbor(s) from whom new events received.
Neighbor who
s consistently performing better than others.
Neighbor from whom most events received.
Gradient

Source

Data
Reinforcement

3/29/2007

NCKU

Sink

225

Negative Reinforcement
Time out
Explicitly Degrade the path by re-sending interest with lower data
rate.

Gradient

Source

Data
Reinforcement

3/29/2007

NCKU

Sink

226

A Brief on Directed
Diffusion
Developed by SCADDS group at USC/ISI
Diffusion model in ns consists of
A core diffusion layer
A library of APIs for diffusion applications
Add-on filters (for gradient routing, logging, tagging,
srcrtg, GEAR etc)

Much in development
Source code in ~ns/diffusion3
Examples under tcl/ex/diffusion3 and test/testsuite-diffusion3.tcl

3/29/2007

NCKU

227

Medium Access Control in


Sensor Nets
Important attributes of MAC protocols

3/29/2007

Collision avoidance
Energy efficiency
Scalability in node density
Latency
Fairness
Throughput
Bandwidth utilization
NCKU

Primary

Secondary

228

Energy Efficiency in MAC


Major sources of energy waste
Idle listening
Energy consumption of typical 802.11 WLAN cards
idle:receive 1:1.05 to 1:2 (Stemm 1997)

3/29/2007

NCKU

229

Energy Efficiency in MAC


Major sources of energy waste (cont.)
Idle listening

Dominant in sensor nets

Long idle time when no sensing event happens

Collisions
Control overhead
Overhearing

Common to all
wireless networks

We try to reduce energy consumption from


all above sources
Combine benefits of TDMA + contention
protocols
3/29/2007

NCKU

230

Sensor-MAC (S-MAC)
Design
Tradeoffs
Latency
Fairness

Energy

Major components in S-MAC


Periodic listen and sleep
Collision avoidance
Overhearing avoidance
Massage passing
3/29/2007

NCKU

231

Periodic Listen and Sleep


Problem: Idle listening consumes significant
energy
Solution: Periodic listen and sleep
listen

sleep

listen

sleep

Turn off radio when sleeping


Reduce duty cycle to ~ 10% (200ms on/2s off)

Latency
3/29/2007

Energy
NCKU

232

Periodic Listen and Sleep


Schedules can differ
Node 1
Node 2

listen

sleep

listen
sleep

listen

sleep
listen

sleep

Prefer neighboring nodes have same schedule


easy broadcast & low control overhead
Schedule 1
Schedule 2

3/29/2007

NCKU

Border nodes:
two schedules
broadcast twice
233

Periodic Listen and Sleep


Schedule Synchronization
Remembernei
ghbor
s
s
c
hedul
es

to know when to send to them

Each node broadcasts its schedule every few


periods of sleeping and listening
Re-sync when receiving a schedule update
Schedule packets also serve as beacons for
new nodes to join a neighborhood
3/29/2007

NCKU

234

Collision Avoidance
Problem: Multiple senders want to talk
Options: Contention vs. TDMA
Solution: Similar to IEEE 802.11 ad hoc
mode (DCF)
Physical and virtual carrier sense
Randomized backoff time
RTS/CTS for hidden terminal problem
RTS/CTS/DATA/ACK sequence
3/29/2007

NCKU

235

Overhearing Avoidance
Problem: Receive packets destined to
others
Solution: Sleep when neighbors talk
use in-channel signaling

Who should sleep?


All immediate neighbors of sender and receiver

How long to sleep?


The duration field in each packet informs other
nodes the sleep interval
3/29/2007

NCKU

236

Message Passing
Problem: Sensor net in-network processing

requires entire message


Solution: Don
ti
nt
er
l
eav
edi
f
f
er
entmes
s
ages
Long message is fragmented & sent in burst
RTS/CTS reserve medium for entire message
Fragment-level error recovery ACK
extend Tx time and re-transmit
immediately

Other nodes sleep for whole message time


Energy
Msg-level latency

Fairness
3/29/2007

NCKU

237

Msg Passing vs. 802.11


fragmentation

S-MAC message passing


Data 19

RTS 21

ACK 18

CTS 20

...

Data 17

ACK 16

Data 1

...

ACK 0

Fragmentation in IEEE 802.11


No indication of entire time other nodes keep listening
If ACK is not received, give up Tx fairness
Data 3

RTS 3
CTS 2
3/29/2007

Data 3
ACK 2

...
ACK 2

NCKU

Data 1

...

ACK 0
238

A brief on SMAC
SMAC MAC designed for sensor
networks
Similar RTS/CTS/DATA/ACK like 802.11
Additional sleep-wakeup cycles
Reduce energy consumptions during idle
phases
Examples under tcl/test/test-suitesmac.tcl

3/29/2007

NCKU

239

Outline
An introduction to ns-2

What is ns-2
Fundamentals
Writing ns-2 codes
Traces support and visualization
Wireless support
Emulation
Related work

3/29/2007

NCKU

240

What is Emulation ?
Ability to introduce the simulator into a
live network
Application:
Allows testing real-world implementations
Allows testing simulated protocols

Requirements:
Scheduler support
Packet capture and generation capabilities
3/29/2007

NCKU

241

Emulation in ns-2

ns
Read packets

Write packets

Network

3/29/2007

NCKU

242

Scheduler
ns operates in virtual time using eventdriven simulation
Real-time scheduler
Does not advance the virtual clock to next
event
Dispatches event at real-time

3/29/2007

NCKU

243

Emulation Objects
Interface between ns
and network traffic
Network Objects
Access to live network via
BPF and raw sockets

Capture: BPF
network to ns

ns

Tap Objects
Conversion between ns
and
network packet formats
3/29/2007

NCKU

ns to network
Inject: Raw socket

244

Modes of Operation
Packet conversion leads to two modes of
operation
Opaque Mode
Network packet fields are not interpreted

Protocol Mode
Network packet is interpreted
TTL values reflect hop count in simulator

Network packet fields are generated


Ping responder, TCP application
3/29/2007

NCKU

245

Opaque Mode
Network packet is passed unmodified
through simulator
Extern
Source
Destination
Size

Source
Destination
Size

Ns packet contains
a pointer to the
network packet
Data

ns
Read packets

Network Packet

3/29/2007

Write packets

Network
NCKU

246

Protocol Mode
Network packet fields are generated by
the simulator
Source
Destination
Size
The ns packet
header is
mapped onto the
network packet
header and visa
versa .

Source
Destination
Size

Host A

Host B

TCP Agent

TCP
Application

Data

Network Packet

ns
Send/receive
packets from
application

Send/receive
packets from
ns

Network
3/29/2007

NCKU

247

Applications
Opaque Mode
Cross-traffic interaction leading to drop, delay
and re-ordering of packets
End to End application testing

Protocol Mode
Protocol and conformance testing
Evaluate effect of DDoS attacks
Wireless networks
3/29/2007

NCKU

248

Example: Setup
Goal: Make a ns TCP agent interact with a TCP server
B 192.168.1.2 port 8000
A 192.168.1.1

nse

Disable IP forwarding

sysctl w
net.inet.ip.forwarding=0

Assign 10.0.0.1 and 6000


to TCP agent

3/29/2007

TCP server

Switch

NCKU

Add route to dummy IP


address
route add 10.0.0.1 192.168.1.1

Disable IP redirects
sysctl w net.inet.ip.redirect=0

249

Example Script
Activate ns and
Change to real-time
scheduler

set ns [new Simulator]


$ns use-scheduler RealTime
set entry_node [$ns node]
set tcp_node [$ns node]

Create topology
$ns duplex-link $entry_node
$tcp_node 10Mb 1ms DropTail

set tcp [new Agent/TCP/FullTcp]


$ns attach-agent $tcp_node $tcp

Create TCP Agent


TCPTap

TCP Agent
tcp_node

entry_node
TCPTap

3/29/2007

BPF

NCKU

RawSocket
250

Example Script
set bpf [new Network/Pcap/Live]
TCP Agent
set dev [$bpf open readonly eth0]
$bpf filter "src 192.168.1.2 and src port 8000 \ tcp_node
and dst 10.0.0.1 and dst port 6000
set capture_tap [new Agent/TCPTap]
$capture_tap network $bpf
$ns attach-agent $entry_node $capture_tap
$ns simplex-connect $capture_tap $tcp
set rawsocket [new Network/IP]
$rawsocket open writeonly
set inject_tap [new Agent/TCPTap]
$inject_tap advertised-window 512
$inject_tap extipaddr 192.168.1.2"
$inject_tap extport 8000
$inject_tap network $rawsocket
$ns attach-agent $entry_node $inject_tap
$ns simplex-connect $tcp $inject_tap
3/29/2007

NCKU

CaptureTap
InjectTap
entry_node
BPF

RawSocket
251

Example Script
$ns at 0.01 "$tcp advance 1"
$ns at 20.0 exit 0"
$ns run

A 192.168.1.1

start nse

B 192.168.1.2

TCP Agent

TCP Server
(8000)
BPF

Raw Socket

Switch
3/29/2007

NCKU

252

Further Information
http://www.isi.edu/nsnam/ns/ns-emulation.html

Scripts ~ns/emulate
Opaque Mode:
em.tcl

Protocol Mode
thrutcp.tcl
pingdemo.tcl
tcpemu.tcl

Kevin Fall, Network Emulation in the Vint/NS Simulator,


ISCC July 1999
3/29/2007

NCKU

253

Ns-2 related work


Other simulators
Researching uses ns-2
Using ns-2 for education

3/29/2007

NCKU

254

Other simulators
GloMoSim

Developed by UCLA
Based on Parsec
Good support for wireless simulation

SSFNET

Java-based (with some C++ components)


Use DML (Domain Modeling Language) for model configuration

OPNET and QualNet

Commercial software
Good support for all layers

PDNS (parallel/distributed ns)

Developed by Georgia Tech


Can distribute a simulation on several 8-16 workstations
Aim to support very large simulation (memory & CPU)

JavaSim

Another Java-based simulator

3/29/2007

NCKU

255

Research using ns-2


Routing
MIT Click Router
Zone routing protocol

Wireless
Mobility generator
MIPv6
Bluetooth
802.11 PSM
Cellular IP
Hierarchical Mobile IP
GPRS
UMTS
3/29/2007

NCKU

256

Research using ns-2..


Generator
Web traffic generators
MPEG
Several topology generators

Others
MPLS
WFQ, CSFQ
RSVP
RIO
BLUE
TCP westwood
SCTP
Multistate error model
3/29/2007

NCKU

257

Using ns-2 for education


Ns-2 scripts/nam traces repository
http://www.isi.edu/nsnam/repository/index.
html

~ns-2/tcl/ex
~nam/ex ~nam/edu
Some ns scripts and nam animations
can be used in widely-used textbooks
http://www.isi.edu/nsnam/ns/edu/index.html

3/29/2007

NCKU

258

S-ar putea să vă placă și