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

Tuesday 16 December 2014

BYZANTINE ATTACK SIMULATION IN NS 2

In order to simulate most of the Byzantine attacks, we developed a protocol-independent Byzantine attack simulation module for ns2. This module provides the capability to simulate the black hole, Byzantine wormhole, and Byzantine overlay network wormhole attacks without modifying the routing protocol. It was not possible to simulate the flood rushing attack using this technique because it requires timing changes in the routing protocol code. Because this attack simulation module is potentially useful to the secure routing community, we make it publicly available below.

The module is implemented as part of the ns2 Link Layer (LL) object which lies directly below the Routing Agent and directly above the MAC layer. The modified LL has several commands that allow it to be configured from the simulation TCL setup script. The first command enables the black hole attack, which is executed by checking the packet type of any packet sent down by the routing agent, and silently dropping any packet which has an application data type (as opposed to a routing protocol type). The second command is used to setup the various wormhole configurations, and creates a back channel connection from one node to another wormhole peer node. The attack module manages any number of these wormhole peer connections, thus allowing the setup TCL script to create either a simple point to point wormhole or the more complicated overlay network wormhole. As a packet is sent down from the routing protocol, its next hop address is used to determine the correct action. In addition to being sent down to the interface queue for transmission by the MAC, copies of any broadcast packets are sent to every configured wormhole peer. If the next hop address of a unicast packet matches a wormhole peer address, the packet is sent directly to that peer. Otherwise, it is sent down the stack normally.

The module was developed for version 2.27 of ns2. The archive contains a directory with the original ns2 files (orig-ns-2.27) and a directory with the modified files for the attack module (odsbr-ns-2.27).

Related Papers:
[1] Baruch Awerbuch, Reza Curtmola, David Holmer, Cristina Nita-Rotaru and Herbert Rubens. On the Survivability of Routing Protocols in Ad Hoc Wireless Networks. In Proc. of IEEE First International Conference on Security and Privacy for Emerging Areas in Communications Networks (SECURECOMM '05), 2005.
[2] Baruch Awerbuch, Reza Curtmola, David Holmer, Cristina Nita-Rotaru and Herbert Rubens. ODSBR: An On-Demand Secure Byzantine Resilient Routing Protocol for Wireless Ad Hoc Networks. In ACM Transactions on Information and System Security (TISSEC), Volume 10, Issue 4, 2007.

For files, Click here
For more, Click here

Wednesday 10 December 2014

INTERNET BASED EFFICIENT CONTENT DISTRIBUTION PROTOCOL FOR MANET

Torrent is one of the Internet's most efficient content distribution protocols. It is known to perform very well over the wired Internet where end-to-end performance is almost guaranteed. However, in wireless ad hoc networks many constraints appear as the scarcity of resources and their shared nature, which make running BitTorrent with its default configuration not lead to best performances. To these constraints it adds the fact that peers are both routers and end-users and that TCP-performance drops seriously with the number of hops. We show in this work that the neighbor selection mechanism in BitTorrent plays an important role in determining the performance of the protocol when deployed over a wireless ad hoc network. It is no longer efficient to choose and treat with peers independently of their location. A first solution is to limit the scope of the neighborhood. In this case, TCP connections are fast but there is no more diversity of pieces in the network: pieces propagate in a unique direction from the seed to distant peers. This prohibits peers from reciprocating data and leads to low sharing ratios and sub optimal utilization of network resources. To recover from these impairments, we propose an enhancement to torrent which aims to minimize the time to download the content and at the same time to enforce cooperation among peers. Our solution considers a restricted neighborhood to reduce routing overhead and to improve throughput, while establishing few connections to remote peers to improve diversity of pieces. With the help of extensive NS-2 simulations, we show that these enhancements to Torrent significantly improve the file completion time while fully profiting from the incentives implemented in Torrent to enforce fair sharing.

For codes, Click here

Tuesday 25 November 2014

ADVANCED TOOL FOR ANALYSING TRACE FILES-APP

Wireless Information Networking Group[WING] of NIT,Surathkal developed a new analyzing tool for easy analysis of trace file.We can analyse following parameters using this;

  • throughput 
  • residual energy of a node
  • delay
For download,Please click here

After installing, Please type following commands in the terminal;

                                                        sudo apt-get udpate
                                                        sudo apt-get install python-matplotlib
                                                        cd APP-Tool-master/
                                                        python GUI_Main.py

Official Site: Wireless Information Networking Group

Saturday 2 August 2014

ADAPTIVE POLLING ALGORITHM FOR WLAN [NS2 IMPLEMENTATION]

IEEE 802.11 PCF mode is defined to support time bounded applications in wireless LANs. The poll scheduling plays an important role in PCF mode operation. It differs from the packet scheduling of routers in that incomplete queueing information in each pollable station is known to the scheduler. This paper proposes an adaptive polling algorithm to improve the wireless medium utilization. In our scheme, each mobile station is assigned a priority by the point coordinator. Based on recent poll feedbacks, the priority for each mobile station will be dynamically updated using the Additive Increase/Multiplicative Decrease algorithm. The proposed polling algorithm is compatible with the IEEE 802.11 standard and requires a simple extension. our simulation studies show that the performance of wireless LANs are improved in terms of the successful poll rate and the aggregate throughput.


For more,Click here

Thursday 31 July 2014

SIMULATION OF ALOHA PROTOCOL USING NS2

ALOHA is a protocol for satellite and terrestrial radio transmissions. In pure Aloha, a user can transmit at any time but risks collisions with other users' messages. "Slotted Aloha" reduces the chance of collisions by dividing the channel into time slots and requiring that the user send only at the beginning of a time slot. Aloha was the basis for Ethernet, a local area network protocol.

Pure ALOHA

Graph of frames being sent from 4 different stations according to the pure ALOHA protocol with respect to time, with overlapping frames shaded to denote collision. The first version of the protocol (now called "Pure ALOHA", and the one implemented in ALOHAnet) was quite simple:
  • If you have data to send, send the data
  • If, while you are transmitting data, you receive any data from another station, there has been a message collision. All transmitting stations will need to try re sending "later".
Boxes indicate frames. Shaded boxes indicate frames which have collided.


Note that the first step implies that Pure ALOHA does not check whether the channel is busy before transmitting. Since collisions can occur and data may have to be sent again, ALOHA cannot use 100% of the capacity of the communications channel. How long a station waits until it transmits, and the likelihood a collision occurs are interrelated, and both effect how efficiently the channel can be used. This means that the concept of "transmit later" is a critical aspect: the quality of the backoff scheme chosen significantly influences the efficiency of the protocol, the ultimate channel capacity, and the predictability of its behavior.

Slotted ALOHA

An improvement to the original ALOHA protocol was "Slotted ALOHA", which introduced discrete time slots and increased the maximum throughput.A station can send only at the beginning of a time slot, and thus collisions are reduced. In this case, we only need to worry about the transmission-attempts within 1 frame-time and not 2 consecutive frame-times, since collisions can only occur during each time slot. 


Thus, the probability of there being zero transmission-attempts in a single time slot is:

Prob_{slotted} = e^{-G}

the probability of k packets is:

Prob_{slotted} k =  e^{-G} ( 1 - e^{-G} )^{k-1}

The throughput is:

S_{slotted}=Ge^{-G}

The maximum throughput is 1/e frames per frame-time (reached when G = 1), which is approximately 0.368 frames per frame-time, or 36.8%. Slotted ALOHA is used in low-data-rate tactical satellite communications networks by military forces, in subscriber-based satellite communications networks, mobile telephony call setup, set-top box communications and in the contact less RFID technologies.

The use of a random-access channel in ALOHAnet led to the development of carrier sense multiple access (CSMA), a "listen before send" random-access protocol that can be used when all nodes send and receive on the same channel. The first implementation of CSMA was Ethernet. CSMA in radio channels was extensively modeled.[11] The AX.25 packet radio protocol is based on the CSMA approach with collision recovery,[12] based on the experience gained from ALOHAnet.

ALOHA and the other random-access protocols have an inherent variability in their throughput and delay performance characteristics. For this reason, applications which need highly deterministic load behavior sometimes used polling or token-passing schemes (such as token ring) instead of contention systems. For instance ARCNET was popular in embedded data applications in the 1980 network.


Script for wired connection:

Thursday 17 July 2014

NS2 INSTALLATION VIA CYGWIN FOR WINDOWS

Here we are providing you the user manual to installing ns2 on windows by using Cygwin. Cygwin is a large collection of GNU and Open Source tools which provide functionality similar to a Linux distribution on Windows. In this post, I will show you how to install NS2.

For User Guide, Click here 





Monday 14 July 2014

SIMULATION OF WIRELESS PERSONAL AREA NETWORK [WPAN] IN NS2

A personal area network (PAN) is a computer network used for data transmission among devices such as computers, telephones and personal digital assistants. PANs can be used for communication among the personal devices themselves (intrapersonal communication), or for connecting to a higher level network and the Internet (an uplink). A wireless personal area network (WPAN) is a PAN carried over wireless network technologies such as:

  • IrDA
  • Wireless USB
  • Bluetooth
  • Z-Wave
  • ZigBee
  • Body Area Network

The reach of a WPAN varies from a few centimeters to a few meters. A PAN may also be carried over wiredcomputer buses such as USB and FireWire.

Wireless Personal Area Network
A wireless personal area network (WPAN) is a personal area network — a network for interconnecting devices centered on an individual person's workspace — in which the connections are wireless. Wireless PAN is based on the standard IEEE 802.15. The two kinds of wireless technologies used for WPAN are Bluetooth and Infrared Data Association.

A WPAN could serve to interconnect all the ordinary computing and communicating devices that many people have on their desk or carry with them today; or it could serve a more specialized purpose such as allowing the surgeon and other team members to communicate during an operation.

A key concept in WPAN technology is known as "plugging in". In the ideal scenario, when any two WPAN-equipped devices come into close proximity (within several meters of each other) or within a few kilometers of a central server, they can communicate as if connected by a cable. Another important feature is the ability of each device to lock out other devices selectively, preventing needless interference or unauthorized access to information.

The technology for WPANs is in its infancy and is undergoing rapid development. Proposed operating frequencies are around 2.4 GHz in digital modes. The objective is to facilitate seamless operation among home or business devices and systems. Every device in a WPAN will be able to plug into any other device in the same WPAN, provided they are within physical range of one another. In addition, WPANs worldwide will be interconnected. Thus, for example, an archeologist on site in Greece might use a PDA to directly access databases at the University of Minnesota in Minneapolis, and to transmit findings to that database.

In NS2 we need two special commands during the simulation of WPAN [IEEE 802.15.4];

$ns at 0.0 "$node_(0) sscs startPANCoord"; # <txBeacon=1><BO=3> <SO=3>

This command is used to start PAN Coordinator and we write its syntax as like this with default values as txtBecon = 1,Becon Order =3 and Superframe Order = 3. Otherwise we can write as; 
"$node_(0) sscs startPANCoord 1 5 4"

$ns at 0.0 "$node_(1) sscs startDevice"# <isFFD=1><assoPermit=1><txBeacon=0><BO=3><SO=3>

This command is used to start device and we write its syntax as like this with default values as txtBecon = 1,Becon Order =3 and Superframe Order = 3. 

"$node_(1) sscs startDevice 1 0"    ====> becon diabled
"$node_(1) sscs startDevice 1 1 1" ====> becon enabled


For Script; Click here 


SCREEN SHOT

terminal

NAM Window





Wednesday 9 July 2014

ENCRYPTION AND DECRYPTION FUNCTION FOR NS2

Here, we are describing encryption and decryption techniques for the NS2 by adding an agent in the ns2 directory.

For script and details, Click here


Tuesday 24 June 2014

KEYBOARD SHORTCUTS FOR USING NAM

Most of the buttons in NAM have keyboard equivalents.We can use it in easy way and handle the network simulation easily. The commands are;

  1. <return> - Typing a <return> will pause nam if it's not already paused. If nam is paused, <return> will step the animation one simulated clock tick. (If your keyboard autorepeats, holding down <return> is a goodway to slow-step through the animation.)
  2. 'p' or 'P' - Pause but not step if paused.
  3. 'c' or 'C' - Continue after a pause.
  4. 'b' or 'B' - Decrease animation time for one screen update interval.
  5. 'r' or 'R' - Rewind.
  6. 'f' or 'F' - Fast Forward.
  7. 'n' or 'N' - Jump to time of next event in the tracefile.
  8. 'x' or 'X' - Undo the last rate change.
  9. 'u' or 'U' - Undo the last time slider drag.
  10. '>' or `.' - Increase the granularity (speed up) by 5%.
  11. '<' or ',' - Decrease the granularity (slow down) by 5%.
  12. <space bar> - Toggle the pause state of nam.
  13. 'q', 'Q' or <control-c> - Quit.
Note they only function when the mouse cursor is inside the nam window.

Monday 2 June 2014

NS2 MODULE FOR ANT COLONY OPTIMIZATION

In computer science and operations research, the ant colony optimization algorithm (ACO) is a probabilistic technique for solving computational problems which can be reduced to finding good paths through graphs.

This algorithm is a member of the ant colony algorithms family, in swarm intelligence methods, and it constitutes some metaheuristic optimizations. Initially proposed by Marco Dorigo in 1992 in his PhD thesis,the first algorithm was aiming to search for an optimal path in a graph, based on the behavior of ants seeking a path between their colony and a source of food. The original idea has since diversified to solve a wider class of numerical problems, and as a result, several problems have emerged, drawing on various aspects of the behavior of ants.

In the natural world, ants (initially) wander randomly, and upon finding food return to their colony while laying down pheromone trails. If other ants find such a path, they are likely not to keep travelling at random, but to instead follow the trail, returning and reinforcing it if they eventually find food.

Over time, however, the pheromone trail starts to evaporate, thus reducing its attractive strength. The more time it takes for an ant to travel down the path and back again, the more time the pheromones have to evaporate. A short path, by comparison, gets marched over more frequently, and thus the pheromone density becomes higher on shorter paths than longer ones. Pheromone evaporation also has the advantage of avoiding the convergence to a locally optimal solution. If there were no evaporation at all, the paths chosen by the first ants would tend to be excessively attractive to the following ones. In that case, the exploration of the solution space would be constrained.

Thus, when one ant finds a good (i.e., short) path from the colony to a food source, other ants are more likely to follow that path, and positive feedback eventually leads to all the ants' following a single path. The idea of the ant colony algorithm is to mimic this behavior with "simulated ants" walking around the graph representing the problem to solve.

This post contains extensions to NS-2 (versions 2.27 and 2.28) which enables the ACO behavior in WSNs. The module is adaptable to the current version of NS-2 since it is installed as a new routing protocol. Written mainly in C++ the ACO module (AntSense) produces the main attributes, however it was design in order to be used by any other technology supported by this simulator.

When designing a routing protocol for WSNs it is important to consider the packet length of each type of packets used by our protocol, since, as already explained communication is an energy-expensive function. In AntSense development, several approaches were used concerning types of packets and different lengths, the configuration illustrated in this section refers to the best pattern found by the results. In ACO approach ants are considered as packets that travel the network changing routing information in order to find the best path towards the anthill, in this case towards the sink-node. The ant packet structure is composed by:
  1. pkt_src: the node that originated the ant packet;
  2. antpath[3]: the three previous nodes visited by the ant;
  3. energy: the average energy per path;
  4. pheromone: the pheromone level that should be dropped by the return ant;
  5. toSinkNode: a boolean variable that informs if the ant is a forward or a return ant;

All the nodes that belong to the ant path are responsible to update the packet with the proper data, and should update also their internal information regarding the neighbor devices and pheromone levels always taking in consideration the direction of the s ant packet. As a normal protocol AntSense also requires a Hello type packets, in order for the nodes know which are the sensor nodes that are contactable with only one hop. The following structure were used in the hello packet:
  1. rp_src: the node that originated the hello packet;
  2. node_energy: the energy of the source node;

ANT Structure
It is important to emphasize that the node energy of the source is also exchange, this procedure allows a to increase the update rate in order to help ants to decide the best route based in available energy.

The AntSense file structure is divided in three different files (Figure): antsense.cc, queue.cc, and table.cc. The first one is the main file, where the routing protocol is written, functions like ant receive and ant forwards are describe here. This main file requires the functions described in the last two files, it uses the queue.cc to manage the data packet queuing, and table.cc to decide the best neighbor device to forward ant packets and data packets.

All the main and “hard” equations are described in the table.cc, where a routing table is kept and updated every time a ant packet is received.

The AntSense model in a first phase was build to behave as a normal ACO approach, however as the integration in WSNs was being designed the final solution reflects several aspects of the WSN integration, i.e. reduce the ant memory to three slots, which allows us to reduce communication time.

For Script, Click here
For More, Click here


Sunday 1 June 2014

PRINTING ROUTING TABLE IN TERMINAL

Here, we are going to generate routing tables IN  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) {
aodv_rt_entry *rt;
printf("Node id \t time \t destination \t nexthop \t hop count \t seq.no\n");
for (rt=rtable.head();rt; rt = rt->rt_link.le_next) {
printf("NODE: %i \t %f \t %i \t %i \t \t %i \t \t %i \n", nodeid, CURRENT_TIME, rt->rt_dst, rt->rt_nexthop, rt->rt_hops, rt->rt_seqno);
}
}



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 sample program,click here  and run the program using command ns filename.tcl

Screen shot





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.