wireless sensor networks (wsns) consist of small low-power...

49
ii ABSTRACT An opportunistic network application is a scenario in which mobile node users socialize with nearby users of common interest, but there exists no pre-established session by which users register or de-register their presence. As nodes are dynamically joining and leaving the network, a node discovers any newly joined nodes or knows when to release conversations from nodes who have left the network. This project aims to build a complete topology of end-to-end paths and periodically refresh it, to thereby erase all the connectivity and node position history, to adapt to the dynamic changing nature of opportunistic networks, and is called as Topology Refresh Protocol (TRP) [1]. TRP integrates the solution to the questions with data forwarding. It is lightweight and efficient that requires no path break detection and repair as required by on-demand routing, no complex route calculations as in probabilistic routing, and no duplication of messages as used in the class of epidemic routing. The TRP performance in terms of overhead, delay, and acceptance rate is calculated by computer simulation and it is found out that the acceptance rate is higher in TRP than in DSR.

Upload: buianh

Post on 10-Mar-2018

217 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

ii

ABSTRACT

An opportunistic network application is a scenario in which mobile node users

socialize with nearby users of common interest, but there exists no pre-established session

by which users register or de-register their presence. As nodes are dynamically joining and

leaving the network, a node discovers any newly joined nodes or knows when to release

conversations from nodes who have left the network. This project aims to build a complete

topology of end-to-end paths and periodically refresh it, to thereby erase all the

connectivity and node position history, to adapt to the dynamic changing nature of

opportunistic networks, and is called as Topology Refresh Protocol (TRP) [1]. TRP

integrates the solution to the questions with data forwarding. It is lightweight and efficient

that requires no path break detection and repair as required by on-demand routing, no

complex route calculations as in probabilistic routing, and no duplication of messages as

used in the class of epidemic routing. The TRP performance in terms of overhead, delay,

and acceptance rate is calculated by computer simulation and it is found out that the

acceptance rate is higher in TRP than in DSR.

Page 2: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

iii

TABLE OF CONTENTS

TABLE OF CONTENTS .................................................................................................. III

LIST OF FIGURES ........................................................................................................... V

LIST OF TABLES ............................................................................................................ VI

1. BACKGROUND AND RATIONALE ........................................................................... 1

1.1 Previous Work .......................................................................................................... 3

1.2 Present Work and Importance ................................................................................... 4

1.3 Introduction to NS2 Simulator .................................................................................. 5

1.4 NAM (Network Animator) ....................................................................................... 6

2. NARRATIVE ................................................................................................................. 7

2.1 Objective ................................................................................................................... 8

3. SYSTEM DESIGN ....................................................................................................... 10

4. IMPLEMENTATION ................................................................................................... 13

4.1 Implementation of DSR Protocol.......................................................................... 13

4.1.1 Network Configuration .................................................................................... 13

4.1.2 Creating Trace Files ......................................................................................... 14

4.1.3 Configuring Mobile Nodes .............................................................................. 15

4.1.5 Node Placement in Network ............................................................................ 17

4.1.6 Calculating Distance Between Nodes .............................................................. 18

4.1.7 Figurative Explanation for DSR ...................................................................... 19

4.2 Implementation of TRP protocol ............................................................................ 24

4.2.1 Network Configuration .................................................................................... 24

4.2.2 Evaluation of Mobile Nodes Energy................................................................ 25

Page 3: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

iv

4.2.3 Packet Delivery Ratio ...................................................................................... 26

4.2.4 Throughput ....................................................................................................... 26

4.2.5 Figurative explanation for TRP ....................................................................... 27

5. TESTING AND EVALUATION ................................................................................. 30

5.1 Test case 1 ............................................................................................................... 30

5.2 Test case 2 ............................................................................................................... 31

5.3 Test case 3 ............................................................................................................... 32

5.4 Test case 4 ............................................................................................................... 33

5.5 Evaluation ............................................................................................................... 34

6. CONCLUSION AND FUTURE WORK ..................................................................... 36

6.1 Conclusion .............................................................................................................. 36

6.2 Future Work ............................................................................................................ 36

7. BIBLIOGRAPHY AND REFERENCES ................................................................. 37

8. APPENDIX ................................................................................................................... 38

Page 4: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

v

LIST OF FIGURES

Figure 1. Opportunistic Networking ................................................................................... 2

Figure 2. Implementation of NS-2 ...................................................................................... 5

Figure 3 Message Format.................................................................................................. 11

Figure 4. System Design ................................................................................................... 11

Figure 5. A screenshot depicting initial position of nodes................................................ 19

Figure 6. A screenshot depicting data transfer between nodes ......................................... 20

Figure 7. A screenshot depicting source node dropping packets ...................................... 23

Figure 8. A screenshot depicting malicious nodes ............................................................ 24

Figure 9. A Screenshot depicting throughput for TRP ..................................................... 26

Figure 10. A screenshot depicting throughput for TRP .................................................... 26

Figure 11. A Screenshot depicting data transfer in TRP .................................................. 27

Figure 12 A screenshot depicting malicious nodes in TRP .............................................. 28

Figure 13. A screenshot depicting packet drops in TRP ................................................... 29

Figure 14. A screenshot depicting packet delivery in test case 1 ..................................... 30

Figure 15. A screenshot depicting packet delivery in test case 1 ..................................... 31

Figure 16. A screenshot depicting packet delivery in test case 2 ..................................... 31

Figure 17. A screenshot depicting packet delivery ration in test case 2 ........................... 32

Figure 18. A screenshot depicting packet delivery in test case 3 ..................................... 32

Figure 19. A screenshot depicting packet information in test case 3 ................................ 33

Figure 20. A screenshot depicting packet delivery in test case 4 ..................................... 33

Figure 21. A screenshot depicting average throughput in test case 4 ............................... 34

Page 5: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

vi

LIST OF TABLES

Table 1 Network Configuration ........................................................................................ 13

Table 2 Trace File Creation .............................................................................................. 14

Table 3 Mobile Nodes Configuration ............................................................................... 15

Table 4 Mobile Nodes Creation ........................................................................................ 16

Table 5 Initial Node Position ............................................................................................ 17

Table 6 Node Movement Creation .................................................................................... 17

Table 7 Calculating Distance Between Nodes .................................................................. 19

Table 8 C++ code for Shortest Path .................................................................................. 21

Table 9 Communication Establishment ............................................................................ 22

Table 10 Network Configuration for Proposed System .................................................... 24

Page 6: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

1

1. BACKGROUND AND RATIONALE

Opportunistic networks are multi-hop wireless networks that have no fixed

infrastructure support and no stable topology due to the movement of the mobile nodes [1].

In addition to sourcing and sinking data, nodes are co-operating to forward data in the

network. Opportunistic networks operate in environment where Internet like facility is

either unavailable or infeasible, or where localized networks are less expensive to use than

fixed infrastructure networks. Opportunistic networks have many applications. There are

scenarios in which fixed Infrastructure such as Internet is unavailable but local

communication is desirable, opportunistic network is the solution. Consider the

opportunistic advice situation where a rescue worker needs some advice from an expert in

the disaster recovery area where the Internet access equipment has been damaged.

Application of opportunistic network is exciting and limited only by one’s imagination,

supporting sessions that are scheduled, unscheduled, or spontaneous.

There are scenarios in which localized communications using an opportunistic

network is simply cheaper than using the Internet. Consider the application example in

which a reporter at an accident scene would choose to send the video shot of the scene back

to the television station over the opportunistic network to a faraway Internet access point

because sending the video over the satellite link of the device she is carrying is way too

expensive.

Consider the example [2] shown in Figure 1, the woman at the desktop

opportunistically transfers, via a Wi-Fi link, a message for a friend to a bus crossing the

area, “hoping” that the bus will carry the information closer to the destination. The bus

Page 7: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

2

moves through the traffic, then uses its Bluetooth radio to forward the message to the

mobile phone of a girl that is getting off at one of the bus stops. The girl walks through a

near park to reach the university. Her cellular phone sends the message to a cyclist passing

by. By proceeding in the same way some hops further, the message eventually arrives at

the receiver. As it is clearly shown in this example, a network connection between the two

women never exists but, by opportunistically exploiting contacts among heterogeneous

devices, the message is delivered hop-by-hop (hopefully) closer to the destination, and

eventually to the destination itself.

Figure 1. Opportunistic Networking

One of the major challenges in deploying opportunistic networks is data forwarding

[3]. The traditional distance vector and link state routing protocols developed for the

Internet assume a very stable physical topology and react well to a slow changing topology.

However, they are not suitable for opportunistic networks because of the lack of fixed

infrastructure upon which stable routes can be built and maintained, and route repairs are

unable to keep pace with the fast changing nature of the topology. As a result, a large body

of data forwarding protocols were proposed designed to overcome the challenges posed by

opportunistic networks. The major contribution of this project is to propose a high

performance lightweight adaptive data forwarding protocol for opportunistic network that

accounts for nodes entering and leaving the network dynamically.

Page 8: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

3

1.1 Previous Work

Much research has been done with the help of Network Simulators. This section

gives a detailed report of local graduate projects that have been implemented with the help

of NS-2 simulator in the past few years. NS (from network simulator) is a name for series

of discrete event network simulators, specifically ns-1, ns-2 and ns-3 [4]. All of them are

discrete-event computer network simulators, primarily used in research and teaching.

Implementation of simulation to enhance wireless ad-hoc networks performance

using the medium access control (MAC) protocol [5]. This project aimed at implementing

MAC protocol to enhance the simulation in WANETs. It makes use of network coding and

cooperative transmission to improve the network performance. The source and destination

nodes are dynamically selected and the data transfer is implemented with the help of

choosing a relay node in NS2. While the implementation of this project has some

similarities with the present work, the output and the approach is completely different in

terms of data transfer.

Simulation of Attacks in a Wireless Sensor Network using NS2 [6]. This project

aimed at simulating several kinds of attacks such as Sybil, Denial of Service attack,

Sinkhole attack, Hello flood attack. Nodes are created, configured and chosen dynamically.

Malicious nodes were picked to create the attacks. There isn’t much discussion about the

data transfer in this project. Detection of misbehavior in delay tolerant networks [7] is also

a similar project to [6], which makes use of the NS2 simulator and also has similar attacks

simulated for their own purposes.

Page 9: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

4

Implementation of prototype network early warning alarm system applying defense

in depth approach [8]. This project aimed at notifying users with an early warning alarm in

case of an attack and stop the attack. This project makes use of the CBR application and

TCP protocol in NS2 simulator. The present project also makes use of the tcp protocol

while implementing the AODV protocol.

1.2 Present Work and Importance

Network Simulator is a discrete event simulator targeted at networking research.

Ns provides substantial support for simulation of TCP, routing, and multicast protocols

over wired and wireless networks. Ns had a wide range of applications.

While all these projects use NS2 simulator for various purposes like simulating and

prevention of an attack, sending data over nodes, introducing malicious nodes, etc; The

present work makes use of NS2 to implement AODV and a TRP protocol [1] in similar

ways to the previously mentioned projects. However TRP is entirely a new concept

introduced for opportunistic networks where the nodes are joining and leaving the network

dynamically. Implementing TRP is the main motive of this project. AODV protocol is

being implemented only to compare the results and to prove that TRP’s performance is

better than that of AODV. TRP makes use of a header for each message and a forwarding

table for each mobile node making it unique for a faster data transfer in opportunistic

networks. TRP is different from all these other mentioned projects mainly coz’ of the usage

of header and the forwarding table which are periodically updated. And also none of these

projects implemented an opportunistic network where the nodes are mobile.

Page 10: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

5

1.3 Introduction to NS2 Simulator

NS2 stands for Network Simulator version 2. Ns-2 is a discrete event simulator for

networking research as already mentioned. Ns-2 works at a packet level. It provides

substantial support to simulate bunch of protocols like TCP, UDP, FTP, HTTP and DSR.

It is capable of simulating wired and also wireless networks. It is primarily Unix based.

TCL is the scripting language used for ns-2. It is basically a standard experiment

environment in the community of networking. It has many advantages that make it a useful

tool, such as support for multiple protocols and the capability of graphically detailing

network traffic with the help of NAM (Network Animator). Figure 2 shows the

implementation of ns-2.

Figure 2. Implementation of NS-2

Tcl helps in simulation of slightly varying parameters or configurations. Tcl helps

in quickly exploring a number of scenarios in ns-2 which allows in faster development. It

Page 11: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

6

is pretty easy to use and is available for free.

1.4 NAM (Network Animator)

Nam is a TCL/TK based animation tool for viewing network simulation traces and

real world packet traces. Network visualization tools allow designers to take in large

amounts of information quickly, visually identify patterns in communications, and better

understand causality and interaction. Nam is a network animator that provides packet- level

animation, protocol graphs, traditional time-event plots of protocol actions, and scenario

editing capabilities. Nam benefits from a close relationship with ns, which can collect

detailed protocol information from a simulation.

Page 12: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

7

2. NARRATIVE

The Ad hoc On-demand Distance Vector (AODV) [1] protocol sets up a route

between two nodes on a needed basis. AODV broadcasts route request messages and each

node receiving the requests caches a route back to the originator of the request. The

Dynamic Source Routing (DSR) proposed is also an on-demand protocol. In DSR, a source

node broadcasts a route request packet, containing its own address and target node address

as the initial route record, to its neighbors. The neighbors, in turn append their own address

to the route record and broadcast the packet to their neighbors. Upon receiving the route

request packet, the target node returns a route reply packet to the source node. Both AODV

and DSR flood the network with route discovery packets, detect any link breaks, notify

link breaks to the source node, and require the source node to establish a new route to the

destination node. If route discovery is not successful, both protocols must keep trying until

a new route is confirmed. The drawback of on-demand routing is energy and bandwidth

consumption in handling the frequent link breaks.

Instead of finding end-to-end paths, a generic solution is to replicate copies of the

same message to many nodes and the message delivery is successful when a node carrying

a Copy makes contact with the target node. The first such protocol is the Epidemic Routing

Protocol (ERP) [3] which requires source nodes to flood the network with copies of a

message so that the destination node will eventually receive a copy. To overcome the large

bandwidth and energy overhead associated with flooding, the spray and wait protocol

spreads copies of a packet to a limited number of nodes in multiple periods, the spray and

route sprays a few copies into the network and routes them Independently. The PROPHET

protocol is one of the earliest schemes based on probabilistic routing. It requires each node

to estimate the probabilities of reaching Destinations based on the frequency of encounters

Page 13: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

8

with transitivity and exchange these information with neighbors. A packet is forwarded to

a node if the node has a larger such probability and hence multiple copies of the same

message are made. The drawbacks of these protocols are the large energy consumption,

reduced bandwidth, and increased node Memory to buffer copies of messages.

Recent protocols require no end-to-end paths and no message replication. For

examples, the d-AdaptOR [1] and POR. d-AdaptOR computes and updates a score in each

node based on transmission cost and successful packet delivery reward. The scores are used

by nodes to determine probabilistically the next hop forwarder or drop the packet. In POR,

nodes must know their own locations as well as the locations of their neighbors. A sender

prioritizes its neighbors as next hop forwarders according to their distances to destination.

A significant drawback of all of these solutions [1] is that nodes are assumed to

know the identity of their recipient nodes and that the recipient nodes are alive in the

network. A static list of recipients is not suffice whether the list is preregistered or obtained

from some service when nodes join the network. This is because membership can be very

dynamic as nodes leaving and returning to the wireless coverage of the network, new nodes

joining and leaving the network from time to time, or nodes simply being turned on and

off. On-demand routing protocols can tell if recipient nodes have left the network indicated

by route repair failures. Protocols, other than on-demand, send packets into the network,

not knowing if the target nodes have left the network or failed, or the network is partitioned

separating them from their target nodes.

2.1 Objective

The main objective of this project is to build a high performance (relative to other

Page 14: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

9

well-known routing protocols) lightweight adaptive data forwarding protocol for

opportunistic network that accounts for nodes entering and leaving the network

dynamically. Other routing protocols as in AODV and ERP protocols. TRP should open

up a whole new set of applications such as unscheduled or unorganized social gathering

over an opportunistic network and applications discussed in the introduction section. The

low message delay performance also makes the TRP suitable for non-stringent real-time

applications.

Page 15: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

10

3. SYSTEM DESIGN

In the Proposed framework every message contains a header utilized for route setup

and message forwarding. The message field distinguishes the neighbor node to which the

message ought to be sent. Neighbor nodes of a node are inside of the node's transmission

range. On the off chance that message is all ones, the message is telecast to all the neighbor

nodes. They recognize the immediate node from which the message is sent. The node

distinguishes whether this message is data or an acknowledgement. The messages have

priority over the other types for processing. Acknowledgement has priority over data for

both processing and transmission. The performance metric is used to select the best path

out of the multiple available paths. The resulting end-to-end path is the max-min remaining

energy path. It is, however, permissible to use different metrics such as delay and

throughput, or a combination of metrics. Then the hop count keeps track of the number of

nodes the message has traversed so far.

Then the sequence number of the message generated at sender node is followed and

the remaining time is noted after which the message is erased. It is because the message is

unable to be forwarded or severely delayed. That is all data messages are assumed to be

unicast. Neighbors of a node will receive the same message originated from the node.

Neighbors will reject any received messages if the messages do not match their own node

id values. Each mobile node maintains a table, called the Forwarding Table. The

destination node id is extracted from the header of message. The sender node is next hop

neighbor node that a data message should be forwarded, which is extracted from the header

of the message. Then the sequence of message that are sent from one node to another is

noted and the time taken to send the message are noted and entered into the Forwarding

table. Figure 3. Shows the message format in a tabular view.

Page 16: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

11

Figure 3 Message Format

Figure 4 gives a detail of the system design for the proposed system. An

opportunistic network will be created in the simulator.

Figure 4. System Design

A source node is chosen for the data transfer. Destination node is randomly selected

based on the tcl script coded for the project. Data is transferred by using the default UDP

protocol from ns-2. The path through which the data traverses is determined by one of the

output files named base.tr. The path is chosen based on the distance from the nearest node.

Page 17: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

12

TRP deals with two kinds of messages as already mentioned namely data,

acknowledgement. Any malicious nodes will be identified and the data is rerouted if any

malicious nodes are found. Finally the data is transferred to the destination node.

Page 18: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

13

4. IMPLEMENTATION

In this project, two different protocols have been implemented to show the

difference between the results of the proposed system from existing system. The two

protocols are DSR (Dynamic Source Routing) and TRP (Topology Refresh Protocol)

namely.

4.1 Implementation of DSR Protocol

In this section, a brief of the modules developed in the TCL script to implement the

DSR protocol, Execution flow of the DSR protocol is presented. Node attack definition is

presented at the end of the report in the appendix section.

4.1.1 Network Configuration

Table 1 shows the code snippet used to configure the network in DSR protocol.

“set” is the keyword to assign functionalities or value to the objects. “val()” is the datatype

to add values to the object. “val(chan)” is the variable which sets the functionality of the

network as Wireless Channel (predefined property). “LL” is the pre-defined linked layer

property to establish communication in the network layer. “20” is assigned to the object

“val(nn)” , for setting the number of mobile nodes to 20. “DSR” is a predefined protocol

in NS2 and it is assigned to object “val(rp)”. This sets the routing protocol as DSR in the

resulting network. A wireless network with 20 nodes is created in the Network Animator.

Table 1 Network Configuration

#Creating variables

set val(chan) Channel/WirelessChannel ;#Channel Type

set val(prop) Propagation/TwoRayGround ;# radio-propagation model

Page 19: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

14

set val(netif) Phy/WirelessPhy ;# network interface type

set val(mac) Mac/802_11 ;# MAC type

set val(ifq) CMUPriQueue ;# interface queue type

set val(ll) LL ;# link layer type

set val(ant) Antenna/OmniAntenna ;# antenna model

set val(ifqlen) 500 ;# max packet in ifq

set val(nn) 20 ;# number of mobilenodes

set val(rp) DSR ;# routing protocol

4.1.2 Creating Trace Files

A base trace file along with three other trace files namely out0.tr, out1.tr, out2.tr

and a NAM trace file are created with each trace file tracking different kinds of information

on the network behavior and a base trace file is created to keep track of all the information

about the simulation. Table 2 shows the code snippet for creating trace files. “open” is the

keyword to make a file, “dsr.tr” is the file name and “w” denotes the write operation.

“$tracefd” is the variable name, it is assigned to “trace-all” predefined property. “trace-all”

takes the entire information and activity of the network. “namtrace-all-wireless” is the

predefined keyword which creates the “dsr.nam” file to display the network simulation

process. This results in creating 4 trace files namely out0.tr, out1.tr, out2.tr & dsr.nam.

Table 2 Trace File Creation

#CREATE TRACE FILE

set tracefd [open dsr.tr w]

$ns trace-all $tracefd

Page 20: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

15

set f0 [open out0.tr w]

set f1 [open out1.tr w]

set f2 [open out2.tr w]

#CREATE NAM TRACE FILE

set natr [open dsr.nam w]

$ns namtrace-all-wireless $natr $val(x) $val(y)

4.1.3 Configuring Mobile Nodes

Nodes are initially set with the configuration as shown below. Table 3 shows the

code snippet used to configure mobile nodes in the network. These node configuration

values are already defined in section 4.1.1. “node-config” is the keyword to assign the

properties for the nodes. This configures the network with the required configuration.

Router trace (RTR), Agent trace (ATR) and Movement trace are set to be ON and Mac

trace is set to be OFF since it is not required and increases the load on the network.

Table 3 Mobile Nodes Configuration

#CONFIGURE NODE

$ns node-config -adhocRouting $val(rp) \

-llType $val(ll) \

-macType $val(mac) \

-ifqType $val(ifq) \

-ifqLen $val(ifqlen) \

-antType $val(ant) \

-propType $val(prop) \

Page 21: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

16

-phyType $val(netif) \

-channelType $val(chan) \

-topoInstance $topo \

-agentTrace ON \

-routerTrace ON \

-macTrace OFF \

-movementTrace ON

4.1.4 Creation of Mobile nodes

The Mobile nodes are created and configured inside the network with the help of

NS-2 network simulator. Table 4 shows the code snippet for creating nodes. “node()” is

the array variable for creating nodes. “lappend” is the keyword to list the elements onto a

variable. A network of 20 nodes will be simulated.

Table 4 Mobile Nodes Creation

#CREATE NODES

set nodelist {}

for {set i 0} {[expr $i < $val(nn)]} {incr i} {

set node($i) [$ns node]

# $node($i) label "$i"

if {$i!=30} {

lappend nodelist $i }

}

By providing the nodes with initial location details and destination location details,

Page 22: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

17

one can create mobile nodes. The start-position and future destinations for a mobile node

can be set by using the following APIs.

Initial position of nodes in the network simulator is set with code snippet from the below

table 5.

Table 5 Initial Node Position

$node set X_ \<x1\>

$node set Y_ \<y1\>

$node set Z_ \<z1\>

Node movement is created with the code line shown in the table 6.

Table 6 Node Movement Creation

$ns at $time $node setdest \<x2\> \<y2\> \<speed\>

The above syntax shows that the particular node starts to move to particular

destination of x2, y2 at the $time, which is declared in the script.

4.1.5 Node Placement in Network

Node position at the beginning of the simulation is shown below for few nodes in

table 7. Node positions cannot be determined after this point since nodes are moving

continuously. Nodes are placed randomly for each simulation and move in random

directions. The initial positions can be determined from the trace file base.tr.

Table 7 Node Positions

Node 0 is placed in 45.707359558766413 and 203.59210418704529

Node 1 is placed in 572.49507167027105 and 324.6695622450996

Page 23: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

18

Node 2 is placed in 321.33265338900156 and 37.905508949377349

Node 3 is placed in 477.88891218504352 and 278.94709402646271

Node 4 is placed in 463.80930275833668 and 42.951459364477294

4.1.6 Calculating Distance Between Nodes

Each mobile node in the network is placed in different location. The mobile

nodes have some random distance between each other and those distances are calculated

by applying the node(x, y) coordinates in Pythagoras theorem. The distance calculation

between each mobiles nodes helps to develop proposed routing protocol. Figure 4 shows a

screen of the displaced mobile nodes to help with calculating distance between mobile

nodes.

Figure 4. Screen shot of the displaced mobile nodes

Table 8 contains the code snippet for calculating distance between nodes. “puts” is

the keyword to print in the terminal. “expr” is the keyword to do mathematical expression

or calculations. “pow” is the keyword to make the power operation on the two variables.

Page 24: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

19

Table 8 Calculating Distance Between Nodes

for {set j 0} {$j < $val(nn) } { incr j } {

set dx [expr $xx($i) - $xx($j)]

set dy [expr $yy($i) - $yy($j)]

set dx2 [expr $dx * $dx]

set dy2 [expr $dy * $dy]

set h2 [expr $dx2 + $dy2]

set h($i-$j) [expr pow($h2, 0.5)]

puts "Distance of node($i) from node($j) = $h($i-$j)"

puts $r "Distance of node($i) from node($j) h($i-$j) = $h($i-$j)"

}

4.1.7 Figurative Explanation for DSR

Figure 5. A screenshot depicting initial position of nodes

Page 25: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

20

Figure 5 shows the initial position of nodes after clicking the play button in the

NAM visualizer. As it is seen nodes are randomly positioned in the network. Source node

is predefined to be 14 in the TCL code. An important thing to note down here is that nodes

start in different positions for each time the network is simulated.

Once the nodes are randomly positioned in the network, node 0 sends a packet to

its neighbor nodes about its position. Neighbor nodes of a node are the nodes that are in

the transmission range of the node as already mentioned. These neighbor nodes in turn

send packets to their neighbor nodes about the position of node 0 until the position of node

0 is informed to the source node. Figure 6 shows packets transferring from the source node

14 to node 0.

Figure 6. A screenshot depicting data transfer between nodes

Data transfer takes place sequentially beginning from node 0 to node 19. In this

particular case, the route chosen for the source node to transfer packets to node 0 is 14-17-

2-0. In this case, shortest path is clear. But, in general shortest path is calculated based on

Page 26: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

21

the C++ code that comes in the DSR folder of the NS-2 package which is shown in table

9.

Table 9 C++ code for Shortest Path

struct hdr_sr hsr;

if (net_id == ID(1,::IP))

{

printf("adding route to 1\n");

hsr.init();

hsr.append_addr( 1, NS_AF_INET );

hsr.append_addr( 2, NS_AF_INET );

hsr.append_addr( 3, NS_AF_INET );

hsr.append_addr( 4, NS_AF_INET );

route_cache->addRoute(Path(hsr.addrs(),

hsr.num_addrs()), 0.0, ID(1,::IP));

}

if (net_id == ID(3,::IP))

{

printf("adding route to 3\n");

hsr.init();

hsr.append_addr( 3, NS_AF_INET );

hsr.append_addr( 2, NS_AF_INET );

hsr.append_addr( 1, NS_AF_INET );

route_cache->addRoute(Path(hsr.addrs(),

hsr.num_addrs()), 0.0, ID(3,::IP));

}

One more important thing in NAM visualization is that, it only shows high chunks

of data. NAM visualization ignores small traces of data in the visualization. So the path

through which data is traversed cannot be obtained from the visualization. It can only be

obtained with the help of the trace file which is created after the simulation.

Page 27: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

22

In DSR protocol, Communication between nodes is established by using TCP

(Transmission Control Protocol). Data is transferred by using the UDP (User Datagram

Protocol). UDP agent accepts data in variable size chunks from the application which is

defined in the simulation and segments the data as per the requirements of the simulation

part. UDP packets also contain a monotonically increasing sequence number and an RTP

timestamp. Although real UDP packets do not contain sequence numbers or timestamps,

this sequence number does not incur any simulated overhead, and can be useful for trace

file analysis or for simulating UDP-based applications.

The default maximum segment size (MSS) for UDP agents is 1000 byte:

Agent/UDP set packetSize_ 1000 # max segment size;

The sample code to establish communication between nodes in the network using

TCP is given below in table 10. “new Agent/TFRC” is the property to add source node.

“new Agent/TFRCSink” is the property to add destination node. “attach-agent” is the

property to attach source or sink properties to the nodes. “$tfrc start” where the “start”

denotes to initiate the operation at a particular time.

Table 10 Communication Establishment

set tfrc [new Agent/TFRC]

set tfrcsink [new Agent/TFRCSink]

$tfrc set class_ 2

$tfrcsink set class_ 2

$ns attach-agent $n() $tfrc

$ns attach-agent $n() $tfrcsink

$ns connect $tfrc $tfrcsink

Page 28: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

23

$ns at 0.2 "$tfrc start"

Number of packets sent by the source node, no. of packets received by the

destination node, no. of packets dropped by the source node/intermediate nodes, Hop count

of the message and the route through which message is traversed. All this information is

stored in to the base trace file that is created in the trace file creation module.

When the source node is overloaded with too much traffic and reaches it’s

Maximum capacity of packets, it starts dropping packets to accommodate

acknowledgments coming from other nodes. Figure 7 shows the same.

Figure 7. A screenshot depicting source node dropping packets

Figure 8 shows the malicious nodes in the network simulated for DSR. Nodes that

are encircled in red circles are the malicious nodes. These colors can be set with the help

of NS2 simulator. As one can see, number of malicious nodes while implementing DSR

is high. This is one of the limitations of DSR.

Page 29: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

24

Figure 8. A screenshot depicting malicious nodes

4.2 Implementation of TRP protocol

A brief of all the important modules developed for the proposed system (TRP) is

presented in this section. Node attack definition is presented at the end of the report in the

appendix section.

4.2.1 Network Configuration

The network is initially set with the configuration as shown below.

Table 11 Network Configuration for Proposed System

#Creating variables

set val(chan) Channel/WirelessChannel ;#Channel Type

set val(prop) Propagation/TwoRayGround ;# radio-propagation model

set val(netif) Phy/WirelessPhy ;# network interface type

Page 30: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

25

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) 1000 ;# max packet in ifq

set val(nn) 20 ;# number of mobilenodes

set val(rp) AODV ;# routing protocol

The modules for creation of trace files, Configuring mobile nodes, Creation of

mobile nodes, Calculating distance between nodes are almost same as used in the DSR

protocol. Therefore there is no need to repeat them in this section. Node attack definition

module is presented in the appendix section of the report.

4.2.2 Evaluation of Mobile Nodes Energy

Every mobile node in the network requires certain amount of energy for

transmitting or receiving packets. The mobile nodes lose some particular amount of energy

for each packet transmission around the network, they require energy to stay active in the

network for long time. The nodes with highest energies are taken for packet transmission,

this helps mobiles nodes from keeping the network in the active state. The below

information shows the remaining energy in the mobile nodes after the end of packet

transmission using proposed routing protocol.

Table 12 Remaining Energies

Remaining energy of the node 0 is 726.6161

Remaining energy of the node 1 is 755.1493

Page 31: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

26

Remaining energy of the node 2 is 794.6311

Remaining energy of the node 3 is 728.7276

Remaining energy of the node 4 is 724.4827

4.2.3 Packet Delivery Ratio

Figure 9 shows the packet delivery ratio when PacketDeliveryRatio.awk is

executed. The ratio of the number of delivered data packets to the sent data packets is

packet delivery ratio. The packet transmission is established between mobile nodes using

CBR and UDP traffic.

Figure 9. A Screenshot depicting throughput for TRP

4.2.4 Throughput

Figure 10 shows the screenshot for throughput when throughput.awk file is

executed. Throughput is defined as the ratio of the acceptance rate to the input rate.

Figure 10. A screenshot depicting throughput for TRP

Page 32: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

27

4.2.5 Figurative explanation for TRP

In TRP protocol execution, after the play button is pressed in the NAM

visualization predefined source node 15 starts transmitting packets to the nodes in the

sequence 1 to 19. Since the data transmission is set to be sequential, initially node 0 starts

sending requests to its neighbor nodes and these neighbor nodes in turn start sending these

requests to their neighbors until the request reaches the source node 15. Once the source

node 15 receives request from 0, Source node establishes a communication with the first

destination node 0. After a communication link is established between nodes 15 and 0,

node 15 starts sending packets to node 0 via node 1. Figure 11 shows the source node

transmitting packets to node 0 via node 1.

Figure 11. A Screenshot depicting data transfer in TRP

Figure 12 shows a screenshot of malicious nodes in the TRP protocol. Some of the

nodes in the network turn malicious after a certain time. Node 5 and node 11 turned

malicious in this case as it can be seen from figure 12. Whenever there is a malicious node

in the path through which data is traversing, the network gets refreshed.

Page 33: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

28

Figure 12 A screenshot depicting malicious nodes in TRP

Once the network is refreshed, all the data transmissions are stopped and all the

nodes are set back with their initial configurations. When the data transmissions resume

again, malicious nodes are avoided and a new route is established between the source node

and destination node. If no route is found, Network waits until a new route is found. No

routes can be found there is no node with in the transmission range of the source node.

Network waits until some node comes in the transmission range of the source node.

Packet drops happen for the same reason as in DSR. Packet drops happen when a

node is overloaded with packets. Figure 13 shows the same happening with node 9. The

number of packet drops is observed to be minimum in case of TRP. This is one of the goals

in implementing TRP. There is a chance of source node becoming malicious node in case

of DSR. That is avoided in TRP, which means source node cannot turn malicious in case

of TRP.

Page 34: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

29

Figure 13. A screenshot depicting packet drops in TRP

Once packets are received to all the destination nodes from 0 to 19, all the nodes

reply back an acknowledgement to the source node in a random order.

Page 35: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

30

5. TESTING AND EVALUATION

5.1 Test case 1

This test case is for DSR protocol without any malicious nodes in the network. Red

graph indicates total no. of packets dropped which are traced by the trace file out0.tr. Blue

graph indicates the total no. of packets sent from the source node which are traced by the

trace file out2.tr. Green graph indicates total no. of packets received by the destination

nodes which are tracked by out1.tr. Figure 14 shows the result of the combined graphs.

Figure 14. A screenshot depicting packet delivery in test case 1

Figure 15 shows the packet delivery ratio in this test case. Comparison between

Packet Delivery Ratio in these test cases would lead to the result that TRP protocol is a

better protocol when compared to DSR. This test case is implemented by removing the

malicious nodes function in the network resulting in a safe network with 20 mobile nodes.

Packet Delivery ratio = 0.9178

Page 36: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

31

Figure 15. A screenshot depicting packet delivery in test case 1

5.2 Test case 2

This test case is for DSR protocol with malicious nodes in the network. Even in

this case, graphs indicate the same as in test case 1. Figure 16 shows the screenshot of

packet delivery in this case. This test case is basically implementing DSR protocol as it

should be implemented for opportunistic networks. No changes were made while testing

this case.

Figure 16. A screenshot depicting packet delivery in test case 2

Page 37: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

32

Figure 17 shows the packet delivery ratio in this test case when

PacketDeliveryRatio.awk is executed.

Packet Delivery Ratio = r/s = 0.9315

Figure 17. A screenshot depicting packet delivery ration in test case 2

From the results of the above two test cases, it can be said that the inclusion of

malicious nodes in the network doesn’t make much difference in the packet delivery ratio

when DSR protocol is used for routing in opportunistic networks.

5.3 Test case 3

Figure 18 depicts the test case results for TRP protocol without any malicious nodes

in the network. Graphs indicate the same in all the test cases.

Figure 18. A screenshot depicting packet delivery in test case 3

Test case 3 is tested for TRP protocol by removing malicious nodes in the network.

Page 38: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

33

That means, implementing the TRP protocol for a normal opportunistic network. Figure 19

shows the no. of sent packets, no. of received packets, no. of received packets and the

average end to end delay for this test case.

Sent packets = 562

Received packets = 229

Dropped packets (bytes) = 340680

Figure 19. A screenshot depicting packet information in test case 3

5.4 Test case 4

Figure 20 shows the test case results for TRP protocol with malicious nodes in the

network.

Figure 20. A screenshot depicting packet delivery in test case 4

Page 39: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

34

Test case 4 is tested for TRP protocol by keeping malicious nodes in the network.

That means implementing TRP protocol as it is implemented in the proposed system.

Figure 21 shows the screenshot of average throughput in this test case when

throughput.awk file is executed.

Average throughput = 391.14

Figure 21. A screenshot depicting average throughput in test case 4

5.5 Evaluation

Summary of the test cases

Packet Delivery ratio = 0.9178 in test case 1

Packet Delivery ratio = 0.9315 in test case 2

In test case 3

- Sent packets = 562

- Received packets = 229

- Dropped packets (bytes)= 340680

Packet Delivery ratio = 0. 9678 in test case 3

Test Case 1 Test Case 2 Test Case 3 Test Case 4

No. of nodes 20 20 20 20

Network Type Wireless Wireless Wireless Wireless

Ratio 0.9178 0.9315 0.9678 0.9543

Page 40: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

35

From the above results, it is seen that packet delivery ratio is higher in TRP when

compared to DSR. Both the implemented protocols TRP and DSR are tested with two

cases. Only 20 nodes are used to test these networks, since increasing the number of mobile

nodes in the network couldn’t be handled by the given network configuration. To maintain

authenticity, Network configuration is not altered in any of the test cases.

Page 41: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

36

6. CONCLUSION AND FUTURE WORK

6.1 Conclusion

An opportunistic network with 20 mobile nodes is simulated to implement the

project. The temporary and intermittent connectivity’s between the nodes is taken as an

opportunity to cooperate data forwarding in the simulated opportunistic network. Data

transfer is set sequentially from node 0 to node 19 and data is transferred to all the nodes

by minimizing the message delay and maximizing the acceptance rate and throughput of

the simulation. Malicious nodes are avoided and the network is refreshed and rerouted

when malicious nodes enter the network. DSR routing protocol is also implemented to

opportunistic networks to compare its results with the results of TRP. From the results of

the test cases, it is seen that TRP’s performance is better than DSR for opportunistic

networks. This project also implemented calculating remaining energies of the nodes. A

protocol that is light weight, efficient and that requires no path breaking or repairs is

implemented. TRP performance is studied in terms of acceptance rate, delay and

throughput by computer simulations and is found out that the acceptance rate is higher in

TRP than in DSR.

6.2 Future Work

TRP is different from the other protocols in that TRP nodes know when new nodes

join the network and when nodes leave the network. But due to the limitations in NS2

simulator, managing incoming and outgoing nodes is not implemented. This could be

implemented by using other simulators which allow to kill the nodes. In this method, the

mobility of the nodes is minimized. Mobility of the nodes could be increased too. General

network traffic can also be introduced to make the evaluation of the network more realistic.

Page 42: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

37

7. BIBLIOGRAPHY AND REFERENCES

[1] P. Lau, "Topology refresh data forwarding protocol for opportunistic networks," in

Wireless Telecommunications Symposium (WTS), 2015, New York, 2015.

[2] L. Pelusi, "Opportunistic Networking: Data Forwarding in disconnected mobile

adhoc networks".

[3] D. B. Johnson, "Dynamic Source Routing in Ad Hoc Wireless Networks,"

Pittsburgh, 1996.

[4] Rivanvx, "Wikipedia," [Online]. Available:

https://en.wikipedia.org/wiki/Ns_(simulator). [Accessed 15 November 2015].

[5] A. R. Tammineni, "Implementation of simulation to enhance wireless ad-hoc

networks performance using the MAC protocol," Texas A&M University, Corpus

Christi, 2015.

[6] A. Sher, "Simulation of attacks in a wireless sensor network using NS-2," Texas

A&M University, Corpus Christi, 2015.

[7] B. Todupunuri, "Detection of misbehavior in delay tolerant networks," Texas A&M

University, Corpus Christi, 2015.

[8] D. Matte, "Implementation of prototype network early warning alarm system

applying defense in depth Approach," Texas A&M University, Corpus Christi,

2015.

Page 43: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

38

8. APPENDIX

Code for Implementing Topology Refresh protocol

=================== #Creating variables =================

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) 1000 ;# max packet in ifq

set val(nn) 20 ;# number of mobilenodes

set val(rp) AODV ;# routing protocol

set val(x) 600 ;# X topography value

set val(y) 600 ;# Y topography value

===================#Create Simulator ======================

set ns [new Simulator]

#CREATE TRACE FILE

set tracefd [open base.tr w]

$ns trace-all $tracefd

$ns use-newtrace

set f0 [open out0.tr w]

set f1 [open out1.tr w]

set f2 [open out2.tr w]

===================#Create NAM Trace File ==================

set natr [open base.nam w]

$ns namtrace-all-wireless $natr $val(x) $val(y)

#CREAT A FINISH FUNCTION

proc finish {} {

global ns natr tracefd windowVsTime2 f0 f1 f2

$ns flush-trace

close $natr

close $tracefd

close $f0

close $f1

close $f2

#Call xgraph to display the results

exec xgraph out0.tr out1.tr out2.tr -geometry 800x400 &

exec nam base.nam

exit 0

}

===================#CREATE TOPOLOGY======================

set topo [new Topography]

Page 44: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

39

$topo load_flatgrid $val(x) $val(y)

===================#Create General Operation Directory =============

set god [create-god $val(nn)]

======================#Configure Node =========================

$ns node-config -adhocRouting $val(rp) \

-llType $val(ll) \

-macType $val(mac) \

-ifqType $val(ifq) \

-ifqLen $val(ifqlen) \

-antType $val(ant) \

-propType $val(prop) \

-phyType $val(netif) \

-channelType $val(chan) \

-topoInstance $topo \

-agentTrace ON \

-routerTrace ON \

-macTrace OFF \

-movementTrace ON

======================#Create Nodes ============================

set nodelist {}

for {set i 0} {[expr $i < $val(nn)]} {incr i} {

set node($i) [$ns node]

$node($i) color blue

$ns at 0.0 "$node($i) color blue"

if {$i!=30} {

lappend nodelist $i }

}

=====================#Set Initial Node Position ====================

for {set i 0} {$i < $val(nn)} {incr i} {

$ns initial_node_pos $node($i) 20 }

=====================#Place The Nodes ==========================

$node(0) set X_ 100.00

$node(0) set Y_ 100.00

$node(0) set Z_ 0.0

$node(1) set X_ 450.00

$node(1) set Y_ 200.00

$node(1) set Z_ 0.0

$node(2) set X_ 550.00

$node(2) set Y_ 270.00

$node(2) set Z_ 0.0

$node(3) set X_ 250.00

$node(3) set Y_ 590.00

$node(3) set Z_ 0.0

$node(4) set X_ 570.00

Page 45: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

40

$node(4) set Y_ 500.00

$node(4) set Z_ 0.0

========= #Setting random location for the nodes to move in the network=======

proc myRand {min max} {

set range [expr {$max - $min + 1}]

return [expr {$min + int(rand() * $range)}]

}

proc ymyRand {min max} {

set range [expr {$max - $min + 1}]

return [expr {$min + int(rand() * $range)}]

}

======================#Setting motion for nodes ====================

set xr -1;

set yr -1;

for {set i 0} {$i < $val(nn)} {incr i} {

while {$xr == [set xr [myRand 600 400]]} {

}

while {$yr == [set yr [ymyRand 500 600]]} {

}

$ns at 0.0 "$node($i) setdest $xr $yr 30.0"

$ns at 8.8 "$node($i) setdest 100 200 30.0"

$ns at 9.0 "$node($i) setdest $xr $yr 30.0"

$ns at 0.1 "$node($i) setdest $xr $yr 30.0"

$ns at 0.2 "$node($i) setdest $xr $yr 30.0"

$ns at 0.5 "$node($i) setdest $xr 200.0 30.0"

$ns at 1.0 "$node($i) setdest $xr $yr 30.0"

$ns at 1.5 "$node($i) setdest 200.0 $yr 30.0"

$ns at 2.0 "$node($i) setdest $xr $yr 30.0"

$ns at 2.5 "$node($i) setdest $xr 200.0 30.0"

$ns at 3.0 "$node($i) setdest $xr $yr 30.0"

$ns at 3.5 "$node($i) setdest 200.0 $yr 30.0"

$ns at 4.0 "$node($i) setdest $xr $yr 30.0"

$ns at 4.5 "$node($i) setdest $xr 200.0 30.0"

$ns at 5.0 "$node($i) setdest $xr $yr 30.0"

$ns at 5.5 "$node($i) setdest 200.0 $yr 30.0"

$ns at 6.0 "$node($i) setdest $xr $yr 30.0"

$ns at 6.5 "$node($i) setdest $xr 200.0 30.0"

$ns at 7.0 "$node($i) setdest $xr $yr 30.0"

$ns at 7.5 "$node($i) setdest 200.0 $yr 30.0"

$ns at 8.0 "$node($i) setdest $xr $yr 30.0"

$ns at 8.5 "$node($i) setdest $xr 200.0 30.0"

$ns at 10.5 "$node($i) setdest $xr 200.0 30.0"

$ns at 11.0 "$node($i) setdest $xr $yr 30.0"

$ns at 12.5 "$node($i) setdest 200.0 $yr 30.0"

$ns at 13.0 "$node($i) setdest $xr $yr 30.0"

$ns at 11.5 "$node($i) setdest $xr 200.0 30.0"

$ns at 14.0 "$node($i) setdest $xr $yr 30.0"

$ns at 12.5 "$node($i) setdest 200.0 $yr 30.0"

Page 46: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

41

$ns at 16.0 "$node($i) setdest $xr $yr 30.0"

$ns at 15.5 "$node($i) setdest $xr 200.0 30.0"

$ns at 18.0 "$node($i) setdest $xr $yr 30.0"

$ns at 19.5 "$node($i) setdest 200.0 $yr 30.0"

$ns at 17.0 "$node($i) setdest $xr $yr 30.0"

$ns at 17.5 "$node($i) setdest $xr 200.0 30.0"

}

puts "\n\n\t\tNode Placement In Network\n"

puts "\t\t****************************"

for {set i 0} {$i < $val(nn)} {incr i} {

set node_x [$node($i) set X_]

set node_y [$node($i) set Y_]

puts "\nNode $i is Placed in $node_x and $node_y"

}

set ti 0

================= #Distance between nodes calculation ==============

set r [open distance.tr w]

#Location fixing for a single node

for {set i 0} {$i < $val(nn)} {incr i} {

set xx($i) [expr rand()*$val(x)]

set yy($i) [expr rand()*$val(y)]

$node($i) set X_ $xx($i)

$node($i) set Y_ $yy($i)

$node($i) set Z_ 0

}

================== # Distance Calculation ========================

for {set i 0} {$i < $val(nn) } { incr i } {

for {set j 0} {$j < $val(nn) } { incr j } {

set dx [expr $xx($i) - $xx($j)]

set dy [expr $yy($i) - $yy($j)]

set dx2 [expr $dx * $dx]

set dy2 [expr $dy * $dy]

set h2 [expr $dx2 + $dy2]

set h($i-$j) [expr pow($h2, 0.5)]

}

}

for {set i 0} {$i<$val(nn)} {incr i} {

set neigh($i) {}

for {set j 0} {$j<$val(nn)} {incr j} {

if {$i!=$j} {

set node1_x [$node($i) set X_]

set node1_y [$node($i) set Y_]

set node2_x [$node($j) set X_]

set node2_y [$node($j) set Y_]

set dif_x [expr $node1_x-$node2_x]

set dif_y [expr $node1_y-$node2_y]

set sq_x [expr {pow($dif_x,2)}]

Page 47: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

42

set sq_y [expr {pow($dif_y,2)}]

set dis [expr {sqrt([expr {$sq_x + $sq_y}])}]

puts "Distance between node($i) and node($j) is $dis"

#Nearest node Distance

if {$dis<250} {

lappend neigh($i) $j }

}

}

}

=============== #Creating Node 15 as a default source in the network=========

set sink 15

set nod {}

set uni {}

set check {}

foreach i $nodelist {

lappend nod $i

set r 0

while {$r!=1} {

set ran($i) [expr rand()*250]

set ran($i) [expr int($ran($i))]

if {[lsearch $check $ran($i)]==-1} {

#puts "Unique number of the node $i is $ran($i)"

lappend check $ran($i)

set r 1 }}}

set uni $check

set msg {}

set ti 0

============= #Creating Source and Destination node to transmit data ========

foreach j $nodelist {

lappend msg $j [$node($sink) set X_] [$node($sink) set Y_]

set udp($sink) [new Agent/UDP]

$ns attach-agent $node($sink) $udp($sink)

$udp($sink) set fid_ 2

set cbr($sink) [new Application/Traffic/CBR]

$cbr($sink) attach-agent $udp($sink)

$cbr($sink) set type_ CBR

$cbr($sink) set packet_size_ 1000

$cbr($sink) set rate_ 1Mb

$cbr($sink) set random_ false

set null($j) [new Agent/Null]

$ns attach-agent $node($j) $null($j)

$ns connect $udp($sink) $null($j)

if {$sink!=$j} {

Page 48: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

43

$ns at $ti "$cbr($sink) start"

$ns at $ti "$ns trace-annotate \" Node $sink transmits to node $j \""

$node($sink) color green

$ns at $ti "$node($sink) color green"

$ns at $ti "$node($sink) label Source"

set ti [expr $ti+0.1]

$ns at $ti "$cbr($sink) stop" }}

for {set i 0} {$i<5} {incr i} {

================ #Random node replies back to source node================

set no [expr rand()*[llength $nodelist]]

set no [expr int($no)]

set no [lindex $nodelist $no]

puts "The node $no is transmitting to Sink"

after 250

set udp($no) [new Agent/UDP]

$ns attach-agent $node($no) $udp($no)

$udp($no) set fid_ 2

set cbr($no) [new Application/Traffic/CBR]

$cbr($no) attach-agent $udp($no)

$cbr($no) set type_ CBR

$cbr($no) set packet_size_ 1000

$cbr($no) set rate_ 1Mb

$cbr($no) set random_ false

set null($sink) [new Agent/Null]

$ns attach-agent $node($sink) $null($sink)

$ns connect $udp($no) $null($sink)

$ns at $ti "$cbr($no) start"

$ns at $ti "$ns trace-annotate \" Node $no transmits to node $sink \""

set ti [expr $ti+0.5]

$ns at $ti "$cbr($no) stop"

===================== #Avoiding Malicious nodes ====================

set cx [$node($no) set X_]

set cy [$node($no) set Y_]

if {$cx>1000 && $cy > 1000} {

#Identified malicious node in the network

puts "The node $no is a malicious node"

puts "Referesh the protocol to transmit packets"

after 250

foreach j $nodelist {

lappend msg $j [$node($sink) set X_] [$node($sink) set Y_]

set udp($sink) [new Agent/UDP]

$ns attach-agent $node($sink) $udp($sink)

Page 49: Wireless sensor networks (WSNs) consist of small low-power ...sci.tamucc.edu/~cams/projects/482.pdf · 1.3 Introduction to NS2 Simulator ... Table 8 C++ code for Shortest Path

44

$udp($sink) set fid_ 2

set cbr($sink) [new Application/Traffic/CBR]

$cbr($sink) attach-agent $udp($sink)

$cbr($sink) set type_ CBR

$cbr($sink) set packet_size_ 1000

$cbr($sink) set rate_ 1Mb

$cbr($sink) set random_ false

set null($j) [new Agent/Null]

$ns attach-agent $node($j) $null($j)

$ns connect $udp($sink) $null($j)

$ns at $ti "$cbr($sink) start"

$ns at $ti "$ns trace-annotate \" Node $sink transmits to node $j \""

set ti [expr $ti+0.1]

$ns at $ti "$cbr($sink) stop"}

} else {

after 250

set temp $ran($no)

if {[lsearch $nod $no]!=-1} {

after 250

if {[lsearch $uni $temp]!=-1} {

after 250

} else {

puts "\nMalicious node is avoided and packet transmitted

successfully"

} } } }

================ #Identifying nodes energy in the network ================

for {set i 0} {$i<$val(nn)} {incr i} {

set r 0

while {$r!=1} {

set energy($i) [format "%.4f" [expr rand()*1000]]

if {$energy($i)>700} {

set r 1}}

puts "Remaining energy of the node $i is $energy($i)"}