Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
329 views39 pages

Lab File of Ad Hoc and Sensor Networks Lab (ETEC - 458) : Department of Information Technology

The document describes an experimental setup for a wireless sensor network (WSN). It discusses creating a WSN with single-hop and hierarchical network topologies in the ns-2 simulator. In a hierarchical topology, leaf nodes sense data and send it to cluster nodes, which average the data and forward it to the sink node. The user can specify the network type, number of nodes, and power level. The code examples show how to implement a leaf node component that interfaces with sensors, radio communication, and timers to sense data and send messages periodically.

Uploaded by

swati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
329 views39 pages

Lab File of Ad Hoc and Sensor Networks Lab (ETEC - 458) : Department of Information Technology

The document describes an experimental setup for a wireless sensor network (WSN). It discusses creating a WSN with single-hop and hierarchical network topologies in the ns-2 simulator. In a hierarchical topology, leaf nodes sense data and send it to cluster nodes, which average the data and forward it to the sink node. The user can specify the network type, number of nodes, and power level. The code examples show how to implement a leaf node component that interfaces with sensors, radio communication, and timers to sense data and send messages periodically.

Uploaded by

swati
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Lab File

Of
AD HOC AND SENSOR NETWORKS LAB
(ETEC – 458)

Department of Information Technology


Dr. AKHILESH DAS GUPTA INSTITUTE OF TECHNOLOGY &
MANAGEMENT

Submitted To : Submitted By :
Ms. Monica Swati
Assistant Professor, IT 03615603117
IT – F9
Swati IT - F9 ROLL NO. : 03615603117

INDEX
S No. NAME OF PARTICULARS SIGN

1. Study of Mobile Adhoc Network.

2. Wireless Sensor Network - Experimental Setup.

3. Implementation of AODV routing protocol in ns2.

4. Implementation of DSR routing protocol in ns2.

5. Implementation of DSDV routing protocol in ns2.

6. Creating Wireless Sensor Network (WSN) in ns2.

7. Creating shortest path for mobile sink in ns2.

8. Creating Blackhole attack in MANET using ns2.

9. Dynamic Nodes generation and traffic flow in ns2.

2
Swati IT - F9 ROLL NO. : 03615603117

PROGRAM NO-1

Aim : Study of Mobile Adhoc Network

Theory:
A mobile ad hoc network (MANET) is a continuously self-configuring, infrastructure-less network
of mobile devices connected wirelessly.

Each device in a MANET is free to move independently in any direction, and will therefore change
its links to other devices frequently. Each must forward traffic unrelated to its own use, and
therefore be a router. The primary challenge in building a MANET is equipping each device to
continuously maintain the information required to properly route traffic. Such networks may
operate by themselves or may be connected to the larger Internet. They may contain one or multiple
and different transceivers between nodes. This results in a highly dynamic, autonomous topology

MANETs are a kind of wireless ad hoc network (WANET) that usually has a routable networking
environment on top of a Link Layer ad hoc network. MANETs consist of a peer-to-peer, self-
forming, self-healing network. MANETs circa 2000-2015 typically communicate at radio
frequencies (30 MHz - 5 GHz)

The growth of laptops and 802.11/Wi-Fi wireless networking have made MANETs a popular
research topic since the mid-1990s. Many academic papers evaluate protocols and their abilities,
assuming varying degrees of mobility within a bounded space, usually with all nodes within a few
hops of each other. Different protocols are then evaluated based on measures such as the packet
drop rate, the overhead introduced by the routing protocol, end-to-end packet delays, network
throughput, ability to scale, etc.

Types:
1. Vehicular ad hoc networks (VANETs) are used for communication between vehicles and
roadside equipment. Intelligent vehicular ad hoc networks (InVANETs) are a kind of artificial
intelligence that helps vehicles to behave in intelligent manners during vehicle-to-vehicle collisions,
accidents.

2. Smart phone ad hoc networks (SPANs) leverage the existing hardware (primarily Bluetooth
and Wi-Fi) in commercially available smart phones to create peer-to-peer networks without relying
on cellular carrier networks, wireless access points, or traditional network infrastructure. SPANs
differ from traditional hub and spoke networks, such as Wi-Fi Direct, in that they support multi-hop

3
Swati IT - F9 ROLL NO. : 03615603117

relays and there is no notion of a group leader so peers can join and leave at will without destroying
the network.

3. Internet-based mobile ad-hoc networks (iMANETs) are ad hoc networks that link mobile
nodes and fixed Internet-gateway nodes. For example, multiple sub-MANETs may be connected in
a classic Hub-Spoke VPN to create a geographically distributed MANET. In such type of networks
normal ad hoc routing algorithms don't apply directly. One implementation of this is Persistent
System's CloudRelay.
Military or tactical MANETs are used by military units with emphasis on security, range, and
integration with existing systems. Common waveforms include the US Army's SRW.

4
Swati IT - F9 ROLL NO. : 03615603117

PROGRAM NO-2

Aim : Wireless Sensor Network - Experimental Setup

Theory:
Wireless sensor networks (WSN), sometimes called wireless sensor and actuator
networks (WSAN), are spatially distributed autonomous sensors to monitor physical or
environmental conditions, such as temperature, sound, pressure, etc. and to cooperatively pass their
data through the network to a main location. The more modern networks are bi-directional, also
enabling control of sensor activity. The development of wireless sensor networks was motivated by
military applications such as battlefield surveillance; today such networks are used in many
industrial and consumer applications, such as industrial process monitoring and control, machine
health monitoring, and so on.

Figure1: Wireless Sensor Network setup

In this wireless sensor network setup each wireless node has its own default address which is
shown in the figure that is

● 1 is the sink node address.

● 2, 8 and 14 are the cluster nodes addresses.

● 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 and 19 are the leaf node addresses.

When leaf node sends sensed data to the cluster node, cluster node does the average of the leaf
node data and will send it to the sink node. In this experiment the remote user can give three inputs
which are listed below
1. Network type: Remote user has the option to select any one of single hop network or
hierarchical network.

Single hop network: In this network, leaf nodes 3, 4, 5, 6 and 7 can be connected to the sink node.

5
Swati IT - F9 ROLL NO. : 03615603117

Hierarchical network: In this network, leaf nodes 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18
and 19 can be connected to the cluster nodes 2, 8 and 14 and these cluster nodes are connected to
the sink node.

2. Number of nodes: In a single hop network, the minimum number of nodes are 2 and the
maximum number of nodes selected is 6. If the user selects number of nodes as 4, then leaf nodes 3,
4 and 5 are connected to the sink node and thus the total number of nodes in the network is 4.

In a hierarchical network, minimum number of nodes are 3 and maximum number of nodes selected
is 19. If the user selects number of nodes as 10, then the leaf nodes 3, 4, 5, 6 and 7 gets connected to
the cluster node 2. Leaf nodes 9, 10 gets connected to the cluster node 8. The cluster nodes 2 and 8
are connected to the sink node 1. Thus the total number of nodes in the network is 10.

3. Power level: User can operate the wireless sensor network in different power levels.

Procedure

1. Implement the configuration file

1.1 Identify the interfaces required

1.2. Identify the components which are providing the required interfaces

1.3. Perform wiring

2. Implement the module file :This is the file, where we are implementing the actual task. Here
the tasks include Implementing two types of network, i.e centralized network and hierarchical
network. For that, we need 4sets on nodes(Gateway node, Sink node, Cluster head and leaf node)

3. Implement the make file

4. Burn the program to device and start functioning.

Creating Leaf node:

The components used are :

6
Swati IT - F9 ROLL NO. : 03615603117

components Main, leafnodeM, TimerC, LedsC, GenericComm;


components CC2420RadioC, SensirionHumidity;

implementation

/* Booting and initialization */


Main.StdControl -> TimerC.StdControl;
Main.StdControl -> leafnodeM.StdControl;
Main.StdControl -> GenericComm.Control;
Main.StdControl -> CC2420RadioC.StdControl;

/* Leds and Timers */


leafnodeM.Leds -> LedsC.Leds;
leafnodeM .Timer1 -> TimerC.Timer[unique("Timer")];
leafnodeM .Timer2 -> TimerC.Timer[unique("Timer")];
leafnodeM .Timer3 -> TimerC.Timer[unique("Timer")];
//leafnodeM.ADC -> Sensor;
//leafnodeM.ADCControl -> Sensor;

/*Radio related */
leafnodeM.CC2420Control -> CC2420RadioC.CC2420Control;
leafnodeM.SendMsg -> GenericComm.SendMsg[AM_INTMSG];
leafnodeM.ReceiveMsg -> GenericComm.ReceiveMsg[AM_INTMSG];

/* sensor reading MTS400 */


leafnodeM.ReadTemp -> SensirionHumidity.Temperature;
leafnodeM.ReadHum -> SensirionHumidity.Humidity;
leafnodeM.SensControl -> SensirionHumidity.SplitControl;

In the module file:

includes IntMsg;

module

provides
interface StdControl;
uses
{
interface Timer as Timer1; //Idle timer to reset
interface Timer as Timer2; //Sensing timer
interface Timer as Timer3;
interface Leds;
interface SendMsg;

7
Swati IT - F9 ROLL NO. : 03615603117

interface ReceiveMsg;
interface CC2420Control; //TxPower set
interface ADC as ReadTemp;
interface ADC as ReadHum;
interface SplitControl as SensControl;

command void health_packet(bool enable, uint16_t intv);


}
}
Implementation {

Write your code here;

event result_t Timer3.fired()


{
IntMsg *message = (IntMsg *)sendPkt.data;
atomic
{
message->val = temperature;
message->src = TOS_LOCAL_ADDRESS;
message->ptype = ntype;
addr_bak = address;
if(call SendMsg.send(addr_bak, sizeof(IntMsg), &sendPkt))
{
atomic
{
send_to_clHead = TRUE;
}
}
}
return SUCCESS;
}
event result_t SendMsg.sendDone(TOS_MsgPtr msg, result_t status)
{
IntMsg *message = (IntMsg *)sendPkt.data;
if(status == FAIL)
{
call Leds.redToggle();
}
if(send_to_clHead)
{
message->expid = 9;
atomic
{
message->dstads = addr_bak;
message->src = TOS_LOCAL_ADDRESS;
message->val = temperature;
}

8
Swati IT - F9 ROLL NO. : 03615603117

if(call SendMsg.send(20, sizeof(IntMsg), &sendPkt))


{
atomic
{
send_to_clHead = FALSE;
}
call Leds.yellowToggle();
}
}
return SUCCESS;
}

Cluster head:
The components used are

components Main, clusternodeM, TimerC, LedsC;


components GenericComm, CC2420RadioC;

implementation
{

components Main, clusternodeM, TimerC, LedsC;


components GenericComm, CC2420RadioC;

Main.StdControl -> TimerC.StdControl;


clusternodeM .Timer1 -> TimerC.Timer[unique("Timer")];
clusternodeM .Timer2 -> TimerC.Timer[unique("Timer")];
Main.StdControl -> clusternodeM.StdControl;
Main.StdControl -> GenericComm.Control;
Main.StdControl -> CC2420RadioC.StdControl;
clusternodeM.CC2420Control -> CC2420RadioC.CC2420Control;
clusternodeM.Leds -> LedsC.Leds;
clusternodeM.SendMsg -> GenericComm.SendMsg[AM_INTMSG];
clusternodeM.ReceiveMsg -> GenericComm.ReceiveMsg[AM_INTMSG];

In the module file:

includes IntMsg;

module

provides interface StdControl;


uses
{
interface Leds;
interface Timer as Timer1;
interface Timer as Timer2;

9
Swati IT - F9 ROLL NO. : 03615603117

interface SendMsg;
interface ReceiveMsg;
interface CC2420Control;

}
}

implementation
{

Write your code here;

event result_t SendMsg.sendDone(TOS_MsgPtr msg, result_t status)


{
IntMsg *message = (IntMsg *)sendPkt.data;
if(status == FAIL)
{
call Leds.redToggle();
}
if(send_to_sink)
{
send_to_sink = FALSE;
message->expid = 9;
message->dstads = 1;
message->val = avg;
if(call SendMsg.send(20, sizeof(IntMsg), &sendPkt))
{
call Leds.yellowToggle();
}
}
return SUCCESS;
}
/*
* Idle timer resets all the LEDs and turnof other timers */
event result_t Timer1.fired()
{
call Leds.set(0);
return SUCCESS;
}
}

Sink node
components used are

10
Swati IT - F9 ROLL NO. : 03615603117

components Main, SinknodeM, TimerC, LedsC;

components GenericComm, CC2420RadioC;

implementation

Main.StdControl -> SinknodeM.StdControl;

SinknodeM .Timer1 -> TimerC.Timer[unique("Timer")];

SinknodeM .Timer2 -> TimerC.Timer[unique("Timer")];

Main.StdControl -> CC2420RadioC.StdControl;

SinknodeM.CC2420Control -> CC2420RadioC.CC2420Control;

SinknodeM.Leds -> LedsC.Leds;

Main.StdControl -> GenericComm.Control;

SinknodeM.SendMsg -> GenericComm.SendMsg[AM_INTMSG];

SinknodeM.ReceiveMsg -> GenericComm.ReceiveMsg[AM_INTMSG];

In the module file:

module SinknodeM
{
provides
interface StdControl;
uses
{
interface Leds;
interface Timer as Timer1;
interface Timer as Timer2;
interface SendMsg;
interface ReceiveMsg;
interface CC2420Control;
}

implementation
{

write your code here

11
Swati IT - F9 ROLL NO. : 03615603117

event result_t Timer2.fired()


{
sendPacket(avg);
return SUCCESS;
}
event result_t Timer1.fired()
{
call Leds.set(0);
return SUCCESS;
}
}

Gateway node/main sink

components used are

components Main, msinkM, LedsC, TimerC, GenericComm, HPLUARTC;

implementation
{

Main.StdControl -> msinkM.StdControl;


Main.StdControl -> TimerC.StdControl;
Main.StdControl -> GenericComm.Control;
msinkM.HPLUART -> HPLUARTC;
msinkM.SendMsg -> GenericComm.SendMsg[AM_INTMSG];
msinkM.UARTTimer -> TimerC.Timer[unique("Timer")];
msinkM.Leds -> LedsC.Leds;
msinkM.ReceiveMsg -> GenericComm.ReceiveMsg[AM_INTMSG];
}

In module file:
includes IntMsg;

module
{
provides
interface StdControl;
uses
{
interface Leds;
interface SendMsg;
interface HPLUART;
interface ReceiveMsg;
interface Timer as UARTTimer;
}
}

12
Swati IT - F9 ROLL NO. : 03615603117

implementation
{

write your code here

event result_t UARTTimer.fired()


{
IntMsg* message;
if(buf_head_index == buf_tail_index)
{
call UARTTimer.stop();
call Leds.redToggle();
timer_started = FALSE;
return SUCCESS;
}
call UARTTimer.stop();
message = (IntMsg *)TosMsgPtr_buf[buf_tail_index]->data;
atomic
{
lastPkt[lastIndex++] = '/';
lastPkt[lastIndex++] = '9';
lastPkt[lastIndex++] = '*';
if(message->src < 10)
{
lastPkt[lastIndex++] = (char)(message->src + 48);
}
else
{
{
lastPkt[lastIndex++] = (char)((message->src % 10) + 48);
lastPkt[lastIndex++] = '1';
}
lastPkt[lastIndex++] = '*' ;
convToNumber((message -> dstads) ) ;
lastPkt[lastIndex++] = '*' ;
convToNumber((message -> val)) ;
lastPkt[lastIndex++] = '$' ;
lastPkt[lastIndex] = '\0' ;

/** Added to reinitialize "lastIndex"


lastIndex = 0;
call HPLUART.put(lastPkt[count++]);
}
buf_tail_index = (buf_tail_index + 1) % (MSG_BUF_SIZE + 1);
return SUCCESS;
}
event async result_t HPLUART.putDone()
{
atomic
{

13
Swati IT - F9 ROLL NO. : 03615603117

if( count == strlen(lastPkt) )


{
/** Added to reinitialize "count"
call UARTTimer.start(TIMER_REPEAT, 5);
count = 0;
call Leds.yellowToggle();
}
else
{
call HPLUART.put(lastPkt[count]) ;
count++ ;
}
}
return SUCCESS;
}

PROGRAM NO-3
Aim: Implementation of AODV routing protocol in ns2

14
Swati IT - F9 ROLL NO. : 03615603117

Theory:
The reactive on demand routing protocols establish the route to a particular destination only if it is
needed. Adhoc on-demand Distance Vector (AODV) is one of the commonly used reactive on
demand routing protocols in mobile ad hoc network (MANET). AODV is a reactive enhancement
of the DSDV protocol. The route discovery process involves ROUTE REQUEST (RREQ) and
ROUTE REPLY (RREP) packets. The source node initiates the route requested through the route
discovery process using RREQ packets. The generated route request is forwarded to the neighbors
of the source node and this process is repeated till it reaches the destination. On receiving a RREQ
packet, an intermediate node with route to destination, it generates a RREP containing the number
of hops required to reach the destination. All intermediate nodes that participates in relaying this
reply to the source node creates a forward route to destination. AODV minimizes the number of
packets involved in route discovery by establishing routes on-demand. The sample15.tcl shows a
node configuration for a wireless mobile node that runs AODV as its adhoc routing protocol. Prior
to the establishment of communication between the source and receiver node, the routing protocol
should be mentioned to find the route between them. Data Transmission is established between
nodes using UDP agent and CBR traffic.

Procedure:

# Simulator Instance Creation


set ns [new Simulator]

#Fixing the co-ordinate of simutaion area


set val(x) 500
set val(y) 500
# Define options
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagation model
set val(netif) Phy/WirelessPhy ;# network interface type
set val(mac) Mac/802_11 ;# MAC type
set val(ifq) Queue/DropTail/PriQueue ;# interface queue type
set val(ll) LL ;# link layer type
set val(ant) Antenna/OmniAntenna ;# antenna model
set val(ifqlen) 50 ;# max packet in ifq
set val(nn) 10 ;# number of mobilenodes
set val(rp) AODV ;# routing protocol
set val(x) 500 ;# X dimension of topography
set val(y) 500 ;# Y dimension of topography
set val(stop) 10.0 ;# time of simulation end

# set up topography object


set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)
# general operational descriptor- storing the hop details in the network
create-god $val(nn)

# configure the nodes


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

15
Swati IT - F9 ROLL NO. : 03615603117

-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

# Node Creation

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

set node_($i) [$ns node]


$node_($i) color black

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

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


$node_($i) set Y_ [expr rand()*$val(y)]
$node_($i) set Z_ 0

}
#******************************Defining Communication Between node0 and all nodes
****************************8

for {set i 1} {$i < 10} {incr i} {


# Defining a transport agent for sending
set udp [new Agent/UDP]

# Attaching transport agent to sender node


$ns attach-agent $node_($i) $udp

# Defining a transport agent for receiving


set null [new Agent/Null]

# Attaching transport agent to receiver node


$ns attach-agent $node_(0) $null

#Connecting sending and receiving transport agents


$ns connect $udp $null

#Defining Application instance


set cbr [new Application/Traffic/CBR]

16
Swati IT - F9 ROLL NO. : 03615603117

# Attaching transport agent to application agent


$cbr attach-agent $udp

#Packet size in bytes and interval in seconds definition


$cbr set packetSize_ 512
$cbr set interval_ 0.1

# data packet generation starting time


$ns at 1.0 "$cbr start"

# data packet generation ending time


#$ns at 6.0 "$cbr stop"

OUTPUT:

17
Swati IT - F9 ROLL NO. : 03615603117

18
Swati IT - F9 ROLL NO. : 03615603117

PROGRAM NO-4
Aim: Implementation of DSR routing protocol in ns2

Theory:
The reactive on demand routing protocols establish the route to a particular destination only if it is
needed. Dynamic Source Routing (DSR) is one of the commonly used reactive on demand routing
protocols in mobile ad hoc network (MANET). DSR is a loop-free, source based, on-demand
routing protocol in which each node maintains a route cache consisting of source routes known by
the node. A source node initiates a fresh route discovery process only if it does not already have a
valid route to the destination in its route cache. The entries in the route cache are regularly updated
as new routes are known. The sample16.tcl shows a node configuration for a wireless mobile node
that runs DSR as its adhoc routing protocol. Prior to the establishment of communication between
the source and receiver node, the routing protocol should be mentioned to find the route between
them. Data Transmission is established between nodes using UDP agent and CBR traffic.

Procedure:

# Simulator Instance Creation


set ns [new Simulator]

#Fixing the co-ordinate of simutaion area


set val(x) 500
set val(y) 500
# Define options
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagation model
set val(netif) Phy/WirelessPhy ;# network interface type
set val(mac) Mac/802_11 ;# MAC type
set val(ifq) CMUPriQueue ;# Interface queue type
set val(ll) LL ;# link layer type
set val(ant) Antenna/OmniAntenna ;# antenna model
set val(ifqlen) 50 ;# max packet in ifq
set val(nn) 10 ;# number of mobilenodes
set val(rp) DSR ;# routing protocol
set val(x) 500 ;# X dimension of topography
set val(y) 500 ;# Y dimension of topography
set val(stop) 10.0 ;# time of simulation end

# set up topography object


set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)

# general operational descriptor- storing the hop details in the network


create-god $val(nn)

# configure the nodes

19
Swati IT - F9 ROLL NO. : 03615603117

$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

# Node Creation

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

set node_($i) [$ns node]


$node_($i) color black

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

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


$node_($i) set Y_ [expr rand()*$val(y)]
$node_($i) set Z_ 0

}
Defining Communication between node0 and all nodes ****************************

for {set i 1} {$i < 3} {incr i} {


# Defining a transport agent for sending
set udp [new Agent/UDP]

# Attaching transport agent to sender node


$ns attach-agent $node_($i) $udp

# Defining a transport agent for receiving


set null [new Agent/Null]

# Attaching transport agent to receiver node


$ns attach-agent $node_(0) $null

#Connecting sending and receiving transport agents


$ns connect $udp $null

#Defining Application instance


set cbr [new Application/Traffic/CBR]

20
Swati IT - F9 ROLL NO. : 03615603117

# Attaching transport agent to application agent


$cbr attach-agent $udp

#Packet size in bytes and interval in seconds definition


$cbr set packetSize_ 512
$cbr set interval_ 0.1

# data packet generation starting time


$ns at 1.0 "$cbr start"

# data packet generation ending time


#$ns at 6.0 "$cbr stop"

21
Swati IT - F9 ROLL NO. : 03615603117

OUTPUT:

22
Swati IT - F9 ROLL NO. : 03615603117

PROGRAM NO - 5
Aim: Implementation of DSDV routing protocol in ns2

Theory:
Proactive routing protocol maintains constant and updated routing information for each pair of
networking nodes by propagating route updates proactively at fixed interval of time. The periodic
and event-driven messages are responsible for route establishment and route maintenance. The
Destination-Sequenced Distance Vector (DSDV) protocol is the commonly used proactive routing
protocol in mobile ad hoc network (MANET). In DSDV, each node maintains a routing table with
one route entry for each destination in which the shortest path is recorded. It uses a destination
sequence number to avoid routing loops. The sample17.tcl shows a node configuration for a
wireless mobile node that runs DSDV as its adhoc routing protocol. Prior to the establishment of
communication between the source and receiver node, the routing protocol should be mentioned to
find the route between them. Data Transmission is established between nodes using UDP agent and
CBR traffic. Routing process follows DSDV routing protocol.

Procedure:

# Simulator Instance Creation


set ns [new Simulator]

#Fixing the co-ordinate of simulation area


set val(x) 500
set val(y) 500
# Define options
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagation model
set val(netif) Phy/WirelessPhy ;# network interface type
set val(mac) Mac/802_11 ;# MAC type
set val(ifq) Queue/DropTail/PriQueue ;# interface queue type
set val(ll) LL ;# link layer type
set val(ant) Antenna/OmniAntenna ;# antenna model
set val(ifqlen) 50 ;# max packet in ifq
set val(nn) 10 ;# number of mobilenodes
set val(rp) DSDV ;# routing protocol
set val(x) 500 ;# X dimension of topography
set val(y) 500 ;# Y dimension of topography
set val(stop) 10.0 ;# time of simulation end

# set up topography object


set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)

# general operational descriptor- storing the hop details in the network


create-god $val(nn)

# configure the nodes


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

23
Swati IT - F9 ROLL NO. : 03615603117

-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

# Node Creation

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

set node_($i) [$ns node]


$node_($i) color black

#******************************Defining Communication Between node0 and all nodes


****************************8

for {set i 1} {$i < 10} {incr i} {


# Defining a transport agent for sending
set udp [new Agent/UDP]

# Attaching transport agent to sender node


$ns attach-agent $node_($i) $udp

# Defining a transport agent for receiving


set null [new Agent/Null]

# Attaching transport agent to receiver node


$ns attach-agent $node_(0) $null

#Connecting sending and receiving transport agents


$ns connect $udp $null
4
#Defining Application instance
set cbr [new Application/Traffic/CBR]

# Attaching transport agent to application agent


$cbr attach-agent $udp

#Packet size in bytes and interval in seconds definition


$cbr set packetSize_ 512
$cbr set interval_ 0.1

24
Swati IT - F9 ROLL NO. : 03615603117

# data packet generation starting time


$ns at 1.0 "$cbr start"

# data packet generation ending time


#$ns at 6.0 "$cbr stop"

25
Swati IT - F9 ROLL NO. : 03615603117

OUTPUT:

26
Swati IT - F9 ROLL NO. : 03615603117

PROGRAM NO - 6
Aim: Creating Wireless Sensor Network (WSN) in ns2

Theory:
A wireless sensor network (WSN) consists of a large number of small sensor nodes that are
deployed in the area in which a factor is to be monitored. In wireless sensor network, energy model
is one of the optional attributes of a node. The energy model denotes the level of energy in a mobile
node. The components required for designing energy model includes initialEnergy, txPower,
rxPower, and idlePower. The “initialEnergy” represents the level of energy the node has at the
initial stage of simulation. “txPower” and “rxPower” denotes the energy consumed for transmitting
and receiving the packets. If the node is a sensor, the energy model should include a special
component called “sensePower”. It denotes the energy consumed during the sensing operation.
Apart from these components, it is important to specify the communication range (RXThresh_) and
sensing range of a node (CSThresh_). The sample 18.tcl designs a WSN in which sensor nodes are
configured with different communication and sensing range. Base Station is configured with highest
communication range. Data Transmission is established between nodes using UDP agent and CBR
traffic.

Procedure:

# Simulator Instance Creation


set ns [new Simulator]

#Fixing the co-ordinate of simulation area


set val(x) 600
set val(y) 600
# Define options
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagation model
set val(netif1) Phy/WirelessPhy ;# network interface type
set val(netif2) Phy/WirelessPhy ;# network interface type
set val(mac) Mac/802_11 ;# MAC type
set val(ifq) Queue/DropTail/PriQueue ;# interface queue type
set val(ll) LL ;# link layer type
set val(ant) Antenna/OmniAntenna ;# antenna model
set val(ifqlen) 50 ;# max packet in ifq
set val(nn) 10 ;# number of mobilenodes
set val(rp) AODV ;# routing protocol
set val(x) 600 ;# X dimension of topography
set val(y) 600 ;# Y dimension of topography
set val(stop) 10.0 ;# time of simulation end
set val(energymodel) EnergyModel ;#Energy set up
# set up topography object

27
Swati IT - F9 ROLL NO. : 03615603117

set topo [new Topography]


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

# general operational descriptor- storing the hop details in the network


create-god $val(nn)

#Transmission range setup

#********************************** UNITY GAIN, 1.5m HEIGHT OMNI DIRECTIONAL


ANTENNA SET UP **************

Antenna/OmniAntenna set X_ 0
Antenna/OmniAntenna set Y_ 0
Antenna/OmniAntenna set Z_ 1.5
Antenna/OmniAntenna set Gt_ 1.0
Antenna/OmniAntenna set Gr_ 1.0

#********************************** SET UP COMMUNICATION AND SENSING


RANGE ***********************************

#default communication range 250m

# Initialize the SharedMedia interface with parameters to make


# it work like the 914MHz Lucent WaveLAN DSSS radio interface
$val(netif1) set CPThresh_ 10.0
$val(netif1) set CSThresh_ 2.28289e-11 ;#sensing range of 500m
$val(netif1) set RXThresh_ 2.28289e-11 ;#communication range of 500m
$val(netif1) set Rb_ 2*1e6
$val(netif1) set Pt_ 0.2818
$val(netif1) set freq_ 914e+6
$val(netif1) set L_ 1.0

# Initialize the SharedMedia interface with parameters to make


# it work like the 914MHz Lucent WaveLAN DSSS radio interface
$val(netif2) set CPThresh_ 10.0
$val(netif2) set CSThresh_ 8.91754e-10 ;#sensing range of 200m
$val(netif2) set RXThresh_ 8.91754e-10 ;#communication range of 200m
$val(netif2) set Rb_ 2*1e6
$val(netif2) set Pt_ 0.2818
$val(netif2) set freq_ 914e+6
$val(netif2) set L_ 1.0

# configure the first 5 nodes with transmission range of 500m

$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(netif1) \

28
Swati IT - F9 ROLL NO. : 03615603117

-channelType $val(chan) \
-topoInstance $topo \
-energyModel $val(energymodel) \
-initialEnergy 10 \
-rxPower 0.5 \
-txPower 1.0 \
-idlePower 0.0 \
-sensePower 0.3 \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace ON

# Node Creation

set energy(0) 1000

$ns node-config -initialEnergy 1000 \


-rxPower 0.5 \
-txPower 1.0 \
-idlePower 0.0 \
-sensePower 0.3

set node_(0) [$ns node]


$node_(0) color black
# configure the remaining 5 nodes with transmission range of 200m

$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(netif2) \
-channelType $val(chan) \
-topoInstance $topo \
-energyModel $val(energymodel) \
-initialEnergy 10 \
-rxPower 0.5 \
-txPower 1.0 \
-idlePower 0.0 \
-sensePower 0.3 \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace ON
for {set i 1} {$i < 3} {incr i} {

set energy($i) [expr rand()*500]

$ns node-config -initialEnergy $energy($i) \

29
Swati IT - F9 ROLL NO. : 03615603117

-rxPower 0.5 \
-txPower 1.0 \
-idlePower 0.0 \
-sensePower 0.3
set node_($i) [$ns node]
$node_($i) color black

30
Swati IT - F9 ROLL NO. : 03615603117

OUTPUT:

31
Swati IT - F9 ROLL NO. : 03615603117

PROGRAM NO-7
Aim: Creating shortest path for mobile sink in ns2

Theory:
In the sensor network after clusterhead selection, cluster member sends data to clusterhead.
Clusterhead aggregates the received data from cluster member. In mobile sink network, only the
sink moves to collect data from clusterhead whereas in static sink case, data is sent in multiple hops
to sink from clusterhead. So sink mobility scheme achieves energy optimization with certain delay
due to the time taken for the arrival sink nearer to clusterhead. Hence the sink moves along the path
as per the shortest path algorithm. The code given below provides the logic for shortest path in grid
based clustering.

Procedure:

Initialize the variable


mc=0;
ec =1;
mx(mc), my(mc) = list of coordinates to which the mobile sink is required to move
for ( j= 1;j <= number_grids; j++) {
mpn = ec%2;
if ( mpn == 1) {
for ( i= 1;i <= number_grids; i++) {      px = (i-1 +0.5)*(communication_range);    
py = (j-1 +0.5)*(communication_range)      mx(mc) =px;      my(mc) =py   
mc =mc+1;     }     } else {     for (i= number_grids; i >= 1; i-1 ) {
px = (i-1 +0.5)*(communication_range);
py = (j-1 +0.5)*(communication_range)
mx(mc) =px;
my(mc) =py
mc =mc+1;
}
}
ec = ec +1;
}

32
Swati IT - F9 ROLL NO. : 03615603117

OUTPUT:

Sink node starting position is (0, 0).

33
Swati IT - F9 ROLL NO. : 03615603117

PROGRAM NO-8
Aim: Creating Blackhole attack in MANET using ns2

Theory:
A Mobile Ad hoc Network (MANET) comprises of mobile nodes that moves independently in an
open environment. Communication between the nodes in a MANET is enabled with the aid of
intermediate routers. The nature of MANET such as open medium, dynamic network topology, lack
of centralized monitoring, and lack of clear defense mechanisms makes it vulnerable to several
routing attacks. In MANET routing, there is a high probability for intermediate nodes to be
malicious that might be a threat to the security. Blackhole is the common attack in ad hoc routing in
which the malicious node uses the process of routing to state itself of being the shortest path to the
destination. Once it receives the data packets, it drops the data packets instead of forwarding them
to its neighbors. In sample20.tcl, the blackhole attacker does not obey the communication model.
Data Transmission is established between nodes using UDP agent and CBR traffic. Sender sends
the data via attacker. Source node transfers data to attacker that does not have shortest route to
Destination. Attacker does not forward data to its neighbours.

Procedure:

set udp [new Agent/UDP]

$ns attach-agent $node_($source) $udp

set null [new Agent/Null]

$ns attach-agent $node_($destination) $null

$ns connect $udp $null

set cbr [new Application/Traffic/CBR]

$cbr attach-agent $udp

$cbr set packetSize_ 512

$cbr set interval_ 0.1

$ns at 3.0 "$cbr start"

$ns at 3.1 "$ns trace-annotate \" Data transmission from source node to destination node\""

$ns at 5.0 "[$node_(5) set ragent_] malicious"

34
Swati IT - F9 ROLL NO. : 03615603117

$ns at 5.0 "$node_(5) color red"

$ns at 5.0 "$node_(5) label Attacker"

$ns at 5.1 "$ns trace-annotate \" Node_5 is malicious node which node drops the packet \""

$ns at 10.0 "$cbr stop"

35
Swati IT - F9 ROLL NO. : 03615603117

OUTPUT:

36
Swati IT - F9 ROLL NO. : 03615603117

PROGRAM NO-9
Aim: Dynamic Nodes generation and traffic flow in ns2
#Create a simulator object
set ns [new Simulator]

#Tell the simulator to use dynamic routing


$ns rtproto DV

#Open the nam trace file


set nf [open out.nam w]
$ns namtrace-all $nf

#Define a 'finish' procedure


proc finish {} {
        global ns nf
        $ns flush-trace
#Close the trace file
        close $nf
#Execute nam on the trace file
        exec nam out.nam &
        exit 0
}

#Create seven nodes


for {set i 0} {$i < 7} {incr i} {
        set n($i) [$ns node]
}

#Create links between the nodes


for {set i 0} {$i < 7} {incr i} {
        $ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms DropTail
}

#Create a UDP agent and attach it to node n(0)


set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0

# Create a CBR traffic source and attach it to udp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

#Create a Null agent (a traffic sink) and attach it to node n(3)


set null0 [new Agent/Null]
$ns attach-agent $n(3) $null0

37
Swati IT - F9 ROLL NO. : 03615603117

#Connect the traffic source with the traffic sink


$ns connect $udp0 $null0 

#Schedule events for the CBR agent and the network dynamics
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n(1) $n(2)
$ns rtmodel-at 2.0 up $n(1) $n(2)
$ns at 4.5 "$cbr0 stop"
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"

#Run the simulation


$ns run

38
Swati IT - F9 ROLL NO. : 03615603117

Output:

So, here is the output sequence. 


First, nodes are created 

Then, down the links and see how dynamically traffic flow by following the other
path 

Then , here is the final output . 

39

You might also like