Showing posts with label NS2. Show all posts
Showing posts with label NS2. Show all posts

Thursday 4 April 2013

New Wireless Packet Trace Format in NS2


New Wireless Packet Trace Format can be activated by adding following TCL statement in the simulation script :

$ns_ use-newtrace

The new wireless trace format is as follows:

<tag> <tag_value> [-<subtag> <subtag_value>]

where <tag> is a one-letter or two-letter option tag, indicating the meaning of the following <tag_value>. Optionally, <subtag> is the subtag whose value is specified in <subtag_value>. The list of option tags and sub-tags as well as their meaning is given bellow :


General Information :

-t  Time

Node Information(-N?) :

-Ni  Node ID
-Nl  Trace level : AGT/RTR/MAC 

-Ne  Energy Level
-Nx,-Ny,-Nz,-Nw  Node Cordinates

IP Information(-I?):

-Is  Source Port
-It  Packet Type
-If  Flow ID
-Iv  Time to live
-Id  Destination Port
-Il  Packet size
-Ii  Unique ID

Next Hop (-H?):

-Hs  ID of this node

MAC Level Information(-M?):

-Ms  Source Ethernet Address
-Md  Destination Ethernet Address
-Mt  Ethernet Type
-Ma  Packet Transmission Time

Application information-ARP (-P arp -P?):

 -Ps   Source address
 -Pm  Source MAC address
 -Po   Either "REQUEST" or "REPLY"
 -Pd   Destination IP Address
 -Pa   Destination MAC address

 Application information-CBR (-P cbr -P?):

 -Pi    Sequence number
 -Pf          The number of time this picket has been forwarded
 -Po   Min. number of hops to reach the destination as indicated by GOD. The default value when GOD is not in use is -1

 Application information - TCP(-P tcp -P?):

 -Ps   Sequence number
 -Pf    same as that of CBR
 -Pa   Acknowledge number acknowledgement number
 -Po   same as that of CBR

Consider Following Example for explanation of this Format :

 s -t 31.000000000 -Hs 0 -Hd -2 
-Ni 0 -Nx 19.36 -Ny 17.32 -Nz 0.00 -Ne -1.000000 
-Nl AGT -Nw --- -Ma 0 -Md 0 -Ms 0 -Mt 0
-Is 0.0 -Id 1.0 -It tcp -Il 40 -If 2 -Ii 3 -Iv 32 
-Pn tcp -Ps 0 -Pa 0 -Pf 0 -Po 0


  • At 31 second, this record traces Node 0 at the agent AGT level. 
  • Node 0 is located at the coordinate (19.36,17.32,0). 
  • The reasons string (i.e., -Nw) is empty. 
  • The record does not trace the node energy level (-Ne -1). 
  • The packet is sent from the address 0 port 0 to the node with the address 1 port 0. 
  • The packet type is “tcp” whose size is 40 bytes (i.e., this is the SYN packet). 
  • The flow ID is 2. The packet unique ID is 3. 
  • The time to live is 32.
  • This packet has never been forwarded before. The number of hops to destination as indicated by GOD is zero (i.e., GOD is not active).



Tuesday 16 October 2012

LEACH in NS2 using Mannasim Frame-work

The code in the editor below shows how to simulate LEACH protocol
using MannaSim patch with ns2. A summary of the simulation settings is
given below:

Area: 500 m X 500m
Duration: 550 sec
# of nodes: 11
# of clusters: 4
New cluster formation interval: 100 sec (fixed)
Initial energy: 10 joules
Disseminating interval: 10 sec
Transmission range: 50 m
Channel type: Wireless
Transport protocol: UDP
Layer: Physical
Antenna: OmniAntenna
Radio Propagation:TwoRayGround
Sensing interval: 5 sec
Data generator type: Temperature
Sensing type: Programmed

The no. of access points has been set to be 0 for our simulation and
all the nodes are static.

The ratio P that has been referred to while describing LEACH in the
theory section is obtained in our case as k/N, where k is the # of
desired cluster heads, and N is the total # of nodes in the network.

Now, answer the following and verify them from the simulation results:

For the given simulation time, how many rounds of cluster formation take place?
What is the number of cluster heads per round?
Does the average number of cluster heads per round equal the desired
number of cluster heads (line #475)? (See the discussion on LEACH in
Theory section)
Vary the number of nodes (line #474) and expected number of cluster
heads (line #475), and once again verify the output


# Generated by MannaSim


puts "Initializing MannaSim Script..."

#Consumo de energia do sensor node - Dados do Mica Motes
set mica(sensing_power) 0.015 ;# i = 5mA, V = 3 --> P = ixV = 15 mW = 0.015 W
set mica(processing_power) 0.024 ;# i = 8mA, V = 3 --> P = ixV = 24 mW = 0.024 W
set mica(instructions_per_second) 8000000 ;# Atmel 128L 8MHZ --> 8MIPS

#Consumo de energia do sensor node - Dados do WINS
set wins(sensing_power) 0.064 ;# 64 mW = 0.064 W
set wins(processing_power) 0.360 ;# 360 mW = 0.360 W
set wins(instructions_per_second) 150000000 ;# Intel StrongArm 1100 133 MHZ --> 150 MIPS

#Seta valores para consumo de energia com o radio
set mica(consumo_transmissao) 0.036 ;#i = 12mA, V = 3 --> P = ixV = 36mW = 0.036W
set mica(consumo_recepcao) 0.024 ;#i = 8mA, V = 3 --> P = ixV = 24mW = 0.024W

set wins(consumo_transmissao)   3.75 ;# 3.75 250m, 0.6 600 mW - 100m
set wins(consumo_recepcao) 1.875 ;# 1.875 250m,  0.3 300 mW

#seta a taxa de transmissao
#Phy/WirelessPhy set  bandwidth_
set mica(taxa_transmissao) 28.8*10e3 ;#28.8 kbps
set wins(taxa_transmissao) 100*10e3 ;#100 kbps

proc setup_mica2 { antenna range }  {
        puts "Setting up mica 2 mote with $antenna and range = $range"      

        Phy/WirelessPhy set Pt_ 0.281838
        Phy/WirelessPhy set freq_ 2.4e09
        Phy/WirelessPhy set L_ 1.0
        Phy/WirelessPhy set lambda_ 0.125
        Phy/WirelessPhy set RXThresh_ [TwoRay 0.281838 [$antenna set Gt_] [$antenna set Gr_] 0.8 0.8 1.0 $range 0.125]
        Phy/WirelessPhy set bandwidth_ 28.8*10e3        ;#28.8 kbps

        Node/MobileNode/SensorNode set sensingPower_ 0.015
        Node/MobileNode/SensorNode set processingPower 0.024
        Node/MobileNode/SensorNode set instructionsPerSecond_ 8000000

}

##########################################
# CONSTANTES
#########################################
# Continuo: 0
# Programada: 1
# Sob Demanda: 2
########################################

proc create_common_app {destination_id disseminating_type disseminating_interval} {
    global val
    #puts "executing create_common_app\n"
    if { $val(commonApp) == "Application/SensorBaseApp/CommonNodeApp/LeachApp" } {
          if { $val(n_ch) == 0 } {
                   puts "NO CLUSTER HEADS HAS BEEN DEFINED! Assuming 20% of common nodes."
                   set val(n_ch) [expr int($val(n_common) * 2 / 10)]
          }
          #puts "Debug: val(n_ch): $val(n_ch)\n";
          set app_ [new $val(commonApp) $val(nn) $val(n_ch) [expr sqrt($val(x) * $val(x) + $val(y) * $val(y))]]
    } else {
          set app_ [new $val(commonApp)]
          $app_ set destination_id_ $destination_id
    }
    $app_ set disseminating_type_ $disseminating_type
    $app_ set disseminating_interval_ $disseminating_interval
    return $app_
}

set val(commonApp) "Application/SensorBaseApp/CommonNodeApp"
set val(chApp)     "Application/SensorBaseApp/ClusterHeadApp"
set val(apApp)     "Application/AccessPointApp"

proc create_cluster_head_app {destination_id disseminating_type disseminating_interval} {
    global val
    set app_ [new $val(chApp)]
    $app_ set destination_id_ $destination_id
    $app_ set disseminating_type_ $disseminating_type
    $app_ set disseminating_interval_ $disseminating_interval
    return $app_
}

proc create_access_point_app {outside_network} {
    global val
    set app_ [new $val(apApp)]
    $app_ set outside_network_ $outside_network
    return $app_
}

proc create_temp_data_generator {sensing_interval sensing_type avg_measure std_deviation maximumTemperatureAllowedValue} {
    set temp_gen_ [new DataGenerator/TemperatureDataGenerator]
    $temp_gen_ set sensing_interval_ $sensing_interval
    $temp_gen_ set sensing_type_ $sensing_type
    $temp_gen_ set avg_measure $avg_measure
    $temp_gen_ set std_deviation $std_deviation
    $temp_gen_ set maximumTemperatureAllowedValue_ $maximumTemperatureAllowedValue
    return $temp_gen_
}

proc create_data_generator {generator sensing_interval sensing_type avg_measure std_deviation maximumTemperatureAllowedValue} {
    set temp_gen_ [new DataGenerator/$generator]
    $temp_gen_ set sensing_interval_ $sensing_interval

    if {$sensing_type=="continuous"} {
          $temp_gen_ set sensing_type_ 0
    } elseif {$sensing_type=="programmed"} {
          $temp_gen_ set sensing_type_ 1
    } elseif {$sensing_type=="on demand"} {
          $temp_gen_ set sensing_type_ 2
    } else {          
          $temp_gen_ set sensing_type_ $sensing_type
    }
    $temp_gen_ set avg_measure $avg_measure
    $temp_gen_ set std_deviation $std_deviation
    $temp_gen_ set maximumTemperatureAllowedValue_ $maximumTemperatureAllowedValue
    return $temp_gen_
}

proc create_common_node { iniEnergy x y z father_addr start stop } {
    global val ns_ node_ topo udp_ app_ gen_ contador_nodos rng trace

    if { [llength $start] == 0 }  {
            set start [expr $val(start) + [$rng uniform 0 1]]
            set stop $val(stop)
    }

    $ns_ node-config -sensorNode ON \
        -adhocRouting $val(rp) \
        -llType $val(ll) \
        -macType $val(mac) \
        -ifqType $val(ifq) \
        -ifqLen $val(ifqlen) \
        -antType $val(antenna) \
        -propType $val(prop) \
        -energyModel $val(en) \
        -phyType $val(netif) \
        -channelType $val(chan) \
        -topoInstance $topo \
        -agentTrace $trace(agent) \
        -routerTrace $trace(router) \
        -macTrace $trace(mac) \
        -rxPower 0.024 \
        -txPower 0.036 \
        -initialEnergy $iniEnergy \
        -movementTrace $trace(movement)

        set node_($contador_nodos) [$ns_ node]
        $node_($contador_nodos) random-motion 0

        $node_($contador_nodos) set X_ $x
        $node_($contador_nodos) set Y_ $y
        $node_($contador_nodos) set Z_ $z

        puts "* Node [$node_($contador_nodos) node-addr] = $contador_nodos created in ($x, $y, $z)"

        set app_($contador_nodos) [create_common_app $father_addr $val(disseminating_type) $val(disseminating_interval)]

        if { $val(leach) == 1 } {
              set agent [new Agent/RCAgent]

              $agent set sport_ 0
              $agent set dport_ 0

              $node_($contador_nodos) attach $agent 0
              $app_($contador_nodos) attach-agent $agent

              $agent add-ll [$node_($contador_nodos) set ll_(0)] [$node_($contador_nodos) set mac_(0)]
        } else {
                set udp_($contador_nodos) [new Agent/UDP]
                $node_($contador_nodos) attach $udp_($contador_nodos) $val(port)
        }
        $node_($contador_nodos) add-app $app_($contador_nodos)

        set processing_($contador_nodos) [new $val(processing)]

        $app_($contador_nodos) node $node_($contador_nodos)

        if { $val(leach) != 1 } {
                $app_($contador_nodos) attach-agent $udp_($contador_nodos)
        }

        $app_($contador_nodos) attach-processing $processing_($contador_nodos)
        $processing_($contador_nodos) node $node_($contador_nodos)

        for { set i 0 } { $i < [llength $start] } { incr i } {
                $ns_ at $start "$app_($contador_nodos) start"
        }

        for { set i 0 } { $i < [llength $stop] } { incr i } {
                $ns_ at $stop "$app_($contador_nodos) stop"
        }

        #[create_temp_data_generator  5.0 0 27.0 10.0 50]
        set gen_($contador_nodos) $val(data_generator)

        $app_($contador_nodos) attach_data_generator $gen_($contador_nodos)

        incr contador_nodos

}

proc create_cluster_head_node { iniEnergy x y z father_addr start stop } {

        global val ns_ node_ topo udp_ app_ gen_ contador_nodos rng trace

        if { [llength $start] == 0 }  {
                set start [expr $val(start) + [$rng uniform 0 1]]
                set stop $val(stop)
        }

        $ns_ node-config -sensorNode ON \
            -adhocRouting $val(rp) \
            -llType $val(ll) \
            -macType $val(mac) \
            -ifqType $val(ifq) \
            -ifqLen $val(ifqlen) \
            -antType $val(antenna) \
            -propType $val(prop) \
            -energyModel $val(en) \
            -phyType $val(netif) \
            -channelType $val(chan) \
            -topoInstance $topo \
             -agentTrace $trace(agent) \
            -routerTrace $trace(router) \
            -macTrace $trace(mac) \
            -rxPower 0.024 \
            -txPower 0.036 \
            -initialEnergy $iniEnergy \
            -movementTrace $trace(movement)

        #puts "Debug Cluster head iniEnergy: $iniEnergy\n";

        set node_($contador_nodos) [$ns_ node]
        $node_($contador_nodos) random-motion 0


        $node_($contador_nodos) set X_ $x
        $node_($contador_nodos) set Y_ $y
        $node_($contador_nodos) set Z_ $z

        puts "* Cluster head [$node_($contador_nodos) node-addr] = $contador_nodos created in ($x, $y, $z)"

        set udp_($contador_nodos) [new Agent/UDP]
        set app_($contador_nodos) [create_cluster_head_app $father_addr $val(disseminating_type) $val(disseminating_interval)]

        $node_($contador_nodos) attach $udp_($contador_nodos) $val(port)
        $node_($contador_nodos) add-app $app_($contador_nodos)

#CN#        set processing_($contador_nodos) [new $val(processing)]

        $app_($contador_nodos) node $node_($contador_nodos)
        $app_($contador_nodos) attach-agent $udp_($contador_nodos)

#CN#        $app_($contador_nodos) attach-processing $processing_($contador_nodos)
        $processing_($contador_nodos) node $node_($contador_nodos)

        for { set i 0 } { $i < [llength $start] } { incr i } {
                $ns_ at $start "$app_($contador_nodos) start"
        }

        for { set i 0 } { $i < [llength $stop] } { incr i } {
                $ns_ at $stop "$app_($contador_nodos) stop"
        }

#CN#        set gen_($contador_nodos) $val(data_generator)
#CN#        $app_($contador_nodos) attach_data_generator $gen_($contador_nodos)

        incr contador_nodos

}

proc create_access_point { iniEnergy x y z start stop} {
        global ns_ val node_ app_ udp_ contador_nodos topo trace rng

        if { [llength $start] == 0 }  {
                set start [expr $val(start) + [$rng uniform 0 1]]
                set stop $val(stop)
        }

        $ns_ node-config -sensorNode ON \
            -adhocRouting $val(rp) \
            -llType $val(ll) \
            -macType $val(mac) \
            -ifqType $val(ifq) \
            -ifqLen $val(ifqlen) \
            -antType $val(antenna) \
            -propType $val(prop) \
            -energyModel $val(en) \
            -phyType $val(netif) \
            -channelType $val(chan) \
            -topoInstance $topo \
             -agentTrace $trace(agent) \
            -routerTrace $trace(router) \
            -macTrace $trace(mac) \
            -rxPower 0.5 \
            -txPower 0.5 \
            -initialEnergy $iniEnergy \
            -movementTrace $trace(movement)

        #puts "Debug AP iniEnergy: $iniEnergy\n";

        set node_($contador_nodos) [$ns_ node]
        $node_($contador_nodos) random-motion 0
        set app_($contador_nodos) [create_access_point_app [$node_(0) node-addr]]

        if { $val(leach) == 1 } {
              set agent [new Agent/RCAgent/LeachAgent]

              $agent set sport_ 0
              $agent set dport_ 0

              $node_($contador_nodos) attach $agent 0
              $app_($contador_nodos) attach-agent $agent

              $agent add-ll [$node_($contador_nodos) set ll_(0)] [$node_($contador_nodos) set mac_(0)]
        } else {
              set  udp_($contador_nodos) [new Agent/UDP]
              $node_($contador_nodos) attach $udp_($contador_nodos) $val(port)
              $app_($contador_nodos) attach-agent $udp_($contador_nodos)
        }
        $node_($contador_nodos) set X_ $x
        $node_($contador_nodos) set Y_ $y
        $node_($contador_nodos) set Z_ $z

        puts "* Access point [$node_($contador_nodos) node-addr] = $contador_nodos created in ($x, $y, $z)"

        for { set i 0 } { $i < [llength $start] } { incr i } {
                $ns_ at $start "$app_($contador_nodos) start"
        }

        for { set i 0 } { $i < [llength $stop] } { incr i } {
                $ns_ at $stop "$app_($contador_nodos) stop"
        }

        incr contador_nodos

}

###
# Grid distribution.

proc get_next_x {} {

        global val
        set aux [expr int(sqrt($val(nn)))]
        return [expr (($contador_nodos) % $aux) * $val(x) / ($aux - 1)]

}

proc get_next_y {} {

        global val
        set aux [expr int(sqrt($val(nn)))]
        return [expr (($contador_nodos) / $aux) * $val(y) / ($aux - 1)]

}

####
# Calculating the receiving threshold (RXThresh_ for Phy/Wireless)
# Wei Ye, weiye@isi.edu, 2000

proc Friis { Pt Gt Gr lambda L d} {
  set M [expr $lambda / (4 * 3.14159265359 * $d)]
  return [expr ($Pt * $Gt * $Gr * ($M * $M)) / $L]
}

proc TwoRay { Pt Gt Gr ht hr L d lambda } {
        set crossover_dist [expr (4 * 3.14159265359 * $ht * $hr) / $lambda]

        if { $d < $crossover_dist } {
                return [Friis $Pt $Gt $Gr $lambda $L $d]
        } else {
                return [expr $Pt * $Gt * $Gr * ($hr * $hr * $ht * $ht) / ($d * $d * $d * $d * $L)]
       }
}

###

proc set_default_settings {} {

        global val

        ####
        # Default network settings
        set val(antenna) "Antenna/OmniAntenna"
        Antenna/OmniAntenna set X_ 0 ;
        Antenna/OmniAntenna set Y_ 0 ;
        Antenna/OmniAntenna set Z_ 1.5 ;
        Antenna/OmniAntenna set Gt_ 1.0 ;
        Antenna/OmniAntenna set Gr_ 1.0 ;

        ###

        # Using Mica 2 Mote settings


        set val(range) 100
        setup_mica2 $val(antenna) $val(range)
        set val(bandwidth) [Phy/WirelessPhy set bandwidth_]
        set val(mac)    Mac/802_11
        set val(ifq)    Queue/DropTail
        set val(ifqlen) 200
        set val(ll) LL
        set val(rp) "LEACH"


        # Configuration adjustment

        if { $val(rp) == "LEACH" } {

                set val(rp) DumbAgent
                set val(leach) 1

                if { $val(ll) != "RCALinkLayer" } {
                        puts "LEACH requires RCALinkLayer! Forcing it!!!"                   
                        set val(ll) RCALinkLayer
                }

                if { $val(netif) != "Phy/WirelessPhy/LeachWirelessPhy" } {
                        puts "LEACH requires LeachWirelessPhy! Forcing it!!!"
                        set val(netif) Phy/WirelessPhy/LeachWirelessPhy
                }

                if { $val(mac) != "Mac/Sensor" } {
                        puts "LEACH requires Mac/Sensor! Forcing it!!!"
                        set val(mac) Mac/Sensor
                }

                set val(port) 0

                Agent/RCAgent set sport_           $val(port)
                Agent/RCAgent set dport_           $val(port)
                Agent/RCAgent set packetMsg_       0
                Agent/RCAgent set distEst_         0
                Agent/RCAgent set packetSize_      0

                RCALinkLayer set delay_            25us
                RCALinkLayer set bandwidth_        [Phy/WirelessPhy set bandwidth_]
                RCALinkLayer set off_prune_        0
                RCALinkLayer set off_CtrMcast_     0
                RCALinkLayer set macDA_            0
                RCALinkLayer set debug_            0
        } else {
                set val(leach) 0
        }
        if { $val(rp) == "DIRECTED DIFFUSION" } {
                set val(rp) "Directed_Diffusion"
        }       
}

set val(father_addr) 0 
set val(port)   2020

set val(netif)  Phy/WirelessPhy

set_default_settings

# Global network settings
set contador_nodos 0
set val(chan)   Channel/WirelessChannel

# Propagation
set val(prop)   Propagation/TwoRayGround

# Energy model
set val(en) EnergyModel/Battery

# Nodes
set val(n_pas)  0
set val(n_common) 11
set val(n_ch) 4
set val(nn) [expr $val(n_pas) + $val(n_common) + $val(n_ch)]

puts "\nNodes count:"
puts " - $val(n_pas) access points"
puts " - $val(n_common) common nodes"
puts " - $val(n_ch) cluster heads"
puts " - $val(nn) nodes"
puts " - $val(rp) routing protocol"
puts " - $val(ll) link layer"
puts " - $val(netif) network interface"

# Scenario size
set val(x)  500.0
set val(y)  500.0

puts "\nScenario size: $val(x) x $val(y)"

set val(start)  0.0
set val(stop)   [expr $val(start) + 550.0]

set ns_     [new Simulator]


# Trace
puts "\nUsing trace.tr as trace file"
set traceFile   [open trace.tr w]
$ns_ trace-all $traceFile
$ns_ use-newtrace

set trace(mac) ON
set trace(router) ON
set trace(agent) ON
set trace(movement) ON


set topo    [new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)
set rng [new RNG]
$rng seed [clock seconds]

#-------------------------------------------------------------------------------------------



# Creating an access point
puts "Creating an access point..."

set_default_settings


# Using Mica 2 Mote settings

puts "Using mica 2 mote settings"
set val(range) 100
setup_mica2 $val(antenna) $val(range)
set local(x) 50.0
set local(y) 50.0
set local(z) 0.0
set local(start) ""
set local(stop) ""
set local(energy) 100.0
set val(apApp) Application/AccessPointApp/AccessPointLeachApp

create_access_point $local(energy) $local(x) $local(y) $local(z) $local(start) $local(stop)



# Creating common node
puts "Creating common node..."

set_default_settings


# Using Mica 2 Mote settings
puts "Using mica 2 mote settings"

set val(range) 100
setup_mica2 $val(antenna) $val(range)

# Disseminating settings
set val(disseminating_type) 0       ;# Programmed
puts "Setting disseminating type to programmed"
set val(disseminating_interval) 10.0
puts "Setting disseminating interval: $val(disseminating_interval)"

set local(start) ""
set local(stop) ""
set local(energy) 10.0
set local(father_addr) $val(father_addr)

set val(processing) Processing/AggregateProcessing
set val(data_generator) "[create_data_generator {TemperatureDataGenerator} {5.0} {programmed} {25.0} {5.0} {30.0}]"


for { set common_node_i 0 } { $common_node_i < 10 } { incr common_node_i } {
    set local(x) [$rng uniform 0.0 $val(x)]
    set local(y) [$rng uniform 0.0 $val(y)]
    set local(z) 0.0

    set val(commonApp) Application/SensorBaseApp/CommonNodeApp/LeachApp
    create_common_node $local(energy) $local(x) $local(y) $local(z) $local(father_addr) $local(start) $local(stop)
}


$ns_ at [expr $val(stop)] "flush stdout"
$ns_ at [expr $val(stop)+0.0001] "finish"


proc finish {} {
    global ns_ traceFile namtrace tempoInicio val

    $ns_ flush-trace
    #    close $namtrace
    $ns_ halt
    $ns_ flush-trace
    #$ns_ nam-end-wireless $val(stop)
    close $traceFile
    #close $namtrace
    flush stdout

    exit 0
}

puts "Starting Simulation..."
$ns_ run

Saturday 25 August 2012

Trace File Format in NS2

In the previous post, I showed you how to create a “trace file” in NS2. In this post, I will show you the interpretation of an NS2 trace file.

Example of trace files :-

When using trace-all in NS2, a trace string is created in a trace file. The trace file would look like this.


Trace file format :-

The format of a trace string is shown below:




where 12 fields of the trace string are as follows.

1. Type Identifier:

 • “+”: a packet enque event
 • “-”: a packet deque event
 • “r”: a packet reception event
 • “d”: a packet drop (e.g., sent to dropHead_) event
 • “c”: a packet collision at the MAC level

2. Time: at which the packet tracing string is created .

3-4. Source Node and Destination Node: denote the IDs of the source and the destination nodes of the tracing object.

5. Packet Name: Name of the packet type

6. Packet Size: Size of the packet in bytes.

7. Flags: A 7-digit flag string

 • “-”: disable
 • 1st = “E”: ECN (Explicit Congestion Notification) echo is enabled.
 • 2nd = “P”: the priority in the IP header is enabled.
 • 3rd : Not in use
 • 4th = “A”: Congestion action
 • 5th = “E”: Congestion has occurred.
 • 6th = “F”: The TCP fast start is used.
 • 7th = “N”: Explicit Congestion Notification (ECN) is on.

8. Flow ID

9-10. Source Address and Destination Address: the format of these two fields is “a.b”, where “a” is the address and “b” is the port.


11. Sequence Number

12. Packet Unique ID

Post processing NS2 Result using NS2 Trace

In this post, I will show you a simple (and perhaps the most common way) to create an NS2 trace file. This trace file contains a lot of information. In fact, it contains too much information, which intimidates NS2 users. Don’t worry about it. We will try to interpret NS2 trace files later. For now, let’s focus on how an NS2 trace file can be created.

To create a trace file, you need to do the following two steps:
  1. Create a file to record tracing information.
  2. Record the tracing information to the created file.
Create a File for Writing :-

Tcl uses a command “open” to open a file. The syntax of the command “open” is as follows:
open <filename> <purpose>
where <filename> is the name of the file to be opened, and <purpose> can be
“w” for writing,
“r” for reading, or
“a” for appending
This statement returns a file handle, which can be used to refer to the opened file.
An example of a Tcl statement which opens a file whose name is “tracefile.tr” for writing and stores to the file handle in the variable $var is shown below:
set var [ open tracefile.tr w ]

Record tracing information in the opened trace file :-

The next step is to record trace information in the opened file. This can be achieved using the following Tcl statement:

$ns trace-all $var

where $ns is the Simulator instance, and $var is the file handle. This statement tells all the tracing objects (e.g., enqT_, deqT_, rcvT_, and drpT_ in the SimpleLink object below) to record information of traversing packets in the trace file whose variable is $var.

There is only one requirement for tracing: The above statement must be located prior to “$ns run”.

After the simulation complete, a trace file would be created. Here is an example of trace files.



The statement “$ns trace-all” inserts tracing object into various places in network topology. The most common place is in a SimpleLink usually used to connect two nodes. The statement “$ns trace-all” inserts few tracing objects into the SimpleLink object as shown above.

A tracing object sits between two NsObject intercepting objects. Once receiving a packet, it prints related tracing information as a line into the trace file. In the above figure, we have four tracing objects:

  • enqT_: Print a line beginning with “+”, indicating an enqueuing event
  • deqT_: Print a line beginning with “-”, indicating a dequeuing event
  • rcvT_: Print a line beginning with “r”, indicating a packet reception event
  • drpT_: Print a line beginning with “d”, indicating a packet dropping event
Tracing Statements in the Trace File:

These tracing objects print information of all traversing packets. Information of packets which do not pass through any of these objects would not appear on the trace file.

The only object responsible for dropping packets in the above figure is queue_. It does so by invoking function drop(p). The function drop(p) in turn sends the packet p to the forwarding NsObject, which in this case is drpT_. It is drpT_, who is responsible for printing dropping information statements (i.e., those begin with ‘d’) in the trace file.

This means that if you drop the packet explicitly (e.g., using drop(p)) without passing the packet through drpT_, no information about dropping packet would appear on the trace file.

IP Routing in NS2



I know. I know. IP is “the most” widely used routing in the computer industry. But, we as people in academic need to be a bit more precise when using buzz words.

IP: refers to IP address. It is different from routing mechanism. IP address is just a hierarchical way of defining an endpoint.
Routing mechanism: is a way of determining the route to get to a given destination. It works according to an underlying routing table.
Routing algorithm: computes a routing table.
Routing protocol: is a set of communication rules, which shall be followed under a certain condition such as a route failure.

Here is a example set of parameters in practice:

Addressing = IP Address
Routing mechanism = Routing table; Route Summary
Routing algorithm = Dijkstra
Routing protocol = OSPF

What about NS2?

By default, NS2 uses the following setting

Addressing = Flat address (1,2,3,…)
Routing mechanism = Address classifiers
Routing algorithm = Dijkstra
Routing protocol = Static (The condition of all the nodes does not change throughout the simulation)

Do You Really Need IP?

I have received quite a few questions like “How do I implement IP in NS2?” My first response would be “this is too vague”. You really have to break down your questions. At least, you have to identify which of the above 4 topics you would like to study.

For example, if you would like to study routing protocols, you’d probably refer to OSPF or BGP routing protocols. If your focus is on the communiation protocols of the routing, you can use the following setting

Addressing: Flat
Routing Mechansism: Classifier
Routing Algrithm: Dijkstra (used by default as a part of OSPF)

which are the default setting of NS2.

Routing in NS2

The default routing protocol of NS2 is static routing. This means that there would be no change in topology throughout the simulation. In this case, NS2 configures the routing information once when the simulation start with the OTcl statement “$ns run”. The process proceeds as follows:

Step 1: [OTcl] Simulator::run
Step 2: [OTcl] Routelogic::configure
Step 3: [OTcl] Agent/rtProto/Static::init-all
Step 4: [OTcl] Simulator::compute-routes
Step 5: [OTcl] Simulator::computer-flat-route
Step 6: [OTcl] RouteLogic::compute
Step 7: [OTcl] Simulator::populate-flat-classifier

Step 6: The OTcl class RouteLogic is bound to the C++ class with the same name (see file ns-2.35/routing/route.cc,h). The OTcl command compute simply executes the funciton compute_routes(…) in the C++ domain. From this point, you have look closely of what NS2 does and apply necessary changes to fit your needs.

Step 7: See how NS2 populate the routing information to all the Nodes. You will need to look into this step to see how routing information are delivered to all related Nodes.

Network Simulator 2 Tutorials

1.  For Learning about Network Simulator 2 basics you can use Marc Greis Tutorials here.

2. You can use following materials

Install Mannasim Patch in NS 2.34 for Wireless Sensor Network Simmulation


1. Download Mannsim Patch for NS 2.34 here.

2. Type the following command on the ns-allinone-2.29 folder:
  • patch -p1 < ns2.34-mannasim-gcc4.3.patch
3. Install NS 2.34 as shown in previous post . 

To test MannaSim installation two simulation scripts are provided bellow. The first one simulates a flat network of homogeneous sensors and the second a hierarchical network composed of two diferent classes of sensor nodes.

If you have any installation problem then post comments......

Install NS 2.34 in Ubuntu 10.10

1. Download & install some packages from repository by following commands :
  • $ sudo apt-get update
  • $ sudo apt-get install build-essential autoconf automake libxmu-dev 
2. Download  ns-2.34 and extract in your home directory.

3. Install the development files for X Windows plus the g++ compiler:
  • sudo apt-get install xorg-dev g++ xgraph
4.  Edit line 6304 of "otcl-1.13/configure"  from SHLIB_LD="gcc -shared" to SHLIB_LD="ld -shared"

5. Now run command in terminal : 
  • $  ./install
6. Set environment variables
  • $ gedit ~/.bashrc
7. Add the following lines to the end of the file. Remember replace “/your/path” by the folder where you have     stored extracted the ns-2 file (For example, if your Linux account name is blackpearl, and you have
    extracted  the file to your home directory, you have to change /your path to /home/blackpearl).

# LD_LIBRARY_PATH
OTCL_LIB=/your/path/ns-allinone-2.35/otcl-1.14
NS2_LIB=/your/path/ns-allinone-2.35/lib
X11_LIB=/usr/X11R6/lib
USR_LOCAL_LIB=/usr/local/lib
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$OTCL_LIB:$NS2_LIB:$X11_LIB:$USR_LOCAL_LIB
# TCL_LIBRARY
TCL_LIB=/your/path/ns-allinone-2.35/tcl8.5.10/library
USR_LIB=/usr/lib
export TCL_LIBRARY=$TCL_LIB:$USR_LIB
# PATH
XGRAPH=/your/path/ns-allinone-2.35/bin:/your/path/ns-allinone-2.35/tcl8.5.10/unix:/your/path/ns-allinone-2.35/tk8.5.10/unix
NS=/your/path/ns-allinone-2.35/ns-2.35/
NAM=/your/path/ns-allinone-2.35/nam-1.15/
export PATH=$PATH:$XGRAPH:$NS:$NAM

8. Ensure that it immediately takes effect:
  • $ source ~/.bashrc
9. You can test the installation by doing the following:
  • $ cd ns-2.35
  • $ ./validate