You are on page 1of 239

Outline

• An introduction to ns-2
• What is ns-2
• Fundamentals
• Writing ns-2 codes
• Wireless support
• Traces support and visualization
• Emulation
• Related work
What is ns-2
• History
• What does it support
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
Multiple levels of detail in
simulations
Consider two nodes simple t=1, A enqueues pkt on LAN
on an Ethernet: queuing t=1.01, LAN dequeues pkt
model: and triggers B

A 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
Alternatives
• Experimentation • Operational details,
• Private lab but
• Public testbed (e.g. • Limited scale
Planetlab) • Expensive, limited
• Shared labs (e.g. flexibility
Utah Emulab) • Higher overhead
• Analysis • Can provide
• Other simulator understanding, but
• Custom simulators • Limited details
• Other general • Important niches
simulators
• Limited re-use
History of ns-2
• History
• Cornell REAL simulator -1989
• VINT project (UCB, Xerox ,USC/ISI) – 1995
• USC/ISI SAMAN/CONSER project – 1999
• Ns-3 project now led by Tom Henderson
• Size
• ~220K lines of codes
• 45% C++
• 31% OTcl
• 23% test suite/example/documents
• ~400 pages of manual
• 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
ns-2 support
• Platform
• FreeBSD, Linux, Solaris, Windows and Mac
• Release
• Periodical release: ~6 months
• current release: ns-2.31, Mar 10, 2007
• Daily snapshot
• Now has moved to sourceforge
• Validation
• 100+ test suites and 100+ examples
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
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
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
“Ns” Components
• Ns, the simulator itself
• Nam, the network animator
• Visualize ns (or other) output
• Nam editor: GUI interface to generate ns scripts
• NSE, the network emulator
• Pre-processing:
• Traffic and topology generators
• Post-processing:
• Simple trace analysis, often in Awk, Perl, or Tcl
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, …
Getting Help
• ns-2 build questions
• http://www.isi.edu/nsnam/ns/ns-build.html
• ns-users@isi.edu
• ns-users-request@isi.edu
• “subscribe ns-users” in body
• Archive: http://www.isi.edu/nsnam/ns
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
Cautions
• Abstraction of the real world is necessary
for a simulator
• You must justify the usage of the simulator
based on your research goals
• What level of details do you need?
• What are your models?
Question?
Outline
• An introduction to ns-2
• What is ns-2
• Fundamentals
• Writing ns-2 codes
• Wireless support
• Traces support and visualization
• Emulation
• Related work
Prerequisite

• Some programming experience of


object-oriented language (such as C++,
Java)
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
Discrete Event Examples

Consider two nodes simple t=1, A enqueues pkt on LAN


on an Ethernet: queuing t=1.01, LAN dequeues pkt
model: and triggers B

A 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
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 Network
Components
• Reusability TclCL

Scheduler
Event
• Maintenance OTcl
• Performance (speed and memory) Tcl
• Careful planning of modularity C++
ns-2
C++ and OTcl Separation

• “data” / “control” separation


• C++ for “data”:
• 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)
Control vs. Data

• Create topology • Details of links and


nodes
• Setup routing
• Details of a routing
• Create transport protocol
connection • Details of TCP
• Create traffic implementation
• Details of a packet

OTcl C++
Creating a link
Octl codes [ns_ duplex-link $n0 $n1 5Mb 2ms drop-tail]

n0 n1

duplex link

Details in C++
n1
head_ entry_
enqT_ queue_ deqT_ link_ ttl_

drophead_ drpT_
tracing simplex link
24
Otcl and C++: The Duality
C++

user
C++/OTcl
simulation split objects
scripts
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
Basic Tcl
variables: procedures:
set x 10
proc pow {x n} {
puts “x is $x”
if {$n == 1} { return $x }
functions and expressions: set part [pow x [expr $n-1]]
set y [pow x 2] return [expr $x*$part]
set y [expr x*x] }

control flow: Also lists, associative arrays,


if {$x > 0} { return $x } else { etc.
return [expr -$x] } => can use a real
while { $x > 0 } { programming language to
puts $x build network topologies,
incr x –1 traffic models, etc.
}
Compare Otcl to C++
• Object oriented extension of Tcl
• C++ constructor/destructor => OTcl
init/destroy method
• C++ this => OTcl $self
• OTcl methods always “virtual”
• C++ static variable => OTcl class
variable
• Multiple inheritance is supported
Basic otcl
Class Person # subclass:
# constructor: Class Kid -superclass Person
Person instproc init {age} { Kid instproc greet {} {
$self instvar age_ $self instvar age_
set age_ $age puts “$age_ years old kid:
} What’s up, dude?”
# method: }
Person instproc greet {} {
$self instvar age_ set a [new Person 45]
puts “$age_ years old: How set b [new Kid 15]
are you doing?” $a greet
} $b greet

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


Octl tutorial
ftp://ftp.tns.lcs.mit.edu/pub/otcl/doc/tutorial.ht
ml
Using ns

Problem

Result Simulation Modify


analysis model ns

Setup/run
simulation
with ns
Hello World - Interactive Mode
Interactive mode: Batch mode:
swallow 71% ns simple.tcl
% set ns [new Simulator] set ns [new Simulator]
_o3 $ns at 1 “puts \“Hello
% $ns at 1 “puts \“Hello World!\””
World!\”” $ns at 1.5 “exit”
1 $ns run
% $ns at 1.5 “exit”
swallow 74% ns simple.tcl
2
Hello World!
% $ns run
swallow 75%
Hello World!
swallow 72%
Let’s learn ns-2 by some
examples first
• #Create a simulator object
• set ns [new Simulator]

• #Open the nam trace file


• set nf [open out.nam w]
• $ns namtrace-all $nf

• #Define a 'finish' procedure


• proc finish {} {
• global ns nf
• $ns flush-trace
• #Close the trace file
• close $nf
• #Execute nam on the trace file
• exec nam out.nam &
• exit 0
• }

• #Create two nodes


• set n0 [$ns node]
• set n1 [$ns node]

• #Create a duplex link between the nodes


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

• #Create a UDP agent and attach it to node n0


• set udp0 [new Agent/UDP]
• $ns attach-agent $n0 $udp0
• # Create a CBR traffic source and attach it to udp0
• set cbr0 [new Application/Traffic/CBR]
• $cbr0 set packetSize_ 500
• $cbr0 set interval_ 0.005
• $cbr0 attach-agent $udp0

• #Create a Null agent (a traffic sink) and attach it to node n1


• set null0 [new Agent/Null]
• $ns attach-agent $n1 $null0

• #Connect the traffic source with the traffic sink


• $ns connect $udp0 $null0

• #Schedule events for the CBR agent


• $ns at 0.5 "$cbr0 start"
• $ns at 4.5 "$cbr0 stop"
• #Call the finish procedure after 5 seconds of simulation time
• $ns at 5.0 "finish"

• #Run the simulation


• $ns run
• #Create a simulator object
• set ns [new Simulator]

• #Define different colors for data flows


• $ns color 1 Blue
• $ns color 2 Red

• #Open the nam trace file


• set nf [open out.nam w]
• $ns namtrace-all $nf

• #Define a 'finish' procedure


• proc finish {} {
• global ns nf
• $ns flush-trace
• #Close the trace file
• close $nf
• #Execute nam on the trace file
• exec nam out.nam &
• exit 0
• }

• #Create four nodes


• set n0 [$ns node]
• set n1 [$ns node]
• set n2 [$ns node]
• set n3 [$ns node]
• #Create links between the nodes
• $ns duplex-link $n0 $n2 1Mb 10ms DropTail
• $ns duplex-link $n1 $n2 1Mb 10ms DropTail
• $ns duplex-link $n3 $n2 1Mb 10ms SFQ

• $ns duplex-link-op $n0 $n2 orient right-down


• $ns duplex-link-op $n1 $n2 orient right-up
• $ns duplex-link-op $n2 $n3 orient right

• #Monitor the queue for the link between node 2 and node 3
• $ns duplex-link-op $n2 $n3 queuePos 0.5

• #Create a UDP agent and attach it to node n0


• set udp0 [new Agent/UDP]
• $udp0 set class_ 1
• $ns attach-agent $n0 $udp0

• # Create a CBR traffic source and attach it to udp0


• set cbr0 [new Application/Traffic/CBR]
• $cbr0 set packetSize_ 500
• $cbr0 set interval_ 0.005
• $cbr0 attach-agent $udp0

• #Create a UDP agent and attach it to node n1


• set udp1 [new Agent/UDP]
• $udp1 set class_ 2
• $ns attach-agent $n1 $udp1
• # Create a CBR traffic source and attach it to udp1
• set cbr1 [new Application/Traffic/CBR]
• $cbr1 set packetSize_ 500
• $cbr1 set interval_ 0.005
• $cbr1 attach-agent $udp1

• #Create a Null agent (a traffic sink) and attach it to node n3


• set null0 [new Agent/Null]
• $ns attach-agent $n3 $null0

• #Connect the traffic sources with the traffic sink


• $ns connect $udp0 $null0
• $ns connect $udp1 $null0

• #Schedule events for the CBR agents


• $ns at 0.5 "$cbr0 start"
• $ns at 1.0 "$cbr1 start"
• $ns at 4.0 "$cbr1 stop"
• $ns at 4.5 "$cbr0 stop"
• #Call the finish procedure after 5 seconds of simulation time
• $ns at 5.0 "finish"

• #Run the simulation


• $ns run
• #Create a simulator object
• set ns [new Simulator]

• #Tell the simulator to use dynamic routing


• $ns rtproto DV

• #Open the nam trace file


• set nf [open out.nam w]
• $ns namtrace-all $nf

• #Define a 'finish' procedure


• proc finish {} {
• global ns nf
• $ns flush-trace
• #Close the trace file
• close $nf
• #Execute nam on the trace file
• exec nam out.nam &
• exit 0
• }

• #Create seven nodes


• for {set i 0} {$i < 7} {incr i} {
• set n($i) [$ns node]
• }

• #Create links between the nodes


• for {set i 0} {$i < 7} {incr i} {
• $ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms DropTail
• }
• #Create a UDP agent and attach it to node n(0)
• set udp0 [new Agent/UDP]
• $ns attach-agent $n(0) $udp0

• # Create a CBR traffic source and attach it to udp0


• set cbr0 [new Application/Traffic/CBR]
• $cbr0 set packetSize_ 500
• $cbr0 set interval_ 0.005
• $cbr0 attach-agent $udp0

• #Create a Null agent (a traffic sink) and attach it to node n(3)


• set null0 [new Agent/Null]
• $ns attach-agent $n(3) $null0

• #Connect the traffic source with the traffic sink


• $ns connect $udp0 $null0

• #Schedule events for the CBR agent and the network dynamics
• $ns at 0.5 "$cbr0 start"
• $ns rtmodel-at 1.0 down $n(1) $n(2)
• $ns rtmodel-at 2.0 up $n(1) $n(2)
• $ns at 4.5 "$cbr0 stop"
• #Call the finish procedure after 5 seconds of simulation time
• $ns at 5.0 "finish"

• #Run the simulation


• $ns run
OK, now what if I want to
create a new protocol?
Ping protocol
• One node will be able to send a packet to
another node which will return it
immediately, so that the round-trip-time
can be calculated
Header file
• struct hdr_ping {
char ret;
double send_time;
};

• class PingAgent : public Agent {


public: PingAgent();
int command(int argc, const char*const* argv);
void recv(Packet*, Handler*);
protected: int off_ping_;
};
C++ codes
• #include "ping.h"

• static class PingHeaderClass : public PacketHeaderClass {


• public:
• PingHeaderClass() : PacketHeaderClass("PacketHeader/Ping",
• sizeof(hdr_ping)) {}
• } class_pinghdr;

• static class PingClass : public TclClass {


• public:
• PingClass() : TclClass("Agent/Ping") {}
• TclObject* create(int, const char*const*) {
• return (new PingAgent());
• }
• } class_ping;
• PingAgent::PingAgent() : Agent(PT_PING)
{
bind("packetSize_", &size_);
bind("off_ping_", &off_ping_);
}
C++

C++/OTcl
split objects

otcl
ns
Otcl and C++: The Duality

C++

user
C++/OTcl
simulation split objects
scripts
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
• int PingAgent::command(int argc, const char*const* argv)
{
if (argc == 2) {
if (strcmp(argv[1], "send") == 0) {
// Create a new packet
Packet* pkt = allocpkt(); // Access the Ping header for the new packet:
hdr_ping* hdr = (hdr_ping*)pkt->access(off_ping_);
// Set the 'ret' field to 0, so the receiving node knows
// that it has to generate an echo packet
hdr->ret = 0; // Store the current time in the 'send_time' field
hdr->send_time = Scheduler::instance().clock();
// Send the packet
send(pkt, 0);
// return TCL_OK, so the calling function knows that the
// command has been processed return
(TCL_OK); }
}
// If the command hasn't been processed by PingAgent()::command,
// call the command() function for the base class
return (Agent::command(argc, argv));
}
void PingAgent::recv(Packet* pkt, Handler*)
{
// Access the IP header for the received packet:
hdr_ip* hdrip = (hdr_ip*)pkt->access(off_ip_);
// Access the Ping header for the received packet:
hdr_ping* hdr = (hdr_ping*)pkt->access(off_ping_);
// Is the 'ret' field = 0 (i.e. the receiving node is being pinged)?
if (hdr->ret == 0) {
// Send an 'echo'. First save the old packet's send_time
double stime = hdr->send_time;
// Discard the packet Packet::free(pkt);
// Create a new packet
Packet* pktret = allocpkt();
// Access the Ping header for the new packet:
hdr_ping* hdrret = (hdr_ping*)pktret->access(off_ping_);
// Set the 'ret' field to 1, so the receiver won't send another
// echo
hdrret->ret = 1;
// Set the send_time field to the correct value
hdrret->send_time = stime;
// Send the packet
send(pktret, 0);
} else {
// A packet was received. Use tcl.eval to call the Tcl
// interpreter with the ping results.
// Note: In the Tcl code, a procedure 'Agent/Ping recv
// {from rtt}'
// has to be defined which allows the user to react to the
// ping result.
char out[100];
// Prepare the output to the Tcl interpreter. Calculate the
// round trip time
sprintf(out, "%s recv %d %3.1f", name(), hdrip-
>src_.addr_ >> Address::instance().NodeShift_[1],
(Scheduler::instance().clock()-hdr->send_time) * 1000);
Tcl& tcl = Tcl::instance();
tcl.eval(out);
// Discard the packet
Packet::free(pkt);
}
}
Necessary changes (I): packet.h
enum packet_t {
PT_TCP,
PT_UDP,
......
// insert new packet types here
PT_TFRC,
PT_TFRC_ACK,
PT_PING,
// packet protocol ID for our ping-agent
PT_NTYPE
// This MUST be the LAST one
};
Necessary changes (I)
class p_info {
public: p_info()
{
name_[PT_TCP]= "tcp";
name_[PT_UDP]= "udp";
...........
name_[PT_TFRC]= "tcpFriend";
name_[PT_TFRC_ACK]= "tcpFriendCtl";
name_[PT_PING]="Ping";
name_[PT_NTYPE]= "undefined";
} .....
}
Necessary change (II): tcl/lib/ns-
default.tcl

• Agent/Ping set packetSize_ 64


Necessary change (III): 'tcl/lib/ns-
packet.tcl'

{ SRMEXT off_srm_ext_}
{ Ping off_ping_ }} {
set cl PacketHeader/[lindex $pair 0]
Necessary Changes (IV): Makefile
sessionhelper.o delaymodel.o srm-ssm.o \
srm-topo.o \
ping.o \
$(LIB_DIR)int.Vec.o $(LIB_DIR)int.RVec.o \
$(LIB_DIR)dmalloc_support.o \
OK, now how to write a tcl script
to use the new Ping Agent you
just wrote?
Ping.tcl
#Create a simulator object
set ns [new Simulator]
#Open a trace file
set nf [open out.nam w]
$ns namtrace-all $nf
#Define a 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
#Create three nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
#Connect the nodes with two links
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
#Define a 'recv' function for the class 'Agent/Ping'
Agent/Ping instproc recv {from rtt} {
$self instvar node_
puts "node [$node_ id] received ping answer
from \
$from with round-trip-time $rtt ms."
}
#Create two ping agents and attach them to the nodes n0
and n2
set p0 [new Agent/Ping]
$ns attach-agent $n0 $p0
set p1 [new Agent/Ping]
$ns attach-agent $n2 $p1
#Connect the two agents
$ns connect $p0 $p1
#Schedule events
$ns at 0.2 "$p0 send"
$ns at 0.4 "$p1 send"
$ns at 0.6 "$p0 send"
$ns at 0.6 "$p1 send"
$ns at 1.0 "finish"
#Run the simulation
$ns run
C++/OTcl Linkage
Root of ns-2 object hierarchy
bind(): link variable values between
TclObject C++ and OTcl
command(): link OTcl methods to C++
implementations
TclClass Create and initialize TclObject’s
Tcl C++ methods to access Tcl interpreter
TclCommand Standalone global commands

EmbeddedTcl ns script initialization


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
TclObject: Hierarchy and Shadowing

TclObject OTcl class C++ class TclObject


hierarchy hierarchy

Agent Agent

Agent/TCP TcpAgent

_o123 *tcp
Agent/TCP OTcl Agent/TCP C++
shadow object object
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
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()
TclObject::command()
OTcl space
no such
$tcp send TclObject::unknown{} $tcp cmd send
procedure

C++ space
TcpAgent::command()

Yes match No
“send”?

process and return Invoke parent:


return Agent::command()
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);
}
TclObject: Creation and Deletion
• Global procedures: new{}, delete{}
• Example
• set tcp [new Agent/TCP]
•…
• delete $tcp
TclObject: Creation and Deletion
Agent/TCP Parent(Agent) TclObject
constructor constructor constructor
invoke parent invoke parent create C++
constructor constructor object
complete which
completeC++ create OTcl
initialization initialization
object to create? shadow object
OTcl
– TclClass
C++
TclObject (C++) parent (Agent) AgentTCP
constructor constructor constructor
invoke parent invoke parent
do nothing, constructor constructor
return bind variables bind variables
and return and return
TclClass
C++ mirroring
Static
Staticclass OTcl
classTcpClass
TcpClass ::public
publicTclClass
TclClass{{
public:
public:
TclObject TclObject
TcpClass()
TcpClass() ::TclClass(“Agent/TCP”)
TclClass(“Agent/TCP”){}{}
TclObject*
TclObject*create(int,
create(int,const
constchar*const*)
char*const*){{
NsObject return
??return(new
(newTcpAgent());
TcpAgent());
}}
}}class_tcp;
class_tcp;
Agent Agent

TcpAgent Agent/TCP
NsObject
• Other important objects:
• NsObject: has recv() method
• Connector: has target() and drop() APPLICATION
• BiConnector: uptarget() & PRESENTATIO
downtarget() N
SESSION
• Class hierarchy TRANSPORT
• NsObject
• Connector
NETWORK
• PingAgent MAC
• BiConnector
PHY
• Mac802_11
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”);
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;
}
Class TclCommand

• How to implement an OTcl command “ns-random” in


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());
}
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
Question?
Ns programming
• Create the event scheduler
• Turn on tracing
• Create network
• Setup routing
• Insert errors
• Create transport connection
• Create traffic
• Transmit application-level data
Creating Event Scheduler
• Create event scheduler
• set ns [new Simulator]
• Schedule events
• $ns at <time> <event>
• <event>: any legitimate ns/tcl commands
• $ns at 5.0 “finish”
• Start scheduler
• $ns run
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_ at 300.5 “$self halt”
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
Discrete Event Scheduler

time_, uid_, next_, handler_


head_ ->
head_ ->
handler_ -> handle()

insert time_, uid_, next_, handler_


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)


• Record “event” in trace file: $ns eventtrace-all
• E 2.267203 0 4 TCP slow_start 0 210 1
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 $sink $fmon
$fmon set pdrops_
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
$ns monitor-agent-trace $tcp
$srm0 tracevar cwnd_
……
$ns delete-agent-trace $tcp
Ns Internals
• Tcl commands translates into
• series of object creation
• plumbing of these objects
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
Components of Node
z id_
z Address of node
z Monotonically increasing by 1
z neighbor_
z A list of neighbors
z agent_
z A list of agents
z nodetype_
z A node type identifier
z A routing module
Unicast node
• Address classifier
• Distribute incoming packets to the correct link
• Port classifier
• Distribute incoming packets to the correct
agent
• First element that handles incoming
packet at the node
• unicast: entry_
• multicast: switch_
Network Topology: Node

n0 n1

Port
Classifier Unicast Multicast dmux_

Addr Node Node classifier_


Classifier
Node entry Node entry
0 dmux_ 0
entry_ entry_ 1 Multicast
classifier_ 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
Hierarchical Node

n2

Address
classifier To Port
demux
Node
Level 3
entry
Level 2
Level 1

ns_ node-config –addressing hier 88


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{}
Network Topology: Link

n0 n1

duplex link

n1
head_ entry_
enqT_ queue_ deqT_ link_ ttl_

drophead_ drpT_
tracing simplex link

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


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-size are sent to the queue’s drop-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
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
Local area network
• Link layer
• Queue: interface queue
• LL: simulate a link layer protocol (e.g. ARQ)
• Mac layer
• Must simulate some MAC protocol CS/CD/CA
• Sending: follow a MAC protocol before transmitting packets to
Channel
• Receiving: pass packets to link layer
• Physical layer
• Channel
• Sending side: simulate the shared medium
• Classifier/Mac
• Receiving side: delivering and optionally replicating packets to the
receiving MAC objects
Routing module
• Routing agent
• Exchange routing packets with neighbors
• Route logic
• Use information gathered by routing agent (or
topology database) to perform route
computation
• Classifier
• Use computed routing table to perform packet
forwarding
Setup Routing
• Unicast
$ns rtproto <type>
<type>: Static, Session, DV, cost, multi-path, Manual
• Multicast
$ns multicast (right after [new Simulator])
$ns mrtproto <type>
<type>: CtrMcast, DM, ST, BST
• Other types of routing supported: source routing,
hierarchical routing
Examples
z $ns rtproto Static ; default, use the Dijkstra’s all-pairs SPF
algorithm
z $ns rtproto Session ; recompute route when topology changes
z $ns rtproto DV $n1 $n2 $n3
z $ns rtproto LS $n1 $n2

z set n1 [$ns Node] ; only enable $n1 to use multiPaths where


applicable
z $n1 set multiPath_ 1 ; only DV routing can generate multipath
routes

z $ns cost $n1 $r1 2


z $ns cost $n2 $r2 2
z $ns cost $r1 $n2 3
Routing..

n0 n1

Port
Classifier
Addr
Classifier
n1
Node entry 0 dmux_ head_ entry
enqT_ queue_ deqT_ link_ ttl_ _
entry_ 1
classifier_ drophead_ drpT_
..Routing

n0 n1

Port Port
Classifier Classifier
Addr Addr
Classifier Classifier
0 dmux_ 1 dmux_
Link n0-n1
entry_ 1 entry_ 0
classifier_ classifier_

Link n1-n0
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
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
Network Dynamics

• Link failures
• Hooks in routing module to reflect routing
changes
• Four models
$ns rtmodel Trace <config_file> $n0 $n1
$ns rtmodel Exponential {<params>} $n0 $n1
$ns rtmodel Deterministic {<params>} $n0 $n1
$ns rtmodel-at <time> up|down $n0 $n1

• Parameter list
[<start>] <up_interval> <down_interval> [<finish>]
Creating Connection and Traffic I

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

• TCP • FTP
set tcp [new Agent/TCP] set ftp [new Application/FTP]
set tcpsink [new $ftp attach-agent $tcp
Agent/TCPSink] • Telnet
$ns attach-agent $n0 $tcp set telnet [new
$ns attach-agent $n1 Application/Telnet]
$tcpsink $telnet attach-agent $tcp
$ns connect $tcp $tcpsink
Creating Traffic: Trace Driven
• Trace driven
set tfile [new Tracefile]
$tfile filename <file>
set src [new Application/Traffic/Trace]
$src attach-tracefile $tfile
<file>:
• inter-packet time (msec) and packet size
(byte)
Transport

n0 n1

Port Port
Classifier dst_=1.0 Classifier dst_=0.0
Addr 0 Agent/TCP Addr Agent/TCPSink
Classifier Classifier 0
agents_ agents_
0 dmux_ 1 dmux_
entry_ 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

Port Application/FTP Port


Classifier dst_=1.0 Classifier dst_=0.0
Addr 0 Agent/TCP Addr 0 Agent/TCPSink
Classifier agents_ Classifier agents_
0 dmux_ 1 dmux_
entry_ entry_
classifier_ classifier_

set ftp [new Application/FTP]


$ftp attach-agent $tcp
$ns at 1.2 “$ftp start”
Packet Flow

n0 n1

Port Application/FTP Port


Classifier dst_=1.0 Classifier dst_=0.0
Addr Agent/TCP Addr Agent/TCPSink
Classifier 0 Classifier 0
0 1
Link n0-n1
entry_ 1 entry_ 0

Link n1-n0
Application objects I
• Exponential
• packetSize_
• burst_time_
• idle_time_
• rate_
• CBR
• packetSize_
• rate_
• interval_
• random_
• maxpkts_
Application objects II
• Pareto
• packetSize_
• burst_time_
• idle_time_
• rate_
• shape_
• Telnet
• interval_
• FTP
• maxpkts_
• Default values in ns/tcl/lib/ns-default.tcl
• All above are virtual applications
• focus only on “size” and “time” when data are transferred
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
• Examples
• TCP: Application/HttpApp
• UDP: Agent/Message
Application-Level Simulation
za representation of a uniform application-
level data unit (ADU)
za common interface to pass data between
applications
zmechanisms to pass data between
applications and transport agents.
ADU
zfunctionality of an ADU is similar to that of
a Packet
z pack user data into an array
zthen included in the user data area of an
nspacket
zUser must derive new agents to accept
user data from applications, or use an
wrapper like TcpApp
Passing data between
applications
class Process {
public:
Process() : target_(0) {}
inline Process*& target() { return target_; }

virtual void process_data(int size, char* data) = 0;


virtual void send_data(int size, char* data = 0);

protected:
Process* target_;
};
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]
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
Question?
Two examples
• Multicast
• Web traffic
Example: Multicast Routing
• Dynamic group membership

time
time G1
G2 n2
1.3s
1.25s
1.35s
1.2s G2 1.5Mb, 10ms
1.5Mb, 10ms
n0 n1 G1
1.5Mb, 10ms

G2 n3
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
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 $n0 $n1 1.5Mb 10ms DropTail
$ns duplex-link $n0 $n2 1.5Mb 10ms DropTail
$ns duplex-link $n0 $n3 1.5Mb 10ms DropTail
Multicast: Step 3
• Routing and group setup
# Routing protocol: let’s run distance vector
$ns mrtproto DM

# Allocate group addresses


set group1 [Node allocaddr]
set group2 [Node allocaddr]
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"
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"
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"
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
Example: Web traffic

8 7 2 3

10Mb, 20ms
1.5Mb, 40ms
9 1 0 4

10 11 6 5
Multiple levels of feedback
effects in Web traffic
client server
request >user
10sec

response HTTP
1~10sec

<TCP
1sec
request

response

page transmission user think time time


user user user
end of page
click click click
3-level Web Model

Web
•User session
¾User arrival
¾Number of page per user user
•Page
¾Page arrival Page
¾Number of objects per page
•Object object
¾Object arrival
¾Object size

2008/10/7
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
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
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 $n($s)
incr i
}
set i 0
foreach s [$ns set dst_] {
$pool set-server $i $n($s)
incr i
}
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
Web traffic: Step 5
• Schedule web sessions
# Let’s schedule two sessions
$pool set-num-session 2
# Let’s 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
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
Question?
Outline
• An introduction to ns-2
• What is ns-2
• Fundamentals
• writing ns-2 codes
• Wireless support
• Traces support and visualization
• Emulation
• Related work
Writing ns-2 codes
• Extending ns
• In OTcl
• In C++
• Debugging
ns Directory Structure
ns-allinone

Tcl8.3 TK8.3 OTcl tclcl ns-2 nam-1

tcl ... C++ code

ex test lib mcast ...

examples validation tests


ensure new changes do not
OTcl code
break the old codes
Extending ns in OTcl
• If you don’t want to compile
• 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
Add Your Changes into ns
ns-allinone

Tcl8.3 TK8.3 OTcl tclcl ns-2 nam-1

tcl ... C++ code

ex test mysrc lib mcast ...

examples validation tests msg.tcl OTcl code


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
Writing ns-2 codes
• Extending ns
• In OTcl
• In C++
• New components
Extending ns in C++
• Modifying code
• make depend
• Recompile
• Adding code in new files
• Change Makefile
• make depend
• recompile
Creating New Components
• Guidelines
• Two styles
• New agent based on existing packet headers
• Add new packet header
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)
New Agent, Old Header
• Exercise: TCP jump start
• Wide-open transmission window at the
beginning
• From cwnd_ += 1 To cwnd_ = MAXWIN_
TCP Jump Start – Step 1

TclObject Handler

NsObject

Connector Classifier

Queue Delay Agent Trace AddrClassifier McastClasifier

DropTail RED TCP Enq Deq Drop

Reno SACK JS
Packet Format

ts_
cmn header
header ptype_
ip header
data uid_
tcp header
size_
rtp header
iface_
trace header
...
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!
How Packet Header Works
Packet
PacketHeader/Common
next_
hdrlen_
bits_ size determined hdr_cmn
at compile time PacketHeader/IP

size determined size determined hdr_ip


at simulator at compile time PacketHeader/TCP
startup time
(PacketHeaderManager) size determined hdr_tcp
at compile time
……
Agent/Message – Step 1
TclObject

NsObject

Connector Classifier

Queue Delay Agent Trace AddrClassifier McastClasifier

DropTail RED TCP Message Enq Deq Drop

Reno SACK
Writing ns-2 codes
• Extending ns
• In OTcl
• In C++
• Debugging: OTcl/C++, memory
• Pitfalls
Debugging C++ in ns
• C++/OTcl debugging

• Memory debugging
• purify
• dmalloc
C++/OTcl Debugging
• Usual technique
• Break inside command()
• Cannot examine states inside OTcl!
• Solution
• Execute tcl-debug inside gdb
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()
......
Memory Debugging in ns

• Purify
• Set PURIFY macro in ns Makefile
• Usually, put -colloctor=<ld_path>
• Gray Watson’s dmalloc library
• http://www.dmalloc.com
• make distclean
• ./configure --with-dmalloc=<dmalloc_path>
• Analyze results: dmalloc_summarize
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
Pitfalls
• Scalability vs flexibility
• Or, how to write scalable simulation?
• Memory conservation tips
• Memory leaks
Scalability vs Flexibility
• It’s tempting to write all-OTcl simulation
• Benefit: quick prototyping
• Cost: memory + runtime
• Solution
• Control the granularity of your split object by
migrating methods from OTcl to C++
THE Merit of OTcl

high Program size, complexity low

C/C++ OTcl
split objects

• Smoothly adjust the granularity of scripting to


balance extensibility and performance
• With complete compatibility with existing
simulation scripts
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
Memory usage
Simulator 268KB
Unicast node 2KB
Multicast node 6KB
Duplex link 9KB
Packet 2KB
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]
• }
• It leaks memory, but can’t be detected!
• Solution
• Explicitly delete EVERY split object that was new-ed
Final Word
• My extended ns dumps OTcl scripts!
• Find the last 10-20 lines of the dump
• Is the error related to “_o*** cmd …” ?
• Check your command()
• Otherwise, check the otcl script pointed by the
error message
Questions?
Outline

• An introduction to ns-2
• What is ns-2
• Fundamentals
• Writing ns-2 codes
• Traces support and visualization
• Wireless support
• Emulation
• Related work
nsÆnam Interface

• Color
• Node manipulation
• Link manipulation
• Topology layout
• Protocol state
• Misc
nam Interface: Color
• Color mapping
$ns color 40 red
$ns color 41 blue
$ns color 42 chocolate
• Color ↔ flow id association
$tcp0 set fid_ 40 ;# red packets
$tcp1 set fid_ 41 ;# blue packets
nam Interface: Nodes
• Color
$node color red
• Shape (can’t be changed after sim starts)
$node shape box ;# circle, box, hexagon
• Marks (concentric “shapes”)
$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
nam Interfaces: Links

• Color
$ns duplex-link-op $n0 $n1 color "green"
• Label
$ns duplex-link-op $n0 $n1 label "abced“
$ns duplex-link-op $n1 $n2 label-color blue
$ns duplex-link-op $n1 $n2 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
nam Interface: Topology Layout
• “Manual” layout: specify everything
$ns duplex-link-op $n(0) $n(1) orient right
$ns duplex-link-op $n(1) $n(2) orient right
$ns duplex-link-op $n(2) $n(3) orient right
$ns duplex-link-op $n(3) $n(4) orient 60deg

• If anything missing Æ automatic


layout
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"
The nam user interface
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
A live demo Nam.exe
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
namgraph
The nam editor
• Create simple scenarios graphically
• Good for those who don’t want to learn Tcl,
but only a limited subset of ns is currently
available
The nam editor
Topology generator

• Inet
• GT-ITM
• TIERS
• BRITE
Summary
http://www.isi.edu/nsnam/ns/ns-topogen.html

Packages Graphs Edge Method


NTG n-level probabilistic
RTG Flat random Waxman
Flat random, n-
GT-ITM various
level, Transit-stub
TIERS 3-level spanning tree
Outline
• An introduction to ns-2
• What is ns-2
• Fundamentals
• Writing ns-2 codes
• Traces support and visualization
• Wireless support
• Emulation
• Related work
Wireless support in ns-2
• Introduction
• Wireless basics
• Wireless internals
• Ad hoc routing
• Mobile IP
• Satellite networking
• Directed diffusion
Contributions to wireless in ns
• Original wireless model in ns contributed
by CMU’s Monarch group
• 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
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
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
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
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
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>
Example –Step 3
• Create God
set god [create-god 3]
$ns at 900.00 “$god set-dist 2 3 1”
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
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
}
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
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-scen-
gen/setdest/

• Random movement
• $node random-motion 1
• $node start
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"
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/
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"
…….
An Example – Step 6
# Define node movement model
source <movement-scenario-files>

# Define traffic model


source <traffic-scenario-files>
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
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
nam Visualization
• Use nam to visualize:
• Mobile node position
• Mobile node moving direction and speed
• Energy consumption at nodes (color keyed)
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]
Wireless support in ns-2
• Introduction
• Wireless basics
• Wireless internals
• Ad hoc routing
• Mobile IP
• Satellite networking
• Directed diffusion
Wireless Internals
• Mobilenode
• Basic node that has address and port de-
muxes, routing agent etc
• Stack of network components consisting of LL,
MAC, NetIF radio-model etc
• Wireless channel
Portrait of A Mobile Node
port
Node classifier
protocol
agent Classifier: Forwarding

255
Agent: Protocol Entity
addr routing
classifier defaulttarget_ agent
Node Entry
LL ARP
LL LL: Link layer object
IFQ
IFQ IFQ: Interface queue
MAC

Propagation
MAC MAC: Mac object
PHY and antenna
models
MobileNode
PHY PHY: Net interface
CHANNEL
Prop/ant Radio propagation/
antenna models
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
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
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
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
Wireless Channel
• Duplicate packets to all mobile nodes
attached to the channel except the sender
• It is the receiver’s responsibility to decide if
it will accept the packet
• Collision is handled at individual receiver
• O(N2) messages Æ grid keeper, reference-
copying etc
Grid-keeper: An Optimization
Mobile Node: Misc.
• Energy consumption model for sensor
networks
• Visualization of node movement,
reachability, and energy
• Validation test suites
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
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-suite-
wireless- { lan-newnode.tcl, lan-aodv.tcl,
lan-tora.tcl }
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-lan-
newnode.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
Simulate sensor network with
ns-2
• Currently support
• Routing
• Direct diffusion
• MAC
• SMAC
Outline
• An introduction to ns-2
• What is ns-2
• Fundamentals
• Writing ns-2 codes
• Traces support and visualization
• Wireless support
• Emulation
• Related work
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
Emulation in ns-2

ns
Read packets Write packets

Network
Scheduler
• ns operates in virtual time using event-
driven simulation
• Real-time scheduler
• Does not advance the virtual clock to next
event
• Dispatches event at real-time
Emulation Objects
Capture: BPF
• Interface between ns and
network traffic network to ns

• Network Objects
• Access to live network via
• BPF and raw sockets ns
• Tap Objects
• Conversion between ns ns to network
and
• network packet formats Inject: Raw socket
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
Opaque Mode
• Network packet is passed unmodified
through simulator

Extern
Source
Destination Source
Size Destination
Size
Ns packet contains
a pointer to the

ns
network packet
Data

Read packets Write packets

Network Packet

Network
Protocol Mode
• Network packet fields are generated by
the simulator
Host A Host B
Source Source TCP Agent
Destination Destination
Size Size
TCP
The ns packet Application
header is Data
mapped onto the
network packet
header and visa
versa . Network Packet ns
Send/receive Send/receive
packets from packets from
application ns

Network
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
Example: Setup
Goal: Make a ns TCP agent interact with a TCP server
A 192.168.1.1 B 192.168.1.2 port 8000

nse TCP server

• Disable IP forwarding • Add route to dummy IP


• sysctl –w address
net.inet.ip.forwarding=0
• route add 10.0.0.1 192.168.1.1
• Assign 10.0.0.1 and 6000 • Disable IP redirects
to TCP agent Switch • sysctl –w net.inet.ip.redirect=0
Example Script
set ns [new Simulator] Activate ns and
$ns use-scheduler RealTime Change to real-time
scheduler
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

TCP Agent TCPTap BPF

tcp_node entry_node
TCPTap RawSocket
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 CaptureTap InjectTap
$ns attach-agent $entry_node $inject_tap entry_node
$ns simplex-connect $tcp $inject_tap BPF RawSocket
Example Script
$ns at 0.01 "$tcp advance 1"
$ns at 20.0 “exit 0" start nse
$ns run

A 192.168.1.1 B 192.168.1.2
TCP Agent

TCP Server
(8000)
BPF Raw Socket

Switch
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
Ns-2 related work

• Other simulators
• Researching uses ns-2
• Using ns-2 for education
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
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
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
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

You might also like