You are on page 1of 13

NS Lab Assignment – 7

Name: Nikhil Singh Roll No: 119CS0170

Ad Hoc On-Demand Distance Vector (AODV)

An Ad Hoc On-Demand Distance Vector (AODV) is a routing protocol designed for


wireless and mobile ad hoc networks. This protocol establishes routes to
destinations on demand and supports both unicast and multicast routing. The AODV
protocol was jointly developed by Nokia Research Center, the University of
California, Santa Barbara and the University of Cincinnati in 1991.
The AODV protocol builds routes between nodes only if they are requested by source nodes.
AODV is therefore considered an on-demand algorithm and does not create any extra traffic for
communication along links. The routes are maintained as long as they are required by the sources.
They also form trees to connect multicast group members. AODV makes use of sequence numbers
to ensure route freshness. They are self-starting and loop-free besides scaling to numerous mobile
nodes.

In AODV, networks are silent until connections are established. Network nodes that need
connections broadcast a request for connection. The remaining AODV nodes forward the message
and record the node that requested a connection. Thus, they create a series of temporary routes
back to the requesting node.

A node that receives such messages and holds a route to a desired node sends a backward
message through temporary routes to the requesting node. The node that initiated the request
uses the route containing the least number of hops through other nodes. The entries that are not
used in routing tables are recycled after some time. If a link fails, the routing error is passed back
to the transmitting node and the process is repeated.

In AODV, nodes discover routes in request-response cycles. A node requests a route to a


destination by broadcasting an RREQ message to all its neighbors. When a node receives an RREQ
message but does not have a route to the requested destination, it in turn broadcasts the RREQ
message. Also, it remembers a reverse-route to the requesting node which can be used to forward
subsequent responses to this RREQ. This process repeats until the RREQ reaches a node that has a
valid route to the destination. This node (which can be the destination itself) responds with an
RREP message. This RREP is unicast along the reverse-routes of the intermediate nodes until it
reaches the original requesting node. Thus, at the end of this request-response cycle a
bidirectional route is established between the requesting node and the destination. When a node
loses connectivity to its next hop, the node invalidates its route by sending an RERR to all nodes
that potentially received its RREP.
Question 1
CODE
#include <iostream>
#include <cmath>
#include "ns3/aodv-module.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/v4ping-helper.h"
#include "ns3/yans-wifi-helper.h"
#include "ns3/netanim-module.h"

using namespace
ns3; class
AodvExample {
public:
AodvExample ();

bool Configure (int argc, char **argv);


/// Run simulation void Run (); /**
* Report results
* \param os the output stream
*/
void Report (std::ostream & os);

private:

// parameters /// Number of nodes


uint32_t size; /// Distance between
nodes, meters double step; ///
Simulation time, seconds double
totalTime; /// Write per-device PCAP
traces if true bool pcap;
/// Print routes if true
bool printRoutes;

// network
/// nodes used in the example
NodeContainer nodes;
/// devices used in the example
NetDeviceContainer devices;
/// interfaces used in the example
Ipv4InterfaceContainer interfaces; private:
/// Create the nodes void
CreateNodes (); /// Create
the devices void
CreateDevices (); ///
Create the network void
InstallInternetStack ();
/// Create the simulation applications
void InstallApplications ();
};

int main (int argc, char **argv)


{
AodvExample test;
if (!test.Configure (argc, argv))
NS_FATAL_ERROR ("Configuration failed. Aborted.");

test.Run ();
test.Report (std::cout);
return 0;
}

//-----------------------------------------------------------------------------
AodvExample::AodvExample () :
size (10), step
(50), totalTime
(100), pcap
(true),
printRoutes (true)
{}

bool
AodvExample::Configure (int argc, char **argv)
{
// Enable AODV logs by default. Comment this if too noisy
// LogComponentEnable("AodvRoutingProtocol", LOG_LEVEL_ALL);

SeedManager::SetSeed (12345);
CommandLine cmd;

cmd.AddValue ("pcap", "Write PCAP traces.", pcap);


cmd.AddValue ("printRoutes", "Print routing table dumps.",
printRoutes); cmd.AddValue ("size", "Number of nodes.", size);
cmd.AddValue ("time", "Simulation time, s.", totalTime); cmd.AddValue
("step", "Grid step, m", step);

cmd.Parse (argc, argv);


return true;
}

void
AodvExample::Run () {
// Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", UintegerValue (1)); // enable
rts cts all the time. CreateNodes ();
CreateDevices ();
InstallInternetStack ();
InstallApplications ();
AnimationInterface anim("119CS0171_LAB_7.xml"); std::cout

<< "Starting simulation for " << totalTime << " s ...\n";

Simulator::Stop (Seconds (totalTime));


Simulator::Run ();
Simulator::Destroy ();
}

void
AodvExample::CreateDevices ()
{
WifiMacHelper wifiMac;
wifiMac.SetType ("ns3::AdhocWifiMac");
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
wifiPhy.SetChannel (wifiChannel.Create ()); WifiHelper wifi;
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", StringValue
("OfdmRate6Mbps"), "RtsCtsThreshold", UintegerValue (0));
devices = wifi.Install (wifiPhy, wifiMac, nodes);

if (pcap)
{
wifiPhy.EnablePcapAll (std::string ("aodv"));
}
}

void
AodvExample::InstallInternetStack ()
{
AodvHelper aodv;

if (printRoutes)
{
Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper> ("aodv.routes",
std::ios::out);
aodv.PrintRoutingTableAllAt (Seconds (8), routingStream);
}
}

void
AodvExample::InstallApplications ()
{
V4PingHelper ping (interfaces.GetAddress (size - 1));
ping.SetAttribute ("Verbose", BooleanValue (true));

ApplicationContainer p = ping.Install (nodes.Get (0));


p.Start (Seconds (0));
p.Stop (Seconds (totalTime) - Seconds (0.001));
// move node away
Ptr<Node> node = nodes.Get (size/2);
Ptr<MobilityModel> mob = node->GetObject<MobilityModel> ();
Simulator::Schedule (Seconds (totalTime/3), &MobilityModel::SetPosition, mob, Vector (1e5, 1e5, 1e5));
}

Wireshark

NetAnim
Question 2
CODE

#include "ns3/aodv-module.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/wifi-module.h"
#include "ns3/v4ping-helper.h"
#include "ns3/position-allocator.h"
#include "ns3/propagation-loss-model.h"
#include "ns3/applications-module.h"
#include "ns3/v4ping.h"
#include "ns3/flow-monitor-module.h"
#include "ns3/udp-client-server-helper.h"
#include "ns3/udp-server.h"
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>

using namespace ns3;


using namespace std;

class AodvExample
{
public:
AodvExample();
/// Configure script parameters, \return true on successful configuration
bool Configure(int argc, char **argv);
/// Run simulation void Run();
/// Report results void
Report(std::ostream &os);

YansWifiPhyHelper wifiPhy;
private: // parameters ///
Number of nodes uint32_t
size;
/// Distance between nodes, meters
double step;
/// Simulation time, seconds
double simTime;
/// Write per-device PCAP traces if true
bool pcap;
/// Print routes if true bool

printRoutes; string topology =

"scratch/manet.csv"; double txrange =

50; uint32_t interval = 10; bool verbose

= false; bool tracing = true; char

*outputFilename = (char *)"manet";

private: void
CreateNodes(); void
CreateDevices(); void
InstallInternetStack(); void
InstallApplications(); };

NS_LOG_COMPONENT_DEFINE("ManetTest");

int main(int argc, char **argv)


{
AodvExample test;
test.wifiPhy.SetErrorRateModel ("ns3::NistErrorRateModel");

if (!test.Configure(argc, argv))
NS_FATAL_ERROR("Configuration failed. Aborted.");

test.Run();
test.Report(std::cout);
return 0;
}

//-----------------------------------------------------------------------------
AodvExample::AodvExample() : size(10),
step(5),
simTime(50),
pcap(true),
printRoutes(false)
{}

bool AodvExample::Configure(int argc, char **argv)


{
// Enable AODV logs by default. Comment this if too noisy
// LogComponentEnable("AodvRoutingProtocol", LOG_LEVEL_ALL); SeedManager::SetSeed(12345);
CommandLine cmd;

cmd.AddValue("pcap", "Write PCAP traces.", pcap);


cmd.AddValue("printRoutes", "Print routing table dumps.", printRoutes);
cmd.AddValue("size", "Number of nodes.", size); cmd.AddValue("simTime",
"Simulation time, in seconds.", simTime); cmd.AddValue("outputFilename",
"Output filename", outputFilename); cmd.AddValue("topology", "Topology
file.", topology);
cmd.AddValue("txrange", "Transmission range per node, in meters.", txrange);
cmd.AddValue("interval", "Interval between each iteration.", interval);
cmd.AddValue("verbose", "Verbose tracking.", verbose);
cmd.AddValue("tracing", "Enable pcap tracing", tracing);
cmd.AddValue("outputFilename", "Output filename", outputFilename);
cmd.Parse(argc, argv);

if (verbose)
{
LogComponentEnable("UdpSocket", LOG_LEVEL_INFO);
LogComponentEnable("UdpServer", LOG_LEVEL_INFO);
}

return true;
}

void AodvExample::Run() {
// Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", UintegerValue (1)); //
enable rts cts all the time. CreateNodes();
CreateDevices();
InstallInternetStack();
InstallApplications();

// std::cout << "Starting simulation for " << simTime << " s ...\n";

Simulator::Stop(Seconds(simTime));
Simulator::Run();
Simulator::Destroy();
}

void AodvExample::Report(std::ostream &)


{}

void AodvExample::CreateNodes()
{
std::cout << "Creating " << (unsigned)size << " nodes with transmission range " << txrange << "m.\n";
nodes.Create(size);
// Name nodes
for (uint32_t i = 0; i < size; ++i)
{ std::ostringstream
os; os << "node-" <<
i;
Names::Add(os.str(), nodes.Get(i));
}

Ptr<ListPositionAllocator> positionAllocS = CreateObject<ListPositionAllocator>();


std::string line;
ifstream file(topology);

uint16_t i = 0;
;
double vec[3];

if (file.is_open())
{
while (getline(file, line))
{

// std::cout<<line<< '\n';
char seps[] = ","; char *token;
token = strtok(&line[0], seps);
// std::cout << token << "\n";

while (token != NULL)


{
// printf("[%s]\n", token);
vec[i] = atof(token);
i++;
token = strtok(NULL, ",");
if (i == 3)
{
// std::cout << "\n" << vec[0] << " " << vec[1] << " " << vec[2] << "\n";
positionAllocS->Add(Vector(vec[1], vec[2], 0.0)); i = 0;
}
}
}
file.close();
}
else
{
std::cout << "Error in csv file" << '\n';
}
MobilityHelper mobilityS;
mobilityS.SetPositionAllocator(positionAllocS);
mobilityS.SetMobilityModel("ns3::ConstantPositionMobilityModel"); // whatever it is
mobilityS.Install(nodes);
}

void AodvExample::CreateDevices()
{

wifiMac.SetType("ns3::AdhocWifiMac");
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default();
wifiChannel.AddPropagationLoss("ns3::RangePropagationLossModel",
"MaxRange", DoubleValue(txrange));
wifiPhy.SetChannel(wifiChannel.Create());
WifiHelper wifi;
wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
"DataMode", StringValue("OfdmRate6Mbps"), "RtsCtsThreshold",
UintegerValue(0)); devices = wifi.Install(wifiPhy, wifiMac, nodes);

if (pcap)
{
wifiPhy.EnablePcapAll(std::string("aodv"));
}
}
void AodvExample::InstallInternetStack()
{
AodvHelper aodv;
// you can configure AODV attributes here using aodv.Set(name, value)
InternetStackHelper stack;
stack.SetRoutingHelper(aodv); // has effect on the next Install
() stack.Install(nodes); Ipv4AddressHelper address;
address.SetBase("10.0.0.0", "255.0.0.0"); interfaces =
address.Assign(devices); for (uint32_t i = 0; i < (size / 2); i++)
{
serverAddress[i] = Address(interfaces.GetAddress(i));
}
if (printRoutes)
{
Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper> ("aodv.routes",
std::ios::out);
aodv.PrintRoutingTableAllAt (Seconds (8), routingStream);
}
}
apps.Start(Seconds(interval_start));
apps.Stop(Seconds(interval_end));
interval_start = interval_end + 1.0;
interval_end = interval_start + interval;
}
Simulator::Run();
k = 0;
monitor->CheckForLostPackets();
Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier>(flowmon.GetClassifier());
std::map<FlowId, FlowMonitor::FlowStats> stats = monitor->GetFlowStats();

for (std::map<FlowId, FlowMonitor::FlowStats>::const_iterator i = stats.begin(); i != stats.end(); ++i)


{
Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow(i->first);

if ((t.sourceAddress < "10.0.0.101") && (t.destinationAddress < "10.0.0.101"))


{
if ((i->second.txBytes >= 1000) || (i->second.rxBytes >= 1000)) //&&(i->second.txBytes ==
i>second.rxBytes))
{
k++;
}

// std::cout << "Flow " << i->first << " (" << t.sourceAddress << " -> " << t.destinationAddress << ")\n";
// std::cout << " Tx Bytes: " << i->second.txBytes << "\n";
// std::cout << " Rx Bytes: " << i->second.rxBytes << "\n";
// std::cout << " Throughput: " << i->second.rxBytes * 8.0 / (i->second.timeLastRxPacket.GetSeconds()
- i->second.timeFirstTxPacket.GetSeconds())/1024/1024 << " Mbps\n";
}
}

uint64_t timeDiff = (rxTimeLast - txTimeFirst);


Simulator::Destroy(); }

OUTPUT

You might also like