Sunday 2 November 2014

Installing ns-2.35 on Mountain Lion, Mavericks and Yosemite (OS X 10.8/9/10)


Here i will provide step by step procedure for you to install ns-2.35 on mac OS X 10.8/9/10 which i successfully installed on my mac (fully tested by me and its working)


Credits:- ISI, Brain Adamson(for great patch) ,Henrique Zelak Leite Bastos for the right help and last but not the least APPLE for Mac OS X.(the best a dev. can get)



1. Enabling root user. (not a necessary step, you can skip if you want)

Enable root by following these steps http://support.apple.com/kb/PH11331


2. Download files and install them.


   a. Download ns 2.35 from  http://sourceforge.net/projects/nsnam/files/allinone/ns-allinone-2.35/ns-allinone-2.35.tar.gz/download


   b. Download XCODE from app store and install command line tools from preferences of XCODE (not needed for XCODE 5 or later).


   c. Download XQuartz from http://xquartz.macosforge.org/ (this installs X11 libraries)
install and reboot .


3. Choose install directory.

Place the downloaded ns-allione-2.35.tar.gz file in the location you want to install it. 


4. Extract ns files.

Go to location where you have put your downloaded ns file and run 

tar zxvf ns-allinone-2.35.tar.gz 


6.  Get into the Directory.

Execute  cd ns-allinone-2.35


7. Download Patch.

Download zip file from https://github.com/aemreunal/ns-allinone-2.35-Mac-OS-10.9-install-patch . Extract and put these files in ns-allinone-2.35 directory.


8. Execute command

Execute sudo ./install64 (will give paths after completion. Copy them)


9. Save Paths.


So now we save them properly. Come back to your user/home directory and run

touch ~/.bash_profile (if you dont have a bash_profile file in your home directory).
open ~/.bash_profile (opens bash_profile file in textEdit).

now enter the paths like 

export PATH=$PATH:path1:path2:path3( Here paths should be separated by colon)

similarly for

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:path1:path2( Here paths should be separated by colon)

and also for

export TCL_LIBRARY=$TCL_LIBRARY:path 


Save and Exit. Now run

source ~/.bash_profile 

Type nam and .... Bingo!!! if you see the nam window.(or else recheck 9th step)

Tutorial to implement protoname in ns2.35


This is an Implementation tutorial of new manet(Mobile Ad-hoc NETworks) unicast protocol name protoname.

The whole credit goes to Francisco J. Ros and Pedro M. Ruiz for their beautiful work and excellent explanation they provide. The link to their work is below. It contains a PDF file also which explains you in detail and I recommend you to go through it once.

List of files to be modified

  • ~/ns-allinone-2.35/ns-2.35/common/packet.h
  • ~/ns-allinone-2.35/ns-2.35/trace/cmu-trace.h
  • ~/ns-allinone-2.35/ns-2.35/trace/cmu-trace.cc
  • ~/ns-allinone-2.35/ns-2.35/tcl/lib/ns-packet.tcl
  • ~/ns-allinone-2.35/ns-2.35/tcl/lib/ns-default.tcl 
  • ~/ns-allinone-2.35/ns-2.35/tcl/lib/ns-lib.tcl
  • ~/ns-allinone-2.35/ns-2.35/queue/priqueue.cc

 
** Note: Text in red is the part that is to be added or modified in given file and location and purple colour denotes the terminal commands.

** Note: mod stands for modification.

** Note: Line number is approx and is provided for your convenience. Please check the methods below and above before inserting.

Step 1:

download protoname.rar

http://www.cs.nccu.edu.tw/~g10031/protoname.rar

Extract the files and place them in ~/ns-allinone-2.35/ns-2.35/protoname directory(create the directory if not present)

Step 2:

gedit ~/ns-allinone-2.35/ns-2.35/common/packet.h (mods at 3 places)

  • a.       its somewhere near line 200

static const packet_t PT_DCCP = 63;
static const packet_t PT_DCCP_REQ = 64;
static const packet_t PT_DCCP_RESP = 65;
static const packet_t PT_DCCP_ACK = 66;
static const packet_t PT_DCCP_DATA = 67;
static const packet_t PT_DCCP_DATAACK = 68;
static const packet_t PT_DCCP_CLOSE  = 69;
static const packet_t PT_DCCP_CLOSEREQ = 70;
static const packet_t PT_DCCP_RESET = 71;

        // M-DART packets
static const packet_t PT_MDART = 72;

        // insert new packet types here

static const packet_t PT_PROTONAME = 73;

static packet_t       PT_NTYPE = 74; // This MUST be the LAST one


  • b. near line 250

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_HDLC || \  //(remember this mod also)
(type) == PT_PROTONAME \ 
       );

  • c.      near line 422
static void initName()
{
                .....
                name_[PT_DCCP_REQ]="DCCP_Request";
name_[PT_DCCP_RESP]="DCCP_Response";
name_[PT_DCCP_ACK]="DCCP_Ack";
name_[PT_DCCP_DATA]="DCCP_Data";
name_[PT_DCCP_DATAACK]="DCCP_DataAck";
name_[PT_DCCP_CLOSE]="DCCP_Close";
name_[PT_DCCP_CLOSEREQ]="DCCP_CloseReq";
name_[PT_DCCP_RESET]="DCCP_Reset";
name_[PT_PROTONAME]="protoname"; 
name_[PT_NTYPE]= "undefined";
}


save and close.

Step 3:  

gedit ~/ns-allinone-2.35/ns-2.35/trace/cmu-trace.h (mod at 1 place)

  • a. Near line 164.

class CMUTrace: public Trace {
public:
CMUTrace (const char * s, char t);
...
private:
char tracename [MAX_ID_LEN + 1];
int nodeColor [MAX_NODE];
...
void format_tora (Packet * p, int offset);
void format_imep (Packet * p, int offset);
void format_aodv (Packet * p, int offset);
/ / ----------------------------------------------
void format_protoname (Packet *p, int offset);
/ / ----------------------------------------------
void format_aomdv (Packet * p, int offset);
void format_mdart (Packet * p, int offset);

/ / This holds all the tracers added at run-time
static PacketTracer * pktTrc_;

};
# Endif / * __ cmu_trace__ * /

save and close.

Step 4:

gedit ~/ns-allinone-2.35/ns-2.35/trace/cmu-trace.cc (mods at 3 places)

  • a. Add this line at start

#include <protoname/protoname_pkt.h>

  • b. Near line 1168
void
CMUTrace :: format_mdart (Packet * p, int offset)  {

.........
........
........
}

void
CMUTrace::format_protoname(Packet *p, int offset)
{
    struct hdr_protoname_pkt* ph = HDR_PROTONAME_PKT(p);
    if (pt_->tagged())
    {
            sprintf(pt_->buffer() + offset, "-protoname:o %d -protoname:s %d -protoname:l %d ", ph->pkt_src(), ph->pkt_seq_num(), ph->pkt_len());
        }
    else if (newtrace_)
    {
            sprintf(pt_->buffer() + offset, "-P protoname -Po %d -Ps %d -Pl %d ", ph->pkt_src(), ph->pkt_seq_num(), ph->pkt_len());
        }
    else
    {
            sprintf(pt_->buffer() + offset, "[protoname %d %d %d] ", ph->pkt_src(), ph->pkt_seq_num(), ph->pkt_len());
        }
}



  • c. Near line 1477
void CMUTrace :: format (Packet * p, const char * why)
{...
switch (ch-> ptype ()) {
case PT_MAC:
...
case PT_GAF:
case PT_PING:
break;
/ / --------------------------------------------
case PT_PROTONAME:
format_protoname(p, offset);
break;
/ / --------------------------------------------
default:
...
}

save and close.

Step 5:

gedit ~/ns-allinone-2.35/ns-2.35/tcl/lib/ns-packet.tcl  (mod at 1 place)

  • a. Near line 172

# Mobility, Ad-Hoc Networks, Sensor Nets:
    AODV     # routing protocol for ad-hoc networks
    Protoname # new routing protocol for ad-hoc networks
    Diffusion     # diffusion/diffusion.cc
    IMEP     # Internet MANET Encapsulation Protocol, for ad-hoc

Save and close.

Step 6:

gedit ~/ns-allinone-2.35/ns-2.35/tcl/lib/ns-default.tcl  (mod at 1 place)

  • a. Add at the last.

# Defaults defined for Protoname
Agent/Protoname set accessible_var_ true


save and close.

step 7:

gedit ~/ns-allinone-2.35/ns-2.35/tcl/lib/ns-lib.tcl  (mod at 2 places)

  • a. Near line 671

switch-exact $ routingAgent_ {
...
ManualRtg {
set ragent [$ self create-manual-rtg-agent $
}
# / ------------------------------------------------ -
Protoname 
{
         set ragent [$self create-protoname-agent $node]

}
# / ------------------------------------------------ -
default {
...
}


  • b. Near line 2278

Simulator instproc create-omnimcast-agent {node} {
...
}
# / ------------------------------------------------ -----
Simulator instproc create-protoname-agent {node} {
    # Create Protoname routing agent
    set ragent [new Agent/Protoname [$node node-addr]]
    $self at 0.0 "$ragent start"
    $node set ragent_ $ragent
    return $ragent
}

# / ------------------------------------------------ -----
# XXX These are very simulation-specific methods, why should they belon
Simulator instproc put-in-list {agent} {
...
}


Step 8:

gedit ~/ns-allinone-2.35/ns-2.35/queue/priqueue.cc (mod at 1 place)

  • a. Near line 95.
void
PriQueue :: recv (Packet * p, Handler * h)
{
struct hdr_cmn * ch = HDR_CMN (p);

if (Prefer_Routing_Protocols) {
switch (ch-> ptype ()) {
...
case PT_MDART:
/ / --------------------------------------------
case PT_PROTONAME:
/ / --------------------------------------------
recvHighPriority (p, h);
break;
default:
Queue :: recv (p, h);
}
}
else {
Queue :: recv (p, h);
}
}

save and close.

Step 9:

gedit ~/ns-allinone-2.35/ns-2.35/Makefile (mod at 1 place)

  • a. Near line 336

OBJ_CC = \
tools / random.o tools / rng.o tools / ranvar.o common / misc.o common /
...
wpan/p802_15_4trace.o wpan/p802_15_4transac.o \
apps / pbc.o \
# / / ----------------------------------------------- -
protoname/protoname.o protoname/protoname_rtable.o \
# / / ----------------------------------------------- -
$ (OBJ_STL)

save and close.

Step 10:

build it now, changes done ( run these in terminal in ~/ns-allinone-2.35/ns-2.35 directory )

  • a. make clean
  • b. touch common/packet.cc
  • c. make

(if you are getting some errors check the spaces in the editing you did above)


Step 11:

gedit ~/ns-allinone-2.35/ns-2.35/test.tcl

copy and paste

set ns [new Simulator]
$ns node-config -Routing protoname   
set nf [open out.nam w]     
$ns namtrace-all $nf       
set nd [open out.tr w]       
$ns trace-all $nd             
  proc finish {} {
          global ns nf  nd
          $ns flush-trace 
          close $nf       
          close $nd       
          exec nam out.nam &
          exit 0
   }

for {set i 0} {$i < 7} {incr i} {set n($i) [$ns node] }
for {set i 0} {$i < 7} {incr i} {
$ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms DropTail
}
set udp0 [new Agent/UDP]   
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR] 
$cbr0 set packetSize_ 500     
$cbr0 set interval_ 0.005      
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(3) $null0
$ns connect $udp0 $null0 
$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"
$ns at 5.0 "finish"
$ns run


save and close

ns ~/ns-allinone-2.35/ns-2.35/test.tcl

and boom you are getting the nam (if not sorry troubleshoot once by going through the tutorial again as I am getting the outputs completely and so should you)

Expected Errors
  1. Got this error

    trace/cmu-trace.cc:1176: error: stray '\302' inprogram
    trace/cmu-trace.cc:1176: error: stray '\240' inprogram
    trace/cmu-trace.cc:1176: error: stray '\302' inprogram
    trace/cmu-trace.cc:1176: error: stray '\240' inprogram
    ...
    trace/cmu-trace.cc:1183: error: stray '\302' inprogram
    trace/cmu-trace.cc:1183: error: stray '\240' inprogram
     
    Solution
    check your cmu.trace.cc file... its a syntactic error.. see you inserted the changes in the right place with right syntax... I did my successfully not in just one attempt... errors come but you need to remove them ... be vigilant ... cheers!!!

  2. Thank you I solved that but still got this error

    trace/cmu-trace.cc:1120: error: stray _FUNCTION_ not declared

    How do I include the FUNCTION?

    Great tutorial! I have followed the orignal tutorial by Francisco J. Ros and Pedro M. Ruiz, and made some modifications to successfully compile it, after which I read your post and used the test script. I was wondering what "protoname" does exactly? I didn't know how to test it until I saw your post. So there must be something I didn't quite understand. Thanks :)

    Possible Question can you tell me what protoname does exactly ??

    Solution
    protoname does not implement any extra ordinary features , it just teaches you basics of creating a user defined protocol and how to add it to ns and use that protocol.

    You can read the .pdf file in the protoname folder. It explains everything in detail. first it pings the neighbours to locate them and then find the path.

  3. Possible Question
    how can i use SPIN routing protocol in wireless sensor network in ns2, i have SPIN code but don't know how to implement it....
     
    Solution
    read ns-manual . They have taught how to implement your own protocol (if SPIN is a user defined one).

  4. Hello..... nice to meet everyone...... I am working the project of black hole attack in AODV protcol. I want to know how can I add new packet type in AODV protocol. I write alarm packet type in aodv protocol such as Hello packet. I declare this packet in aodv_packet.h and then I write the send and receive fun in aodv.h. I use by calling this fun in aodv.cc. When I am compiling Ns-2, there is no error. But, when I run TCL script, there is error such as Invalid AODV pcket format. So, Anybody help me. How can I add alarm packet in aodv protocol??????

    trace your program control... use debugging tools


  5. hey i m getting dis error
    common/tclAppInit.o: In function `Tcl_AppInit':
    tclAppInit.cc:(.text+0xec): undefined reference to `et_ns_ptypes'
    collect2: error: ld returned 1 exit status
    make: *** [ns] Error 1re-check the changes you made.... especially in first 3 steps
     
  6. but following your instructions i got it working!
  7. but i was curious of step 11.. where exactly is the new implemented protocol being used?
    is it this line? $ns node-config -Routing protoname

    yup... try using AODV in place of protoname or DSDV...

How to color nodes in NS2

You can color the nodes in NS2. It is bit tricky to color them in a wireless network. We can do this by following code.

set node0 [$ns node]
$node0 color "blue"
$ns at 0.0 "$node0 color blue"

How to configure Eclipse for NS-2 (2.34) in Linux.


1) Install the NS2.

2) Make a backup copy of your NS2 folder, i.e. ns-allinone-2.34 somewhere so
    that you can reset the changes by replacing.
 
3) Download the Eclipse SDK 3.7.2 Indigo (Classic) from here. This file is
     approx. of size 174 MB.
 
4) Download the CDT from here. This file is approx. of size 44 MB.
 
5) Copy the "eclipse-SDK-3.7.2-linux-gtk.tar.gz" file to user folder (/home/user)
     and extract.
6) Open the eclipse and set the workspace as /home/user/ns-allinone-2.34.
 
7) Now in Eclipse go to Help->Install New Software... A window with name
    "install" will pop up. Then go to Add. Put the values as shown below.
    Name:- CDT
    Location:- Browse to the "cdt-master-6.0.2.zip" file.
 
8) Check "CDT Main Features" and "CDT Optional Features", click next,
    then accept license and finish. At last it will ask you to restart Eclipse, then
    choose Restart.
 
9) Now choose /home/user/ns-allinone-2.34 as workspace. Click New->C++
    Project. Put Project name:- ns-2.34 (It will warn you that a directory already
    exists. Just ignore it.). Choose Project type as make project->Empty project
    and Toolchains linux GCC and click finish.
 
10) Now go to Project->clean->clean projects selected below->ns-2.34 and OK.
 
11) Go to Project->Build All.
 
12) After build is completed without any error, go to Run->Run configurations.
      Double click C/C++ Application. For Project: browse to ns-2.34. Go to
      Search Project and click ns from Program selection window, then Apply and
      Run. If you get % sign in console, you are done.

13) (Optional) If you want to speed up the make time of NS2, just don't clean it,
       directly build all from Eclipse. It will get compiled in less than 5 seconds.
       All the best!

Terms Packet delivery ratio, Packet Lost, End to end delay

If you want to evaluate the performance of protocol using NS-2, first you have to define the evaluation criteria. This time I want to explore about Packet delivery ratio, packet lost and end to end delay.
What are they?
Packet delivery ratio : the ratio of the number of delivered data packet to the destination. This illustrates the level of delivered data to the destination.
∑ Number of packet receive / ∑ Number of packet send
The greater value of packet delivery ratio means the better performance of the protocol.
End-to-end Delay : the average time taken by a data packet to arrive in the destination. It also includes the delay caused by route discovery process and the queue in data packet transmission. Only the data packets that successfully delivered to destinations that counted.
∑ ( arrive time – send time ) / ∑ Number of connections
The lower value of end to end delay means the better performance of the protocol.
Packet Lost : the total number of packets dropped during the simulation.
Packet lost = Number of packet send – Number of packet received .
The lower value of the packet lost means the better performance of the protocol.
How to analyze trace file to find the result?
First : you must analyze the trace file with this Script PDR and E2ED
run this script with command :
awk -f PacketDeliveryRatio.awk (name trace file.tr)
awk -f Endtoenddelay.awk (name trace file.tr)

If error 
This is exactly what I need. However I couldn’t run the command. Probably I misunderstood something. On what file should I run “awk -f Endtoenddelay.awk (name trace file.tr)”
I downloaded the text file you provided, saved it as .awk file and run it like “awk -f pdr.awk ~/Desktop/mypackets.trace” but it returns all 0’s.

Solution
1. you must execute the awk files inside folder that contain your trace files.
2. please make sure that you are using new trace file format or old trace file format. you can check this type in your tcl schenario script.

how can i enable the new trace file format not the old one in the tcl script ?
You can changes it in your TCL file.
For example in this tcl files :
# wrls1.tcl
# A 3-node example for ad-hoc simulation with DSDV

# Define options
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) AODV ;# routing protocol
set val(x) 500 ;# X dimension of topography
set val(y) 400 ;# Y dimension of topography
set val(stop) 300 ;# time of simulation end

set ns [new Simulator]
set tracefd [open simple.tr w]
set windowVsTime2 [open win.tr w]
set namtrace [open simwrls.nam w]

$ns use-newtrace —————–> to enable new trace format
#$ns use-trace ——————-> if you delete tha “#” means that you enable old trace format
$ns trace-all $tracefd

#$ns new-trace-all $tracefd
$ns namtrace-all-wireless $namtrace $val(x) $val(y)

# set up topography object
set topo [new Topography]

$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)

If Division by zero error
Maybe there is problem in the variable definition.
Please check your trace files. Make sure that you use new trace format or old trace format.
After that changes the number of variable.
For Example:
Based on trace format bellow, the time variable is in row 3. so put $3 in your variable definition. In this case time=$3;

#Example of new trace format
#1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#s -t 1.142046604 -Hs 0 -Hd -2 -Ni 0 -Nx 1186.47 -Ny 1093.76 -Nz 0.00 -Ne 100.000000 -Nl AGT -Nw —
#
#22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#Ma 0 -Md 0 -Ms 0 -Mt 0 -Is 0.0 -Id 40.0 -It cbr -Il 512 -If 0 -Ii 3 -Iv 32 -Pn cbr -Pi 1 -Pf 0 -Po 16777215
event = $1;
time = $3;
node = $5;
type = $19;
reason = $21;
packetid = $41;
packettype = $35;
src = $31;
dst = $33;
cbr_packetid = $47;
numhops = $49;
opt_numhops = $51;
energy = $17;
 Possible error

Hi when i type this command for delay i don’t have any result what’s the problem ??
Please check your trace files. Make sure that you use new trace format or old trace format.
After that changes the number of variable.
For Example:
Based on trace format bellow, the time variable is in row 3. so put $3 in your variable definition. In this case time=$3;

#Example of new trace format
#1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#s -t 1.142046604 -Hs 0 -Hd -2 -Ni 0 -Nx 1186.47 -Ny 1093.76 -Nz 0.00 -Ne 100.000000 -Nl AGT -Nw —
#
#22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#Ma 0 -Md 0 -Ms 0 -Mt 0 -Is 0.0 -Id 40.0 -It cbr -Il 512 -If 0 -Ii 3 -Iv 32 -Pn cbr -Pi 1 -Pf 0 -Po 16777215
event = $1;
time = $3;
node = $5;
type = $19;
reason = $21;
packetid = $41;
packettype = $35;
src = $31;
dst = $33;
cbr_packetid = $47;
numhops = $49;
opt_numhops = $51;
energy = $17;


How to set path in bashrc after Installation NS-2

How to Set environment variables after installation NS-2 finished?
$ gedit ~/.bashrc
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
# LD_LIBRARY_PATH
OTCL_LIB=/your/path/ns-allinone-2.34/otcl-1.13
NS2_LIB=/your/path/ns-allinone-2.34/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.34/tcl8.4.18/library
USR_LIB=/usr/lib
export TCL_LIBRARY=$TCL_LIB:$USR_LIB

# PATH
XGRAPH=/your/path/ns-allinone-2.34/bin:/your/path/ns-allinone-2.34/tcl8.4.18/unix:/your/path/ns-allinone-2.34/tk8.4.18/unix
NS=/your/path/ns-allinone-2.34/ns-2.34/
NAM=/your/path/ns-allinone-2.34/nam-1.14/
PATH=$PATH:$XGRAPH:$NS:$NAM
Ensure the changes by execute this command:
$ source ~/.bashrc

If Problems
Solution
there are problem with your startx server. please try the solution in http://www.isi.edu/nsnam/ns/ns-problems.html

Black hole in AODV

I am trying to add a black hole to AODV-based MANET as a part of my study. I've found a good reference that tells how to add malicious node. The original link is here. His code is perfect. Everything runs smooth except when the very fast wireless links are used in the simulation. There were several warnings that relates to something I don't really remember. I will try to replicate that later and update in the blog someday. In order to get the simulation work, I tried tweaking the code a bit and found that adding C++ program syntax fixed that. Nothing much but a break. I will show my code which is changed a little bit from original one.

Add the following code in aodv.h
bool malicious;

around ( just before or after, it doesn't really matter)
double PerHopTime(aodv_rt_entry *rt);

In aodv.cc, the constructor shall be initialized with malicious=false.
/*
Constructor
*/
AODV::AODV(nsaddr_t id) : Agent(PT_AODV),
btimer(this), htimer(this), ntimer(this),
rtimer(this), lrtimer(this), rqueue() {
index = id;
seqno = 2;
bid = 1;
malicious = false; // code added

So far, aodv works the same with before the changes. To command a black hole start functioning, the command will be passed from TCL file. AODV needs to be programmed in a way so that it catches the passed parameter and started acting like a black hole. Thus, the following code is looked for in aodv.cc.

if(argc == 2) {
Tcl& tcl = Tcl::instance();
if(strncasecmp(argv[1], "id", 2) == 0) {
tcl.resultf("%d", index);
return TCL_OK;
}

And the following lines are added.

if(strcmp(argv[1], "malnode") == 0) {
malicious = true;
return TCL_OK;
}

In TCL, a malicious node or black hole is set by using the following command. It should be added after the nodes have been initialized.

$ns at 0.0 "[$node_(5) set ragent_] malnode"

Finally, the procedure which a black hole will be performed is going to be added. The following code segment is looked for in aodv.cc.

/*
Route Handling Functions
*/
void
AODV::rt_resolve(Packet *p) {
struct hdr_cmn *ch = HDR_CMN(p);
struct hdr_ip *ih = HDR_IP(p);
aodv_rt_entry *rt;
...

The following lines are added.
if (malicious == true ) {
drop(p, DROP_RTR_ROUTE_LOOP);
}

This is where the original code ends. It runs fine unless the data rate is high. When the packets are transferred at a significantly high rate, it causes some problems. So, the last segment of the code has been modified like the following. It works for me though I could not guarantee that it will be fine in other means.

if (malicious == true ) {
drop(p, DROP_RTR_ROUTE_LOOP);
return ;
}

Process on how to add trust table in NS2.

I am assuming AODV protocol. In rtable.cc add below code


trust_entry::trust_entry()
{
   //Initialize as per your need.
}
trust_entry::~trust_entry()
{
  //Deconstruct as per your need.
}

trust_entry* trust_store::trust_lookup(
nsaddr_t node_id)
{
     trust_entry *rp = trusthead.lh_first;
     for (; rp; rp = rp->trust_link.le_next) {
             if (rp->node_id == node_id)
                 break;
     }
    return rp;
}
void trust_store::trust_delete(
nsaddr_t node_id)
{
    trust_entry *rp = trust_lookup(node_id);

    if (rp)
    {
        LIST_REMOVE(rp, trust_link);
        delete rp;
    }

}

trust_entry*
trust_store::trust_insert(
nsaddr_t node_id, nsaddr_t prev_node,nsaddr_t next_node,int32_t trust_value)
{
    trust_entry *rp;
    //assert(tr_lookup(dst_seq_no) == 0);
    rp = new trust_entry;
    assert(rp);
    rp->node_id = node_id;
    rp->prev_node = prev_node;
    rp->next_node = next_node;
    rp->trust_value = trust_value;
    LIST_INSERT_HEAD(&trusthead, rp, trust_link);
    return rp;
}

trust_entry* trust_store::trust_update(
nsaddr_t node_id,nsaddr_t prev_node,nsaddr_t next_node, int32_t trust_value)
{    trust_delete(node_id);
    trust_insert(node_id,prev_
node,next_node,trust_value);
}
In rtable.h add below code


class trust_entry
{
    friend class AODV;
    friend class trust_store;
public:
    trust_entry();
    ~trust_entry();
    nsaddr_t node_id;
    nsaddr_t prev_node;
    nsaddr_t next_node;
    int32_t trust_value;
protected:
    LIST_ENTRY(trust_entry) trust_link;
};

class trust_store
{

public:
    trust_store()
    {
        LIST_INIT(&trusthead);
    }
    trust_entry* head()
    {
        return trusthead.lh_first;
    }
    trust_entry* trust_insert(nsaddr_t node_id,nsaddr_t prev_node,nsaddr_t next_node,int32_t trust_value);
    trust_entry* trust_lookup(nsaddr_t node_id);
    void trust_delete(nsaddr_t node_id);
    trust_entry* trust_update(nsaddr_t node_id,nsaddr_t prev_node,nsaddr_t next_node, int32_t trust_value);
private:
    LIST_HEAD(trust_head, trust_entry) trusthead;
};

while using in aodv code i.e. aodv.cc add below code to aodv.h

trust_store             tstore;
and if u want to access functions for adding route entry in aodv.cc then add below code in aodv.cc
tstore.trust_insert(node_id,prev_node,next_node,trust_value);
Note:- replace above four parameters with your own. Like wise u can access update, delete and lookup.

All the best!