Friday, July 5, 2013

Overhearing Packets (or) Entering a node into Promiscuous Mode in NS-2

This post is an extension to the broadcast example. In this, I am going to explain how a node can be entered into promiscuous mode so that it can overhear the packets sent, forward or received by neighboring nodes. It all require a class called Tap which is available in mac.h header file. Tap class offer a function called void tap(const Packet *p).  To define the tap function, we need to inherit the class Tap. Usage of tap function and Tap class has shown with the broadcast example.

/* This Protocol perform Simple broad cast and overhear the packets of neighboring nodes
 * sbcast.h
 *
 *  Created on: 19-May-2013
 *      Author: P. RAGHU VAMSI
 *      @ JAYPEE INSTITUTE OF INFORMATION TECHNOLOGY UNIVERSITY, INDIA
 *      @ prvonline@yahoo.co.in
 */

#ifndef SBCAST_H_
#define SBCAST_H_

// Include mac header to overhear
#include

#define CURRENT_TIME Scheduler::instance().clock()

#define MAX_NODES 20

#define JITTER (Random::uniform()*0.5)
#define CURRENT_TIME Scheduler::instance().clock()
#define HDR_BEACON(p) (hdr_beacon *) hdr_beacon::access(p)

struct hdr_beacon {
nsaddr_t addr_;
u_int8_t seq_num_;
inline nsaddr_t & addr() { return addr_; }
inline u_int8_t & seq_num() { return seq_num_; }
static int offset_;
inline static int & offset() { return offset_; }
inline static hdr_beacon * access(const Packet *p) {
return (hdr_beacon*) p->access(offset_);
}
};


class SBAgent;

class BcastTimer : public TimerHandler {
protected:
SBAgent *agent_;
virtual void expire(Event *e);
public:
BcastTimer(SBAgent *agent):TimerHandler(),agent_(agent) { }
};





class SBAgent : public Tap,public Agent {
protected:
friend class BcastTimer;
private:
BcastTimer btimer_;
PortClassifier *dmux_;
Trace *logtarget_;
nsaddr_t my_addr_;
int seq_num_;
int node_count;
// for obtaining the mac of the node
Mac *mac_;
public:
static int pkt_received[MAX_NODES];
static int pkt_send[MAX_NODES];
static int no_of_nodes;
static int color_count;

SBAgent();
int command(int,const char*const*);
void recv(Packet *,Handler *);
void sendBeacon();
void resetBcastTimer();
inline nsaddr_t & my_addr() { return my_addr_;}
void changeColor();
//Tap to overhear the packets (or) to enter into promiscous mode
void tap(const Packet *);
};

#endif /* SBCAST_H_ */

sbcast.cc

/*
 * sbcast.cc
 * This Protocol perform Simple broad cast
 *  Created on: 19-May-2013
 *      Author: P. RAGHU VAMSI
 *      @ JAYPEE INSTITUTE OF INFORMATION TECHNOLOGY UNIVERSITY, INDIA
 *      @ prvonline@yahoo.co.in
 */

#include "sbcast.h"
#include "mobilenode.h"
// TCL Hooks

int hdr_beacon::offset_;

static class SBcastHeaderClass : public PacketHeaderClass {
public:
SBcastHeaderClass():PacketHeaderClass("PacketHeader/SB",sizeof(hdr_beacon)) {
bind_offset(&hdr_beacon::offset_);
}
}class_hdr_sbcast;

static class SBcastClass : public TclClass {
public:
SBcastClass():TclClass("Agent/SB") { }
TclObject *create(int argc,const char*const* argv) {
return (new SBAgent());
}
virtual void bind();   // for access of static variables
virtual int method(int argc, const char*const* argv);
}class_sbagent;

int SBAgent::pkt_received[MAX_NODES];
int SBAgent::pkt_send[MAX_NODES];
int SBAgent::no_of_nodes;
int SBAgent::color_count;

void SBcastClass::bind() {
TclClass::bind();
add_method("print-stats");
}

int SBcastClass::method(int ac, const char*const* av) {
    int argc = ac - 2;
    const char*const* argv = av + 2;
    if (argc == 2) {
    if(strcmp(argv[1],"print-stats")==0){

for(int i=0;
i          printf("Packets Sent By Node %d : %d \n",i,SBAgent::pkt_send[i]);
          printf("Packets Received By Node %d : %d \n",i,SBAgent::pkt_received[i]);
 

            }
    }
    return TCL_OK;
    }
}


SBAgent::SBAgent():Agent(PT_SB),btimer_(this) {
bind("node_count",&node_count);
no_of_nodes = node_count;
}

int SBAgent::command(int argc,const char*const* argv) {
if(argc==2){
if(strcmp(argv[1],"start")==0){
my_addr_ = addr();
return TCL_OK;
}
if(strcmp(argv[1],"base-station")==0){
btimer_.resched((double)0.1);
my_addr_ = addr();
return TCL_OK;
}
}else if (argc == 3) {
// Obtains corresponding dmux to carry packets to upper layers
if (strcmp(argv[1], "port-dmux") == 0) {
dmux_ = (PortClassifier*)TclObject::lookup(argv[2]);
if (dmux_ == 0) {
fprintf(stderr, "%s: %s lookup of %s failed\n",
__FILE__,
argv[1],
argv[2]);
return TCL_ERROR;
}
return TCL_OK;
}

if (strcmp(argv[1], "log-target") == 0 ||
strcmp(argv[1], "tracetarget") == 0) {
logtarget_ = (Trace*)TclObject::lookup(argv[2]);
if (logtarget_ == 0)
return TCL_ERROR;
return TCL_OK;
}
/* Add a command to install tap on a mac layer of a node */
if (strcmp(argv[1], "install-tap") == 0) {
  mac_ = (Mac*) TclObject::lookup(argv[2]);
  mac_->installTap(this);
  return TCL_OK;
   }
}
return (Agent::command(argc,argv));
}

void BcastTimer::expire(Event *e) {
agent_->sendBeacon();
agent_->changeColor();
agent_->resetBcastTimer();
}

void SBAgent::resetBcastTimer() {
btimer_.resched((double)0.5);

}

void SBAgent::sendBeacon() {
Packet* p = allocpkt();
struct hdr_cmn* ch = HDR_CMN(p);
struct hdr_ip* ih = HDR_IP(p);
struct hdr_beacon * ph = HDR_BEACON(p);

ph->addr() = my_addr();
ph->seq_num() = seq_num_++;

ch->ptype() = PT_SB;
ch->direction() = hdr_cmn::DOWN;
ch->size() = IP_HDR_LEN;
ch->error() = 0;
ch->next_hop() = IP_BROADCAST;
ch->addr_type() = NS_AF_INET;

ih->saddr() = my_addr();
ih->daddr() = IP_BROADCAST;
ih->sport() = RT_PORT;
ih->dport() = RT_PORT;
ih->ttl() = IP_DEF_TTL;

pkt_send[my_addr()]++;
send(p,0);
}

void SBAgent::recv(Packet *p,Handler *h) {

struct hdr_cmn *ch = HDR_CMN(p);
if(ch->ptype() == PT_SB) {
pkt_received[my_addr()]++;
}

}

void SBAgent::changeColor() {
char *color[5] = {"blue","brown","red","yellow","purple"};
Tcl& tcl = Tcl::instance();
tcl.evalf("%s set node_", name());
const char *node_object = tcl.result();
 Tcl::instance().evalf("$ns at %f \"%s color %s\"",CURRENT_TIME,
node_object,color[color_count]);

 if(color_count >= 4) color_count=0;
  else color_count++;
}

/* Define the tap function to overhear the packets (or) to enter
 * into promiscuos mode.
 */
void SBAgent::tap(const Packet *p) {
struct hdr_cmn* ch = HDR_CMN(p);
struct hdr_beacon * ph = HDR_BEACON(p);

printf("\n Node: %d IN TAP: from %d Seq Number: %d Packet Type: %d",my_addr(),ph->addr_,ph->seq_num_,ch->ptype());


}


bcast.tcl

#===================================
#     Simulation parameters setup
#===================================
set val(chan)   Channel/WirelessChannel    ;# channel type
set val(prop)   Propagation/TwoRayGround   ;# radio-propagation model
set val(netif)  Phy/WirelessPhy            ;# network interface type
set val(mac)    Mac/802_11                 ;# MAC type
set val(ifq)    Queue/DropTail/PriQueue    ;# interface queue type
set val(ll)     LL                         ;# link layer type
set val(ant)    Antenna/OmniAntenna        ;# antenna model
set val(ifqlen) 50                         ;# max packet in ifq
set val(nn)     5                         ;# number of mobilenodes
set val(rp)     SB                      ;# routing protocol
set val(ie)     100     ; # initial energy of a node
set val(em)     EnergyModel     ; # Energy model 
set val(x)      100                      ;# X dimension of topography
set val(y)      100                      ;# Y dimension of topography
set val(stop)   50 

Agent/SB set node_count $val(nn)

#===================================
#  Attaching selected headers    
#===================================

remove-all-packet-headers
add-packet-header Mac LL IP ARP LL SB

#===================================
#        Initialization        
#===================================
#Create a ns simulator
set ns [new Simulator]

#Setup topography object
set topo       [new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)


#Open the NS trace file
set tracefile [open bcast.tr w]
$ns trace-all $tracefile

#Open the NAM trace file
set namfile [open bcast.nam w]
$ns namtrace-all $namfile
$ns namtrace-all-wireless $namfile $val(x) $val(y)

set chan [new $val(chan)];#Create wireless channel

Mac/802_11 set dataRate 512Kbps

#===================================
#     Node parameter setup
#===================================
$ns node-config -adhocRouting  $val(rp) \
                -llType        $val(ll) \
                -macType       $val(mac) \
                -ifqType       $val(ifq) \
                -ifqLen        $val(ifqlen) \
                -antType       $val(ant) \
                -propType      $val(prop) \
                -phyType       $val(netif) \
                -channel       $chan \
                -topoInstance  $topo \
                -agentTrace    ON \
                -routerTrace   ON \
                -macTrace      ON \
                -movementTrace OFF \
-energyModel   $val(em) \
-initialEnergy  $val(ie) \
-rxPower  35.25e-23 \
-txPower 31.21e-23 \
-idlePower 712e-6 \
-sleepPower 144e-9 

#===================================
#        Nodes Definition        
#===================================

for {set i 0} {$i < $val(nn)} {incr i} {
 set node_($i) [$ns node] 
 $node_($i) color blue
}

for {set i 0} {$i < $val(nn)} {incr i} {
 set u_($i) [new Agent/SB]
 $ns attach-agent $node_($i) $u_($i)
}


$node_(0) set X_ 0.0
$node_(0) set Y_ 0.0
$node_(0) set Z_ 0
$node_(1) set X_ 40.0
$node_(1) set Y_ 0.0
$node_(1) set Z_ 0
$node_(2) set X_ 25.0
$node_(2) set Y_ 0.0
$node_(2) set Z_ 0
$node_(3) set X_ 0.0
$node_(3) set Y_ 75.0
$node_(3) set Z_ 0
$node_(4) set X_ 60.0
$node_(4) set Y_ 20.0
$node_(4) set Z_ 0



#$ns at 1.0 "$node_(0) setdest 99.0 99.0 15.0"
for {set i 0} {$i < $val(nn)} {incr i} {
$ns at 0.0 "[$node_($i) set ragent_] base-station"
}


for {set i 0} {$i < $val(nn)} {incr i} {
 $ns initial_node_pos $node_($i) 10  
}

for {set i 0} {$i < $val(nn)} {incr i} {
[$node_($i) set ragent_] install-tap [$node_($i) set mac_(0)]
}


proc finish {} {
    global ns tracefile namfile 
    $ns flush-trace
    close $tracefile
    close $namfile
    Agent/SB print-stats
    exec nam bcast.nam &
    exit 0
}

#===================================
#  Reset the nodes   
#===================================

for {set i 0} {$i < $val(nn) } { incr i } {
    $ns at $val(stop) "$node_($i) reset"
}

#===================================
#  Simulation start up  
#===================================

$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
puts "before sim run"
$ns run


Wednesday, June 19, 2013

My First NS-2 Teaching Experiance

Network Simulator NS-2 is a tough one to understand for beginners in the field of network simulation. Due to its credibility in the research community most of the researchers look forward to implement and realize their ideas on this simulator. I am no exception for this. As a major task of learning simulation and emulation tools in this semester, I have started learning and practicing this simulation tool along with TinyOs, nesC and TOSSIM. Unfortunately, I got an opportunity to conduct a mini workshop on NS-2 to my peers for three days. This workshop has conducted during 17-19 June 2010. However, I am very glad to work on chalking out required lesson plan for three day to conduct workshop smoothly. Finally, I came out with the following agenda.


Day 1 (17.06.2013)

Introduction to Simulation
           Discrete Event System Simulation
Simulation Tools available for computer network simulation
          Available tools, their pros and cons
Review of Network Protocol Stacks
          ISO-OSI, TCP/IP
NS-2 Installation and setup with Eclipse
           TCL scripting
           Tcl and OTcl Basics
           Writing TCL Scripts
NS-2 Trace formats (Wired and Wireless)
Introduction to AWK programming
          AWK basics
          Writing AWK scripts to analyze Trace formats
Network Simulator NS-2 Basics
Packets, Packet Headers and Header Formats

Day 2 (18.06.2013)

Recap of Day 1
Creating User Defined Agents in NS-2
           Working with TclObject, TclClass, and Agent classes
           Writing Tcl Script for using user defined agent
Simulating Wireless Networks
           Writing Tcl Script for simulating wireless networks
Introduction to STL in C++
           Utility classes (Map, Vector and Iterater classes)
Writing User Defined Routing Algorithms in NS-2
          Review – Packet, Packet Header and Header Formats
          Review – Agents and related classes
          Working with Timers
Writing Tcl Script for simulating user defined routing algorithm

Day 3 (19.06.2013)

Project – Implementing Greedy Pare meter Stateless Routing (GPSR Algorithm)
Conclusion


During this workshop my colleges (co-researchers)  have gained an insight in learning this tough tool. In addition, I have exposed to various search direction to use the simulators to the extent possible and my weak areas to strength up in network simulation with the help of their interaction and discussions.
I request the readers of this post to make comment on the course content for improvements, enhancements, suggestions, schedules, etc ( any other word in synonym) which greatly improve the credibility of teaching NS-2.  

Error Setting Color to a node dynamically - Solution

In ns-2.35, while setting node colors dynamically I faced the following error.


 _o14 color blue: can't read "attr_(COLOR)": no such variable
    while executing
"eval list "n -t [format "%.15g" [$ns now]] -s $id_ -S COLOR -c $color -o $attr_(COLOR) -i $color -I $attr_(LCOLOR)""
    invoked from within
"if [$ns is-started] {

$ns puts-nam-config  [eval list "n -t [format "%.15g" [$ns now]] -s $id_ -S COLOR -c $color -o $attr_(COLOR) -i $color -I $attr..."
    (procedure "_o14" line 6)
    (Node color line 6)
    invoked from within
"_o14 color blue"

The above solution can be rectified by 

1. Set a default node color to all nodes at the time of creating nodes.

2. Make sure that node color need to be set with 

$ns at

Example

set ns [new Simulator]

for {set i 0} {$i < $val(nn)} {incr i} {
 set node_($i) [$ns node] 
 $node_($i) color blue   ;# setting up a default color
}

$ns at 0.1 "$node_(0) color green"
$ns at 0.1 "$node_(0) color red"



Sunday, June 16, 2013

AWK to analyze trace files

In this post I am going to present analyzing NS-2 trace file with AWK script. For this, let consider the trace file obtained from the post "Creating Broadcast agents in NS-2". AWK script consists of three blocks BEGIN - where global variables are placed, logic - which are enclosed in simple flower braces ({}) for writing the logic and END - to print the results obtained by running logic.

As the output of simulation are placed in the trace file in column wise. We need to read the column to analyse the results.

let name the following file as bcast.awk


BEGIN {
rsent[4] = 0; #array to hold router sent packets
msent[4] = 0; #array to hold mac sent packets
rrecv[4] = 0; #array to hold router receive packets
mrecv[4] = 0; #array to hold mac receive packets
}
{
#column 1 of trace file representing event such as send, receive etc
event = $1;
#column 3 of trace file represent node number
node = $3;
#column 4 of trace file represent level - Router (RTR), Mac (MAC) etc
level = $4;
# increment the packet count if event is send and level is RTR
if(event == "s" && level == "RTR") {
if(node == "_0_")
rsent[0]++;
else if(node == "_1_")
rsent[1]++;
else if(node == "_2_")
rsent[2]++;
else if(node == "_3_")
rsent[3]++;
}
# increment the packet count if event is send and level is MAC
if(event == "s" && level == "MAC") {
if(node == "_0_")
msent[0]++;
else if(node == "_1_")
msent[1]++;
else if(node == "_2_")
msent[2]++;
else if(node == "_3_")
msent[3]++;
}
# increment the packet count if event is receive and level is RTR
if(event == "r" && level == "RTR") {
if(node == "_0_")
rrecv[0]++;
else if(node == "_1_")
rrecv[1]++;
else if(node == "_2_")
rrecv[2]++;
else if(node == "_3_")
rrecv[3]++;
}
# increment the packet count if event is receive and level is MAC
if(event == "r" && level == "MAC") {
if(node == "_0_")
mrecv[0]++;
else if(node == "_1_")
mrecv[1]++;
else if(node == "_2_")
mrecv[2]++;
else if(node == "_3_")
mrecv[3]++;
}
}
END {
# Print the result
for(i=0;i<4 b="" i="">
printf ("Routing Packets Sent by Node %d : %d \n",i,rsent[i]);
}
for(i=0;i<4 b="" i="">
printf ("Routing Packets Received by Node %d : %d \n",i,rrecv[i]);
}
for(i=0;i<4 b="" i="">
printf ("Mac Packets Sent by Node %d : %d \n",i,msent[i]);
}
for(i=0;i<4 b="" i="">
printf ("Mac Packets Received by Node %d : %d \n",i,mrecv[i]);
}
}

Save and close file

run the file as follows

$ awk -f bcast.awk out.tr

and see the result


Saturday, June 15, 2013

Creating Broad Cast Agent in NS-2 - Continued....

This post is with reference to post title "Creating Broad Cast Agent in NS-2", I am going to present small modification to the existing one. In the previous post all the nodes will broadcast the beacon messages  periodically. A modification to this, the problem situation is as follows: There is a base station which   transmit a beacon message periodically so that all other client nodes has to receive the beacon message. In this situation we need to make a node as base station and all other nodes as clients.

Here are the modifications to the existing code.

In the SBAgent::command method definition, modify code as

if(argc==2){
if(strcmp(argv[1],"start")==0){
my_addr_ = addr();
return TCL_OK;
}
if(strcmp(argv[1],"base-station")==0){
btimer_.resched((double)0.1);
my_addr_ = addr();
return TCL_OK;
}
}

  and Recompile the code.

./configure
make
sudo make install 

In the tcl script add the line which indicated in RED under node definition section



#===================================
#        Nodes Definition      
#===================================

for {set i 0} {$i < $val(nn)} {incr i} {
 set node_($i) [$ns node]
}

for {set i 0} {$i < $val(nn)} {incr i} {
 set u_($i) [new Agent/SB]
 $ns attach-agent $node_($i) $u_($i)
}

$ns at 0.0 "[$node_(0) set ragent_] base-station"


Save and run the file


Thursday, May 23, 2013

How to write a good discussion

Here is some interesting presentation about "How to write a good discussion in research papers and dissertations": follow the link

http://www.slideshare.net/GerardPaulSharpling/writing-a-good-discussion-gs-may-2013

Saturday, May 18, 2013

Creating a Broadcast Agent in NS-2

In this post I am going to explain how a broadcast agent can be created. The agent will broadcast beacon message consisting of node id and packet sequence number. This broadcast takes place periodically using timers. The over all use of entire code is to create an agent which will broadcast beacon messages periodically. This agent will not receive any messages, however, it broadcast messages.

:~/ns-allinone-2.35/ns-2.35$ mkdir sbcast
:~/ns-allinone-2.35/ns-2.35/sbcast$


/* This Protocol perform Simple broad cast
 * sbcast.h
 *
 *  Created on: 19-May-2013
 *      Author: P. RAGHU VAMSI
 *      @ JAYPEE INSTITUTE OF INFORMATION TECHNOLOGY UNIVERSITY, INDIA
 *      @ prvonline@yahoo.co.in
 */

#ifndef SBCAST_H_
#define SBCAST_H_




#include "agent.h"
#include "classifier-port.h"
#include "ip.h"
#include "packet.h"
#include "cmu-trace.h"




#define CURRENT_TIME Schedular::instance().clock()
#define HDR_BEACON(p) (hdr_beacon *) hdr_beacon::access(p)

// Beacon packet header
struct hdr_beacon {
nsaddr_t addr_;
u_int8_t seq_num_;
inline nsaddr_t & addr() { return addr_; }
inline u_int8_t & seq_num() { return seq_num_; }
static int offset_;
inline static int & offset() { return offset_; }
inline static hdr_beacon * access(const Packet *p) {
return (hdr_beacon*) p->access(offset_);
}
};

// Simple Broadcast Agent
class SBAgent;


//Broadcast Timer class
class BcastTimer : public TimerHandler {
protected:
SBAgent *agent_;
virtual void expire(Event *e);
public:
BcastTimer(SBAgent *agent):TimerHandler(),agent_(agent) { }
};


class SBAgent : public Agent {
protected:
friend class BcastTimer;
private:
BcastTimer btimer_;
PortClassifier *dmux_;
Trace *logtarget_;
nsaddr_t my_addr_;
int seq_num_;
public:
SBAgent();
int command(int,const char*const*);
void recv(Packet *,Handler *);
void sendBeacon();
void resetBcastTimer();
inline nsaddr_t & my_addr() { return my_addr_;}
};
#endif /* SBCAST_H_ */


------------------------------------------------------------------------------------------------


/*
 * sbcast.cc
 * This Protocol perform Simple broad cast
 *  Created on: 19-May-2013
 *      Author: P. RAGHU VAMSI
 *      @ JAYPEE INSTITUTE OF INFORMATION TECHNOLOGY UNIVERSITY, INDIA
 *      @ prvonline@yahoo.co.in
 */

#include "sbcast.h"

// TCL Hooks

int hdr_beacon::offset_;

static class SBcastHeaderClass : public PacketHeaderClass {
public:
SBcastHeaderClass():PacketHeaderClass("PacketHeader/SB",sizeof(hdr_beacon)) {
bind_offset(&hdr_beacon::offset_);
}
}class_hdr_sbcast;

static class SBcastClass : public TclClass {
public:
SBcastClass():TclClass("Agent/SB") { }
TclObject *create(int argc,const char*const* argv) {
return (new SBAgent());
}
}class_sbagent;

SBAgent::SBAgent():Agent(PT_SB),btimer_(this) { }

int SBAgent::command(int argc,const char*const* argv) {
if(argc==2){
if(strcmp(argv[1],"start")==0){
                       // Reschedule the timer for every 0.1 seconds
btimer_.resched((double)0.1);
my_addr_ = addr();
return TCL_OK;
}
}else if (argc == 3) {
// Obtains corresponding dmux to carry packets to upper layers
if (strcmp(argv[1], "port-dmux") == 0) {
dmux_ = (PortClassifier*)TclObject::lookup(argv[2]);
if (dmux_ == 0) {
fprintf(stderr, "%s: %s lookup of %s failed\n",
__FILE__,
argv[1],
argv[2]);
return TCL_ERROR;
}
return TCL_OK;
}

if (strcmp(argv[1], "log-target") == 0 ||
strcmp(argv[1], "tracetarget") == 0) {
logtarget_ = (Trace*)TclObject::lookup(argv[2]);
if (logtarget_ == 0)
return TCL_ERROR;
return TCL_OK;
}
}
return (Agent::command(argc,argv));
}

void BcastTimer::expire(Event *e) {
agent_->sendBeacon();
agent_->resetBcastTimer();
}

void SBAgent::resetBcastTimer() {
   // Reschedule the timer for every 0.1 seconds
btimer_.resched((double)0.1);
}

void SBAgent::sendBeacon() {
Packet* p = allocpkt();
struct hdr_cmn* ch = HDR_CMN(p);
struct hdr_ip* ih = HDR_IP(p);
struct hdr_beacon * ph = HDR_BEACON(p);

ph->addr() = my_addr();
ph->seq_num() = seq_num_++;

ch->ptype() = PT_SB;
ch->direction() = hdr_cmn::DOWN;
ch->size() = IP_HDR_LEN;
ch->error() = 0;
ch->next_hop() = IP_BROADCAST;
ch->addr_type() = NS_AF_INET;

ih->saddr() = my_addr();
ih->daddr() = IP_BROADCAST;
ih->sport() = RT_PORT;
ih->dport() = RT_PORT;
ih->ttl() = IP_DEF_TTL;

send(p,0);
}

void SBAgent::recv(Packet *p,Handler *h) {
}


---------------------------------------------------------------------------------------------------

Perform additions in the following files


Add entry in ns-2.35/Makefile.in

:~/ns-allinone-2.35/ns-2.35$ gedit Makefile.in

Make entry in OBJ_CC
OBJ_CC = sbcast/sbcast.o \

:~/ns-allinone-2.35/ns-2.35$ cd common

:~/ns-allinone-2.35/ns-2.35/common$ gedit packet.h

add the packet PT_SB



static const packet_t PT_SB = 74;
        // insert new packet types here
static packet_t       PT_NTYPE = 75; // This MUST be the LAST one

make entry in the function


static bool data_packet(packet_t type) {
return ( (type) == PT_TCP || \
        (type) == PT_TELNET || \
        (type) == PT_CBR || \
        (type) == PT_AUDIO || \
        (type) == PT_VIDEO || \
        (type) == PT_ACK || \
        (type) == PT_SCTP || \
        (type) == PT_SCTP_APP1 || \
            (type) == PT_SB || \
        (type) == PT_HDLC \
       );
}


provide meaning of packet in the same file


name_[PT_SB] = "SB";
name_[PT_NTYPE]= "undefined";



close packet.h

:~/ns-allinone-2.35/ns-2.35$ cd queue
:~/ns-allinone-2.35/ns-2.35/queue$ gedit priqueue.cc

add the following in switch case



case PT_SB:
recvHighPriority(p, h);
                        break;


close priqueue.cc




:~/ns-allinone-2.35/ns-2.35$ cd tcl/lib/
:~/ns-allinone-2.35/ns-2.35/tcl/lib$ gedit ns-lib.tcl


 SB {
set ragent [$self create-sb-agent $node]
   }



Simulator instproc create-sb-agent { node } {
        #  Create AODV routing agent
set ragent [new Agent/SB [$node node-addr]]
        $self at 0.0 "$ragent start"     ;# start BEACON/HELLO Messages
        $node set ragent_ $ragent
        return $ragent
}



save and close ns-lib.tcl

:~/ns-allinone-2.35/ns-2.35/tcl/lib$ gedit ns-agent.tcl

Agent/SB instproc init args {
         $self next $args
}

save and close ns-agent.tcl


:~/ns-allinone-2.35/ns-2.35/tcl/lib$ gedit ns-packet.tcl

make an entry for SB

SB

save and close ns-packet.tcl

:~/ns-allinone-2.35/ns-2.35$ ./configure
:~/ns-allinone-2.35/ns-2.35$ make
:~/ns-allinone-2.35/ns-2.35$ sudo make install

TCL script for running the  simulation


#===================================
#     Simulation parameters setup
#===================================
set val(chan)   Channel/WirelessChannel    ;# channel type
set val(prop)   Propagation/TwoRayGround   ;# radio-propagation model
set val(netif)  Phy/WirelessPhy            ;# network interface type
set val(mac)    Mac/802_11                 ;# MAC type
set val(ifq)    Queue/DropTail/PriQueue    ;# interface queue type
set val(ll)     LL                         ;# link layer type
set val(ant)    Antenna/OmniAntenna        ;# antenna model
set val(ifqlen) 50                         ;# max packet in ifq
set val(nn)     5                         ;# number of mobilenodes
set val(rp)     SB                      ;# routing protocol
set val(ie) 100   ; # initial energy of a node
set val(em) EnergyModel   ; # Energy model 
set val(x)      100                      ;# X dimension of topography
set val(y)      100                      ;# Y dimension of topography
set val(stop)   10 

#===================================
# Attaching selected headers    
#===================================

remove-all-packet-headers
add-packet-header Mac LL IP ARP LL SB

#===================================
#        Initialization        
#===================================
#Create a ns simulator
set ns [new Simulator]

#Setup topography object
set topo       [new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)


#Open the NS trace file
set tracefile [open out.tr w]
$ns trace-all $tracefile

#Open the NAM trace file
set namfile [open out.nam w]
$ns namtrace-all $namfile
$ns namtrace-all-wireless $namfile $val(x) $val(y)
set chan [new $val(chan)];#Create wireless channel

Mac/802_11 set dataRate 512Kbps

#===================================
#     Node parameter setup
#===================================
$ns node-config -adhocRouting  $val(rp) \
                -llType        $val(ll) \
                -macType       $val(mac) \
                -ifqType       $val(ifq) \
                -ifqLen        $val(ifqlen) \
                -antType       $val(ant) \
                -propType      $val(prop) \
                -phyType       $val(netif) \
                -channel       $chan \
                -topoInstance  $topo \
                -agentTrace    ON \
                -routerTrace   ON \
                -macTrace      OFF \
                -movementTrace OFF \
-energyModel   $val(em) \
-initialEnergy  $val(ie) \
-rxPower 35.25e-23 \
-txPower 31.21e-23 \
-idlePower 712e-6 \
-sleepPower 144e-9 

#===================================
#        Nodes Definition        
#===================================

for {set i 0} {$i<$val(nn)} {incr i} {
set node_($i) [$ns node]
}

for {set i 0} {$i<$val(nn)} {incr i} {
set u_($i) [new Agent/SB]
$ns attach-agent $node_($i) $u_($i)
}


$node_(0) set X_ 0.0
$node_(0) set Y_ 0.0
$node_(0) set Z_ 0
$node_(1) set X_ 40.0
$node_(1) set Y_ 0.0
$node_(1) set Z_ 0
$node_(2) set X_ 25.0
$node_(2) set Y_ 0.0
$node_(2) set Z_ 0
$node_(3) set X_ 0.0
$node_(3) set Y_ 75.0
$node_(3) set Z_ 0
$node_(4) set X_ 60.0
$node_(4) set Y_ 20.0
$node_(4) set Z_ 0

for {set i 0} {$i < $val(nn)} {incr i} {
$ns initial_node_pos $node_($i) 10
}


proc finish {} {
    global ns tracefile namfile 
    $ns flush-trace
    close $tracefile
    close $namfile
    exec nam out.nam &
    exit 0
}

#===================================
# Reset the nodes   
#===================================

for {set i 0} {$i < $val(nn) } { incr i } {
    $ns at $val(stop) "$node_($i) reset"
}

#===================================
# Simulation start up  
#===================================

$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
puts "before sim run"
$ns run