Hi All, Our website moved to a new URL. Please bookmark the new link: https://ns2bloggers.blogspot.com/

Thursday 29 May 2014

MODIFYING AODV PROTOCOL

Many people doing project on AODV modification, but most of them have trouble in doing the same. The best way to modify aodv is to study aodv.cc and aodv.h well before starting your work. So here we are going to provide some help to modify AODV protocol.
First of all you have to study the function of each timer in aodv.cc; for that put a printf message inside each function of aodv.cc separately and then you can see how many times each function calls while executing a simple aodv program.

Step 1: open /ns-allinone-2.35/ns-2.35/aodv directory
Step 2: open aodv.cc file and add the commands which is shown in yellow outline.

void
HelloTimer::handle(Event*) {
 

// Begin ns2blogger.blogspot.in
printf("DEBUG TEST TEST \n");
// End ns2blogger.blogspot.in

   agent->sendHello();
   double interval = MinHelloInterval +
                 ((MaxHelloInterval - MinHelloInterval) * Random::uniform());
   assert(interval >= 0);
   Scheduler::instance().schedule(this, &intr, interval);
}


Step 3: Save the aodv.cc file and open the terminal and execute these commands.
            make clean
            make
            sudo make install
Step 4: Change directory and run any aodv program. You can see how many times the function 'HellowTimer::handle(Event*)' was called in this program.


For more details on aodv, click here to download pdf.

ASYMMETRIC PROPAGATION PROXY MODEL

NS-2 supports only symmetric propagation models like Shadowing. It means that the link quality between two nodes is always equal. For example if A hears B with propability of p, B will hear A with the same propability of p. For supporting asymmetric propagation we develop a new propagation model. Unlike the other models it is just a proxy, that will connected with a normal propagation model. The proxy changes the transmission power of the transmitter in dependency of the angle (between transmitter and receiver). You can configure the behaviour of each node by setting the gain (or damping) in dependence of the angle.


The following diagram shows the algorithm of the Asymmetric Propagation Proxy:



First the proxy calculates the angle between transmitter and receiver. For each node a profile exists (if not, it will be generated randomly) in which for a number of angles a gain values are given. The angle is linear mapped to a gain value. This gain is used to modify the transmission power (an exponential function). At the end the common routines of the connected propagation model (for example shadowing) are invoked.

For More, Click here
For Script, Click here
For TCL Script, Click here



Tuesday 27 May 2014

FLOODING PROTOCOL FOR NETWORKS

Flooding is a simple routing algorithm in which every incoming packet is sent through every outgoing link except the one it arrived on.Flooding is used in bridging and in systems such as Usenet and peer-to-peer file sharing and as part of some routing protocols, including OSPF, DVMRP, and those used in ad-hoc wireless networks.

There are generally two types of flooding available, Uncontrolled Flooding and Controlled Flooding.

Uncontrolled Flooding is the fatal law of flooding. All nodes have neighbours and route packets indefinitely. More than two neighbours creates a broadcast storm.

Controlled Flooding has its own two algorithms to make it reliable, SNCF (Sequence Number Controlled Flooding) and RPF (Reverse Path Flooding). In SNCF, the node attaches its own address and sequence number to the packet, since every node has a memory of addresses and sequence numbers. If it receives a packet in memory, it drops it immediately while in RPF, the node will only send the packet forward. If it is received from the next node, it sends it back to the sender.




Algorithm

There are several variants of flooding algorithm. Most work roughly as follows:

  1. Each node acts as both a transmitter and a receiver.
  2. Each node tries to forward every message to every one of its neighbours except the source node.
  3. This results in every message eventually being delivered to all reachable parts of the network.


Algorithms may need to be more complex than this, since, in some case, precautions have to be taken to avoid wasted duplicate deliveries and infinite loops, and to allow messages to eventually expire from the system. A variant of flooding called selective flooding partially addresses these issues by only sending packets to routers in the same direction. In selective flooding the routers don't send every incoming packet on every line but only on those lines which are going approximately in the right direction.

Advantages
  1. If a packet can be delivered, it will (probably multiple times).
  2. Since flooding naturally utilizes every path through the network, it will also use the shortest path.
  3. This algorithm is very simple to implement.[citation needed]

Disadvantages
  1. Flooding can be costly in terms of wasted bandwidth. While a message may only have one destination it has to be sent to every host. In the case of a ping flood or a denial of service attack, it can be harmful to the reliability of a computer network.
  2. Messages can become duplicated in the network further increasing the load on the networks bandwidth as well as requiring an increase in processing complexity to disregard duplicate messages.
  3. Duplicate packets may circulate forever, unless certain precautions are taken:
  4. Use a hop count or a time to live count and include it with each packet. This value should take into account the number of nodes that a packet may have to pass through on the way to its destination.
  5. Have each node keep track of every packet seen and only forward each packet once
  6. Enforce a network topology without loops

For Script, Click here

Monday 26 May 2014

INTRODUCTION TO TCL/TK

Tcl (Tool Command Language) is a very powerful but easy to learn dynamic programming language, suitable for a very wide range of uses, including web and desktop applications, networking, administration, testing and many more. Open source and business-friendly, Tcl is a mature yet evolving language that is truly cross platform, easily deployed and highly extensible.

Tk is a graphical user interface toolkit that takes developing desktop applications to a higher level than conventional approaches. Tk is the standard GUI not only for Tcl, but for many other dynamic languages, and can produce rich, native applications that run unchanged across Windows, Mac OS X, Linux and more.

Core Development

A wide variety of developers contribute to the open source Tcl and Tk core, which is hosted at core.tcl.tk. The Tcl Core Team (TCT) helps steer this development through mechanisms like Tcl Improvement Proposals (TIP's) and the core mailing list.

For more, Click here


Friday 23 May 2014

MODIFY TRANSMISSION RANGE IN NS-2

For changing the transmisson range you should do the following steps.
 
Modified folder: ns-2/mac/channel.cc
1.Some parameters calculation are reduced and those are shown RED BOLD letters.

……
void
WirelessChannel::calcHighestAntennaZ(Phy *tifp)
{
……
highestAntennaZ_ = highestZ/5;//Divide 5
WirelessPhy *wifp = (WirelessPhy *)tifp;
distCST_ = wifp->getDist(wifp->getCSThresh(), wifp->getPt(),
0.1, //REDUCE 1 to 0.1
0.1, //REDUCE 1 to 0.1
highestZ/2 , highestZ/2, wifp->getL(),
wifp->getLambda());
}

DATA ABOUT NEIGHBOR NODES

Here we developed a program to find the details of neighbor nodes especially current location and distance from a particular nodes.We think its helpful for you all.


proc neighbor {} {
set ns [Simulator instance]
global x1 x2 y1 y2 d n i j nn val
for {set i 0} {$i <$val(nn)} {incr i} {
puts "\n Neighbor list of node: $i"
   for {set j 0} {$j <$val(nn)} {incr j} {
if {$i != $j} {
set x1 [expr int([$n($i) set X_])]
set y1 [expr int([$n($i) set Y_])]
set x2 [expr int([$n($j) set X_])]
set y2 [expr int([$n($j) set Y_])]
set d [expr int(sqrt(pow(($x2-$x1),2)+pow(($y2-$y1),2)))]
puts "node: $j ==> position:- X: $x2 Y: $y2 Z= 0 \t distance: $d"
}
}
}
}
$ns at 10 "neighbor"



For script, Click here

SCREEN SHOT: 




CONGESTION CONTROL ALGORITHM FOR NETWORKS

Rate Control Protocol (RCP) is a congestion control algorithm designed for fast download times (i.e. aka user response times, or flow-completion times). Whereas other modifications to TCP (e.g. STCP, Fast TCP, XCP) are designed to work for specialized applications that use long-lived flows (scientific applications and supercomputer centers), RCP is designed for the typical flows of typical users in the Internet today. For example, a mid-size flow in the Internet today contains 1000 packets and TCP typically makes them last 10x longer than need-be (XCP is even worse). RCP makes flows finish close to the minimum possible, leading to a perceptible improvement for web users, distributed computing, and distributed file-systems. We believe RCP is the only congestion control algorithm to do this.

The main properties of RCP are:
  • Typical Internet flows will see 10 times faster download times than TCP and 30 times faster than XCP. Winners are the greater than 90% of sessions that never leave slow-start today.
  • Efficiently uses high bandwidth-delay product networks such as the long haul optical links.
  • Provably stable network independent of link-capacities, round-trip times and number of flows.
  • Flows are easy to police, to ensure they adhere to congestion control (not generally possible with other schemes).
  • Network operators can give preference (or weighted preference) to some flows/aggregates.

RCP has two components 

(1) End-host congestion control layer that sits between IP and TCP/UDP. During introduction, the end-host could adapt by testing for RCP at each end and along the path, falling back to TCP if need-be. 

(2) Each router maintains a single fair-share rate per link. Each packet carries the rate of the bottleneck link. For each packet, the router compares the two values. If the router's fair-share rate is smaller, it overwrites the value in the packet. This way, the source learns the fair-share rate of bottleneck link. It is simple, requires a very minor change to switches/routers and requires no per-flow state. 


For scripts, Click here
For ns 2.35 RCP patch, Click here 
For more, Click here

Thursday 22 May 2014

CONTROL PLAYBACK TIME OF NAM WINDOW

Everyone is keen to know how to increase or decrease the speed of network animation or playback time as by using default commands. By default the playback time is 2 ms and its suitable for script with lower stop value. But in case of script with stop value near or more than 100 seconds, its hard to wait that much time without controlling manually.

In here we are showing a command to control playback time of NAM window and you can add it on any part of tcl script.

$ns set-animation-rate <your value>

For example : $ns set-animation-rate 10ms

To know more about nam,Click here


Screen Shot :


REAL TIME PROTOCOLS [RTP/RTCP] FOR VIDEO STREAMING IMPLEMENTATION

Here, we describe the necessary steps to include the new developed RTP/RTCP module with the other built-in NS-2 modules, without needing to replace the native implementation for these protocols. We assume the reader has successfully installed a current NS-2.XX version. This code has been developed and tested with NS-2.33 and NS-2.34. 

In the legacy code, RTP and RTCP protocols are implemented as the RTP Agent and the RTCP Agent classes, respectively. These two classes are implemented in the rtp.cc (located in ~ns-2.XX/apps/rtp.cc) and rtcp.cc (located in ~ns-2.XX/tcp/rtcp.cc) files, as can be appreciated in Figure 1.  The RTP Agent holds all the functionalities for sending and receiving data packets, whereas the RTCP Agent is responsible for the control reports transmission and reception. The RTP Session class (implemented in ~ns-2.XX/common/session-rtp.cc) mainly deals with feedback report building and participant’s information tables maintenance, through the received packets passed by its agents. This class also defines the procedures for session initialization, report interval calculation, associating new RTP sessions with nodes, managing join and leave processes to multicast groups, stopping RTP flow transmissions, liberating the session resources, etc. It is called by its binding Session/RTP OTcl class (implemented in ~ns-2.XX/tcl/rtp/session-rtp.tcl). All the above files use rtp.h (located in ~ns-2.XX/apps/rtp.h) as header file, and they are shown in pink boxes in Figure 1.



The native implementation is quite generic. Many attributes specified in RFC 3550 are not included or they are not implemented accurately: 

i) it does not define all the RTCP packets, only RTCP Sender Reports (SR) packets are included, but its format is not complete (it does not include payload type, number of packets/octets sent fields, etc.)

ii) since RTCP Receiver Reports (RR) messages are not defined, neither QoS metrics (jitter, network delay, Round Trip Time -RTT-, loss rate) monitoring nor reporting are provided

iii) the same packet header data structure is used for both RTP and RTCP packets construction

iv) the packet header fields are specified using incorrect variables’ types and sizes

v) there is a bug for multicast transmissions configuration; vi) the code does not support multiple multicast streams on the same node; vii) the RTP Agent is only capable of generating CBR (Constant Bit Rate) traffic, etc. 

As simulations rely on the accuracy of the proposed models, and as the NS-2 native implementation for RTP/RTCP standard protocols is incomplete and imprecise, authors decided to develop a new module with a more complete and accurate implementation for these protocols than the one in the NS-2 native code, following strictly all the attributes specified in RFC 3550. The code includes the following enhancements: 

i) definition of all the types of RTCP packets with their exact format (Sender Report or SR, Receiver Reports or RR, Source Description or SDES, Application-defined or APP and BYE packets)

ii) network-level metrics (such as end-to-end delay, jitter, RTT, throughput and packet loss) monitoring, processing and registering in simulation time

iii) capability of processing any kind of application traffic pattern supported by NS-2

iv) support for multiple multicast streams on the same node; and v) compatibility with the legacy code.

INSTALLATION STEPS

In order to install the new developed NS-2 module, users must follow the next instructions:

1. Download module from here

2. Decompress the ‘rtp_gs_module.tar.gz’ file. After decompression, a new folder ‘rtp_gs_module’ will be created. It includes:
  • ‘rtp_gs’ folder, containing the C++ source code:


rtp_gs.h   rtp_gs.cc   rtcp_gs.h   rtcp_gs.cc   session-rtp_gs.h   session-rtp_gs.cc

  • session-rtp.tcl file, including the TCL code: In this file we have slightly modified the native TCL code in order to correct a small bug that does not allow configuring multicast scenarios. We have also included, in the same file, the TCL code for the new developed module in order to avoid adding another file (and/or directory).
  • rtp_scenario.tcl file, with an example of a TCL script: It includes the necessary steps in order to configure a new multicast simulation scenario with one RTP Source and three RTP Receivers distributed over the network topology, using our new RTP/RTCP module. 

3. Move the ‘rtp_gs’ folder into ns-allinone-2.XX/ns-2.XX directory.

4. Replace the session-rtp.tcl file, located in ns-allinone-2.XX/ns-2.XX/tcl/rtp/, with the one provided in the ‘rtp_gs_module’ folder.

5. Define the new specific packet types for the new developed protocols. The list of supported packets by NS-2 is located inside ~ns-2.XX/common/packet.h file. Thus, users must modify this file including the new RTP/RTCP packets (using numeric constants, which can vary depending on the NS-2 version) in packet_t enumeration (located in this header file):

typedef unsigned int packet_t;
static const packet_t PT_TCP = 0;
static const packet_t PT_UDP = 1;
...
static const packet_t PT_RTCP = 14;
static const packet_t PT_RTP = 15;
...
// insert new packet types here
static const packet_t PT_RTCP_GS = 61;
static const packet_t PT_RTP_GS = 62;
// The numbers can vary depending on the NS-2 version!!!
// This MUST be the LAST one (61+2)
static packet_t PT_NTYPE = 63;

6. In the same file, users must provide a textual name for the new RTP/RTCP novel packets identifying in order to distinguish them from the native packets in the output trace files generated by the simulator. This is done by adding the following lines inside p_info C++ class constructor:

 class p_info {
public:
       p_info()
       {
             initname()
       }
...
static void initName()
{
      ...
      name_[PT_TCP]= "tcp";
      name_[PT_UDP]= "udp";
      ...
      name_[PT_RTCP]= "rtcp";
      name_[PT_RTP]= "rtp";
      ...
      name_[PT_RTCP_GS]= "rtcp_gs";
      name_[PT_RTP_GS]= "rtp_gs";
      ...
}
}

Doing so, the new RTP/RTCP packets will be able to be sent, received and processed by the NS-2 simulation objects.

7. Save changes.

8. Add the following lines to ‘ns-2.XX/tcl/lib/ns-default.tcl’ file just below the line ‘Agent/RTCP set seqno_ 0’, in order to set default values for the Otcl/C++ bound variables:

            Agent/RTCP set seqno_ 0
            # New RTP/RTCP module: default variables setting
            Agent/RTP_gs set seqno_ 0
            Agent/RTP_gs set packetSize_ 1000

            Agent/RTCP_gs set interval_ 500ms.
            Agent/RTCP_gs set random_ 0

            Session/RTP_gs set debug_ 0
            Session/RTP_gs set cname_ 0
            Session/RTP_gs set jitter_ 0
            Session/RTP_gs set RTT_ 0
            Session/RTP_gs set rx_recv_ 0
            …

9. Save changes.

10. After that, it is necessary to open the ‘Makefile.in’ file (located in ~ns-2.XX/ directory) and modify it in order to add the source files of the new RTP/RTCP module.
  • Add to the INCLUDES section this text: '-I./rtp_gs \'. It should look like:


INCLUDES = \
-I. @V_INCLUDE_X11@ \
-I. \
@V_INCLUDES@ \
-I./tcp -I./sctp -I./common -I./link -I./queue
-I./adc -I./apps -I./mac -I./mobile -I./trace \
-I./routing -I./tools -I./classifier -I./mcast \
-I./diffusion3/lib/main -I./diffusion3/lib \
-I./diffusion3/lib/nr -I./diffusion3/ns \
-I./diffusion3/filter_core -I./asim/ -I./qs \
-I./diffserv -I./satellite -I./rtp_gs \
-I./wpan

  • Go to the “OBJ.CC” section and add the following line (before the line @V_STLOBJ@):


  • rtp_gs/rtp_gs.o rtp_gs/rtcp_gs.o rtp_gs/session-rtp_gs.o \

          We can add it just below the line:
          
          common/session-rtp.o apps/rtp.o tcp/rtcp.o \

       Users need to do that because the source directories for the new RTP/RTCP code have been collocated in a new directory (‘rtp_gs’).

11. Save changes.

12. Here, all the necessary modifications have been finished. Open a terminal window, move to ns-allinone-2.XX/ns-2.XX and run:

./configure

             , in order to create a new ‘Makefile’ file.

13. The last step is to compile the code. Execute the following commands (users must still be in ns-allinone-2.XX/ns-2.XX directory):
                 

make clean;make depend;make;

                                                                

Once it is finished, a new binary file named ‘ns’ in ns-allinone-2.XX/ns-2.XX/ directory will be available with the new RTP/RTCP functionality.

TCP SCRIPT: 

set ns [new Simulator]
set end_sim_time 10.0
#Open the nam trace file
set nf [open final.nam w]
set tf [open final.tr w]
$ns namtrace-all $nf
$ns trace-all $tf
#Define a 'finish' procedure
proc finish {} {
global ns nf tf
$ns flush-trace
#Close the trace file
close $nf
close $tf
#Execute nam on the trace file
exec nam final.nam &
exit 0
}
set node_(s1) [$ns node]
set node_(s2) [$ns node]
set node_(r1) [$ns node]
$ns duplex-link $node_(s1) $node_(r1) 10Mb 5ms DropTail
$ns duplex-link $node_(s2) $node_(r1) 10Mb 5ms DropTail
set trace_file [new Tracefile]
$trace_file filename starwars.nsformat
set RTP_s [new Agent/RTP_v2]
set RTCP_r [new Agent/RTCP_v2]
set self [new Session/RTP]
$ns attach-agent $node_(s1) $RTP_s
$ns attach-agent $node_(s2) $RTCP_r
$ns connect $RTP_s $RTCP_r
set video [new Application/Traffic/Trace]
$video attach-tracefile $trace_file
$video attach-agent $RTP_s
$RTCP_r session $self
$RTP_s session $self
$RTCP_r set interval_ 100ms
$RTCP_r set seqno_ 0
$RTP_s set packetSize_ 1064
$ns at 0.0 "$video start"
$ns at 0.0 "$RTCP_r start"
$ns at $end_sim_time {
$video stop
$RTCP_r stop
#$RTP_s stop
finish
}
$ns run

The information contained in the periodic RTCP-RR packets sent between 
destination and source are displayed in the display by default (you can watch it on the terminal screen). If you want to store it to a file, you can try this command:

ns rtp-rtcp-simulation.tcl > rtcps-info.log

The information will be stored in a new le named "rtcps-info.log".




Wednesday 21 May 2014

DISTANCE CALCULATION BETWEEN NODES

Lot of people mailed us about how to calculate distance between neighbor nodes or between source and destination?? Now we added some scripts in front end program i.e in tcl script to find out distance between source and destination or with neighbor nodes. 

We used distance calculation equation to find out the distance between two nodes.If (x1,y1) be the position of first node and (x2,y2) be the position of second node.Then,distance (d) between two nodes is given as;

d=[ (x2-x1)2+(y2-y1)]1/2

For Script ,Click here.


Screen Shot :



Sunday 11 May 2014

VISUALIZING TRACE FILE DATA WITH GnuPlot



Gnuplot is a portable command-line driven graphing utility for Linux, OS/2, MS Windows, OSX, VMS, and many other platforms. The source code is copyrighted but freely distributed (i.e., you don't have to pay for it). It was originally created to allow scientists and students to visualize mathematical functions and data interactively, but has grown to support many non-interactive uses such as web scripting. It is also used as a plotting engine by third-party applications like Octave. Gnuplot has been supported and under active development since 1986. 
Gnuplot can be used to visualize the trace file data; several network parameters can be plotted using this Gnu plot..for more details click here

Saturday 10 May 2014

SCRIPT TO FIND DESTINATION AND ENERGY OF NODES

Here we created a script to print final position of node and energy of nodes in your terminal.We hope it is useful for you all....!!!!!!

For script and details, Click here 

Screenshot:




Tuesday 6 May 2014

ADDING NS2 IN ECLIPSE

Now a days,running ns2 codes over ns2 is very useful and easy.If u want to speed up your programming and also you do not want to waste your time to remember Classes/APIs/Functions, do not want to waste time to open/close/reopen files, switch files back forth and finally, if you want to understand the code architecture better and quicker, you should use some good environment i.e IDE. In windows,the better IDE is visual studio.But in case of NS2,it is better to use Eclipse as the IDE for both linux and windows.In here we are explaining installation and working of Eclipse indigo and for ns2 versions (ns 2.31 to ns 2.35).

INSTALLATION OF ECLIPSE:

STEP 1: First,we have to download eclipse.And for that ,please go through following link;

                                              ECLIPSE DOWNLOAD

STEP 2: After downloading,open folder.It was normally in compressed format,so we have to extract it.Extract the IDE to a folder.

STEP 3 : Now download CDT from following link.
                                                  CDT DOWNLOAD

STEP 4: Now open Eclipse,go to help and then to install new software [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.

STEP 5: 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.

CDT stands for “C/C++ Development Tooling”
If you do not have a working internet connection in the system you have installed Eclipse, instead of steps 4 and 5, download the CDT from the above mentioned site. Then move to Install New Software (STEP 4) -> Add and add the archive downloaded.

STEP 6: Now,install ns2, Download ns2 form here and then Extract NS-2 to a folder, i.e. /home/username/ns-allinone-2.35

Edit Makefile :

1. Open “…/ns-allinone-2.35/ns-2.35/Makefile.in” and

2. Add "-g" to the line CCOPT = @V_CCOPT@ as follows
                              CCOPT = @V_CCOPT@ -g

3. Add -DNDEBUG -DDEBUG to the end of the following line:
DEFINE = -DTCP_DELAY_BIND_ALL -DNO_TK @V_DEFINE@ @V_DEFINES@       @DEFS@-DNS_DIFFUSION -DSMAC_NO_SYNC -DCPP_NAMESPACE=@CPP_NAMESPACE@-DUSE_SINGLE_ADDRESS_SPACE -Drng_test -DNDEBUG -DDEBUG

4. Navigate to …/ns-allinone-2.34/ns-2.34 and run “./configure”

5. Navigate to the NS-2 folder using terminal and type ./install

6. Also, follow the instructions are displayed at the end of a successful installation. These instructions are to modify the PATH variable and other environment variables as needed.

7. You may encounter compilation troubles, due to the DEBUG flag being enabled. My experience was that several printf statements needed to be disabled (commented out):
                   mobile/shadowing-vis.cc line 293
                   aodv/aodv.cc line 210
                   aomdv/aomdv_rtable.cc line 186
                   aomdv/aomdv.cc line 283

ADDING NS2 IN ECLIPSE

STEP 7: Now once again open eclipse and set the workspace as the ns2 installation path (/home/user/ns-allinone-2.35) by selecting File -> Switch Workspace.

Choose File -> New -> Project -> C++ Project.

Select Project Type as Makefile Project -> Empty C++ Project.
            1. Toolchains: Linux GCC
            2. Enter Project Name as ns-2.34

Uncheck “Use default location” then browse to the directory NS-2 source directory ( …/ns-allione-2.35/ns-2.35 )

In Eclipse Indigo, you may not be allowed to create a new project in the existing ns-2.35 subfolder if you uncheck the “Use default location” checkbox. You will not need to, anyway, if you have chosen the parent folder as workspace. In this case, Eclipse will only warn you that you are creating a project in a directory which already exists.

Select “Next” and “Finish”.

From the workspace, Selecting the NS-2 Project and choosing Project -> Build All should not give Error.

Running the project must open the console with the NS-2 prompt, %

SETTING DEBUG CONFIGURATION

STEP 8: Select Run -> Debug Configurations

Choose C/C++ Application. Type in any name.

Under the Main tab, Choose the following:

Project as ns-2.34.

C/C++ Application as ns. (Search Project and Choose this)

Under the Debugger tab, choose GDB Debugger. Uncheck the “Stop on startup at” option.

Apply and Debug.



Saturday 3 May 2014

IMPLEMENTING A NEW PROTOCOL

Tutorial to implement protoname in ns2.35


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

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
  • d. sudo make install

(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)


The whole credit of this work goes to Francisco J. Ros and Pedro M. Ruiz for their beautiful work and excellent explanation they provide.

ROUTING TABLE GENERATION

We all know that there was no automatic provisioning to generate a routing table for the nodes  in ns2. One of the way to solve this is by analyzing trace file generated by using some high level scripts like awk script, perl script or some other scripts.But it is little complex and also we have good knowledge in that and another way is to generating routing table is by modifying the existing routing protocol.

Here, we are going to generate routing tables for tcl scripts by modifying AODV protocol. For that we have to modify following files in the AODV directory[for AODV directory look at ns2.35 folder];
  1. aodv.h 
  2. aodv.cc

1. aodv.h modification

First display aodv.h file and then add the following lines inside the class AODV in the protected scope Add the line after the rt_down() function.

void rt_print(nsaddr_t nodeid);




Save the aodv.h file and

2. aodv.cc modification

Now click on aodv.cc file and select display option,

Now add the following function rt_print to the aodv.cc file probably below rt_down function.

void  AODV::rt_print(nsaddr_t nodeid) {
FILE *fp;
fp = fopen("route_table.txt", "a");
aodv_rt_entry *rt;
for (rt=rtable.head();rt; rt = rt->rt_link.le_next) {
fprintf(fp, "NODE: %i \t %f \t %i \t %i \n", nodeid, CURRENT_TIME, rt->rt_dst, rt->rt_nexthop);
}
fclose(fp);
}


















This function records the routing table entry into the file route_table.txt

The above code ;
  1. Creates a file pointer under append mode.
  2. Creates a pointer to routing table entry.
  3. Process the queue and finally print the values to the file with file pointer fp.
  4. Close the file pointer.

Now finally we have to call the function that we written above,we can call it in any part of protocol. Here we are going to call inside recvReply() function.

For that we have to write following line inside if (ih->daddr() == index);

 rt_print(index);



After completing these steps.Open the terminal window and change the directory to the ns2.35 by using following command.

cd /home/user/Desktop/ns-allinone-2.35/ns-2.35 [change path as yours]

and now type 
                                                                     make clean 
then type
                                                                         make
then type
                                                               sudo make install
  
         

























After successful completion of steps.Run a sample program.
For AODV,Click here
For sample program,click here  and run the program using command ns filename.tcl

Screen shot of a routing table



Note: File route_table.txt will be saved in the directory where program is located

This post is taken and modified from www.elmurod.net and www.nsnam.com

APPLICATION LAYER SIMULATIONS ON NS-2

A framework named "ns2-app" is developed and maintained by Xizhi Zhu to simplify the application layer simulations on NS-2.

BE CAREFUL, it's only tested on NS2.33 above, but it should work on some older versions as it doesn't change any existing code.

Why this framework

NS2 supports only unreal applications that just contain the length of packets. There do exist some real applications, but they are difficult to reuse, or even restricted to a specific type of applications.
Therefore, we decide to write this framework trying to reduce the difficulty. Also, a P2P framework is to be provided based on it.

Usage

  • The application layer simulation framework
    1. Download the latest source code here, uncompress it into the ~/ns-2.33/ directory, and recompile NS. BE CAREFUL, it will overwrite the original Makefile. But you can also modify the Makefile yourself by adding -I./real-app to the INCLUDES section and real-app/adu.o real-app/wrapper.o real-app/real-app.o real-app/test/test.o to the OBJ_CC section.
    2. Derive a class from ADU to represent the application layer data, and rewrite the size function. The packets are sent by calling the RealApplication::send() function
    3. Derive a class from RealApplication to represent the application, and rewrite the recv function which is called when a packet is arrived.
    4. Derive a class from TclClass to combine the application in C++ with OTcl.
    5. Write an OTcl script to configure the simulation.
  • The P2P application
    1. It's still under development.

The source code can be downloaded from the following link:

Download ns2-app-0.02.tar.bz2
After downloading, untar the downloaded folder in  ~/ns-2.33 directory and recompile NS-2.
For more details on installation and the possible errors, please visit the official website of ns2-app here.