diff --git a/AUTHORS b/AUTHORS
index 7ade1a3d3..f016de8f2 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -6,6 +6,7 @@ Mehdi Benamor (mehdi.benamor@telecom-bretagne.eu)
Raj Bhattacharjea (raj.b@gatech.edu)
Timo Bingmann (timo.bingmann@student.kit.edu)
Pavel Boyko (boyko@iitp.ru)
+Elena Buchatskaia (borovkovaes@iitp.ru)
Gustavo Carneiro (gjc@inescporto.pt, gjcarneiro@gmail.com)
Angelos Chatzipapas (chatzipa@ceid.upatras.gr)
Luis Cortes (cortes@gatech.edu)
diff --git a/CHANGES.html b/CHANGES.html
index 1beecb862..eb469ebb7 100644
--- a/CHANGES.html
+++ b/CHANGES.html
@@ -59,6 +59,10 @@ event with a context different from the execution context of the caller. This AP
by the ns-3 logging system to report the execution context of each log line.
Object::DoStart : Users who need to complete their object setup at the start of a simulation
can override this virtual method, perform their adhoc setup, and then, must chain up to their parent.
+
+Aod hoc On-Demand Distance Vector (AODV) routing model,
+RFC 3561
+
Changes to existing API:
@@ -122,6 +126,9 @@ sched.SetTypeId ("ns3::ListScheduler");
Simulator::SetScheduler (sched);
+ Extensions to IPv4 Ping application: verbose output and the ability to configure different ping
+sizes and time intervals (via new attributes)
+
Changed behavior:
diff --git a/RELEASE_NOTES b/RELEASE_NOTES
index 94ee6d58b..de91a904e 100644
--- a/RELEASE_NOTES
+++ b/RELEASE_NOTES
@@ -31,10 +31,12 @@ http://www.nsnam.org/wiki/index.php/Installation
New user-visible features
-------------------------
- * The ns-3 logging macros (NS_LOG_*) now report automatically the node id
- of the event which called the macro.
+ a) The ns-3 logging macros (NS_LOG_*) now report automatically the node id
+ of the event which called the macro.
-API changes from ns-3.5
+ b) Ad hoc On-Demand Distance Vector (AODV) routing model according to RFC 3561.
+
+API changes from ns-3.6
-----------------------
API changes for this release are documented in the file CHANGES.html.
diff --git a/examples/routing/aodv.cc b/examples/routing/aodv.cc
new file mode 100644
index 000000000..de1de85cd
--- /dev/null
+++ b/examples/routing/aodv.cc
@@ -0,0 +1,214 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2009 IITP RAS
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * This is an example script for AODV manet routing protocol.
+ *
+ * Authors: Pavel Boyko
+ */
+
+#include "ns3/aodv-module.h"
+#include "ns3/core-module.h"
+#include "ns3/common-module.h"
+#include "ns3/node-module.h"
+#include "ns3/helper-module.h"
+#include "ns3/mobility-module.h"
+#include "ns3/contrib-module.h"
+#include "ns3/wifi-module.h"
+#include "ns3/v4ping-helper.h"
+#include
+#include
+
+using namespace ns3;
+
+/**
+ * \brief Test script.
+ *
+ * This script creates 1-dimensional grid topology and then ping last node from the first one:
+ *
+ * [10.0.0.1] <-- step --> [10.0.0.2] <-- step --> [10.0.0.3] <-- step --> [10.0.04]
+ *
+ * ping 10.0.0.4
+ */
+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);
+
+private:
+ ///\name 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;
+ //\}
+
+ ///\name network
+ //\{
+ NodeContainer nodes;
+ NetDeviceContainer devices;
+ Ipv4InterfaceContainer interfaces;
+ //\}
+
+private:
+ void CreateNodes ();
+ void CreateDevices ();
+ void InstallInternetStack ();
+ 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 (120),
+ totalTime (10),
+ pcap (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 ("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 ();
+
+ std::cout << "Starting simulation for " << totalTime << " s ...\n";
+
+ Simulator::Stop (Seconds (totalTime));
+ Simulator::Run ();
+ Simulator::Destroy ();
+}
+
+void
+AodvExample::Report (std::ostream &)
+{
+}
+
+void
+AodvExample::CreateNodes ()
+{
+ std::cout << "Creating " << (unsigned)size << " nodes " << step << " m apart.\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));
+ }
+ // Create static grid
+ MobilityHelper mobility;
+ mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
+ "MinX", DoubleValue (0.0),
+ "MinY", DoubleValue (0.0),
+ "DeltaX", DoubleValue (step),
+ "DeltaY", DoubleValue (0),
+ "GridWidth", UintegerValue (size),
+ "LayoutType", StringValue ("RowFirst"));
+ mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
+ mobility.Install (nodes);
+}
+
+void
+AodvExample::CreateDevices ()
+{
+ NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
+ wifiMac.SetType ("ns3::AdhocWifiMac");
+ YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
+ YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
+ wifiPhy.SetChannel (wifiChannel.Create ());
+ WifiHelper wifi = WifiHelper::Default ();
+ wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", StringValue ("wifia-6mbs"), "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);
+ stack.Install (nodes);
+ Ipv4AddressHelper address;
+ address.SetBase ("10.0.0.0", "255.0.0.0");
+ interfaces = address.Assign (devices);
+}
+
+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));
+
+ // move node away
+ Ptr node = nodes.Get (size/2);
+ Ptr mob = node->GetObject ();
+ Simulator::Schedule (Seconds (totalTime/3), &MobilityModel::SetPosition, mob, Vector (1e5, 1e5, 1e5));
+}
+
diff --git a/examples/routing/wscript b/examples/routing/wscript
index bff2f8b0e..c3404d2c7 100644
--- a/examples/routing/wscript
+++ b/examples/routing/wscript
@@ -44,3 +44,7 @@ def build(bld):
obj = bld.create_ns3_program('simple-routing-ping6',
['csma', 'internet-stack'])
obj.source = 'simple-routing-ping6.cc'
+
+ obj = bld.create_ns3_program('aodv',
+ ['wifi', 'internet-stack', 'aodv'])
+ obj.source = 'aodv.cc'
diff --git a/src/applications/v4ping/v4ping.cc b/src/applications/v4ping/v4ping.cc
index 8523439f5..b23f45484 100644
--- a/src/applications/v4ping/v4ping.cc
+++ b/src/applications/v4ping/v4ping.cc
@@ -20,10 +20,10 @@
#include "ns3/ipv4-address.h"
#include "ns3/socket.h"
#include "ns3/uinteger.h"
+#include "ns3/boolean.h"
#include "ns3/inet-socket-address.h"
#include "ns3/packet.h"
#include "ns3/trace-source-accessor.h"
-#include "ns3/simulator.h"
namespace ns3 {
@@ -41,6 +41,19 @@ V4Ping::GetTypeId (void)
Ipv4AddressValue (),
MakeIpv4AddressAccessor (&V4Ping::m_remote),
MakeIpv4AddressChecker ())
+ .AddAttribute ("Verbose",
+ "Produce usual output.",
+ BooleanValue (false),
+ MakeBooleanAccessor (&V4Ping::m_verbose),
+ MakeBooleanChecker ())
+ .AddAttribute ("Interval", "Wait interval seconds between sending each packet.",
+ TimeValue (Seconds (1)),
+ MakeTimeAccessor (&V4Ping::m_interval),
+ MakeTimeChecker ())
+ .AddAttribute ("Size", "The number of data bytes to be sent, real packet will be 8 (ICMP) + 20 (IP) bytes longer.",
+ UintegerValue (56),
+ MakeUintegerAccessor (&V4Ping::m_size),
+ MakeUintegerChecker (16))
.AddTraceSource ("Rtt",
"The rtt calculated by the ping.",
MakeTraceSourceAccessor (&V4Ping::m_traceRtt));
@@ -49,9 +62,14 @@ V4Ping::GetTypeId (void)
}
V4Ping::V4Ping ()
- : m_socket (0),
- m_seq (0)
-{}
+ : m_interval (Seconds (1)),
+ m_size (56),
+ m_socket (0),
+ m_seq (0),
+ m_verbose (false),
+ m_recv (0)
+{
+}
V4Ping::~V4Ping ()
{}
@@ -92,6 +110,7 @@ V4Ping::Receive (Ptr socket)
NS_ASSERT (realFrom.GetPort () == 1); // protocol should be icmp.
Ipv4Header ipv4;
p->RemoveHeader (ipv4);
+ uint32_t recvSize = p->GetSize ();
NS_ASSERT (ipv4.GetProtocol () == 1); // protocol should be icmp.
Icmpv4Header icmp;
p->RemoveHeader (icmp);
@@ -99,10 +118,11 @@ V4Ping::Receive (Ptr socket)
{
Icmpv4Echo echo;
p->RemoveHeader (echo);
- if (echo.GetSequenceNumber () == (m_seq - 1) &&
- echo.GetIdentifier () == 0)
+ std::map::iterator i = m_sent.find(echo.GetSequenceNumber());
+
+ if (i != m_sent.end () && echo.GetIdentifier () == 0)
{
- uint32_t buf[4];
+ uint32_t buf[m_size / 4];
uint32_t dataSize = echo.GetDataSize ();
if (dataSize == sizeof(buf))
{
@@ -111,13 +131,22 @@ V4Ping::Receive (Ptr socket)
if (buf[0] == GetNode ()->GetId () &&
buf[1] == GetApplicationId ())
{
- int64_t ts = buf[3];
- ts <<= 32;
- ts |= buf[2];
- Time sendTime = TimeStep (ts);
+ Time sendTime = i->second;
NS_ASSERT (Simulator::Now () > sendTime);
Time delta = Simulator::Now () - sendTime;
+
+ m_sent.erase (i);
+ m_avgRtt.Update (delta.GetMilliSeconds());
+ m_recv++;
m_traceRtt (delta);
+
+ if (m_verbose)
+ {
+ std::cout << recvSize << " bytes from " << realFrom.GetIpv4() << ":"
+ << " icmp_seq=" << echo.GetSequenceNumber ()
+ << " ttl=" << (unsigned)ipv4.GetTtl ()
+ << " time=" << delta.GetMilliSeconds() << " ms\n";
+ }
}
}
}
@@ -135,20 +164,8 @@ V4Ping::Write32 (uint8_t *buffer, uint32_t data)
}
void
-V4Ping::StartApplication (void)
+V4Ping::Send ()
{
- NS_LOG_FUNCTION (this);
- m_socket = Socket::CreateSocket (GetNode (), TypeId::LookupByName ("ns3::Ipv4RawSocketFactory"));
- NS_ASSERT (m_socket != 0);
- m_socket->SetAttribute ("Protocol", UintegerValue (1)); // icmp
- m_socket->SetRecvCallback (MakeCallback (&V4Ping::Receive, this));
- InetSocketAddress src = InetSocketAddress (Ipv4Address::GetAny (), 0);
- int status;
- status = m_socket->Bind (src);
- NS_ASSERT (status != -1);
- InetSocketAddress dst = InetSocketAddress (m_remote, 0);
- status = m_socket->Connect (dst);
- NS_ASSERT (status != -1);
Ptr p = Create ();
Icmpv4Echo echo;
echo.SetSequenceNumber (m_seq);
@@ -161,22 +178,17 @@ V4Ping::StartApplication (void)
// (where any difference would show up anyway) and borrow that code. Don't
// be too surprised when you see that this is a little endian convention.
//
- uint8_t data[4 * sizeof(uint32_t)];
+ uint8_t data[m_size];
+ for (uint32_t i = 0; i < m_size; ++i) data[i] = 0;
+ NS_ASSERT (m_size >= 16);
+
uint32_t tmp = GetNode ()->GetId ();
Write32 (&data[0 * sizeof(uint32_t)], tmp);
tmp = GetApplicationId ();
Write32 (&data[1 * sizeof(uint32_t)], tmp);
- int64_t now = Simulator::Now ().GetTimeStep ();
- tmp = now & 0xffffffff;
- Write32 (&data[2 * sizeof(uint32_t)], tmp);
-
- now >>= 32;
- tmp = now & 0xffffffff;
- Write32 (&data[3 * sizeof(uint32_t)], tmp);
-
- Ptr dataPacket = Create ((uint8_t *) &data, 16);
+ Ptr dataPacket = Create ((uint8_t *) &data, m_size);
echo.SetData (dataPacket);
p->AddHeader (echo);
Icmpv4Header header;
@@ -184,13 +196,57 @@ V4Ping::StartApplication (void)
header.SetCode (0);
p->AddHeader (header);
m_socket->Send (p, 0);
+ m_sent.insert (std::make_pair (m_seq - 1, Simulator::Now()));
+ m_next = Simulator::Schedule (m_interval, & V4Ping::Send, this);
+}
+
+void
+V4Ping::StartApplication (void)
+{
+ NS_LOG_FUNCTION (this);
+ m_started = Simulator::Now ();
+ if (m_verbose)
+ {
+ std::cout << "PING " << m_remote << " 56(84) bytes of data.\n";
+ }
+
+ m_socket = Socket::CreateSocket (GetNode (), TypeId::LookupByName ("ns3::Ipv4RawSocketFactory"));
+ NS_ASSERT (m_socket != 0);
+ m_socket->SetAttribute ("Protocol", UintegerValue (1)); // icmp
+ m_socket->SetRecvCallback (MakeCallback (&V4Ping::Receive, this));
+ InetSocketAddress src = InetSocketAddress (Ipv4Address::GetAny (), 0);
+ int status;
+ status = m_socket->Bind (src);
+ NS_ASSERT (status != -1);
+ InetSocketAddress dst = InetSocketAddress (m_remote, 0);
+ status = m_socket->Connect (dst);
+ NS_ASSERT (status != -1);
+
+ Send ();
}
void
V4Ping::StopApplication (void)
{
NS_LOG_FUNCTION (this);
+ m_next.Cancel();
m_socket->Close ();
+
+ if (m_verbose)
+ {
+ std::ostringstream os;
+ os.precision (4);
+ os << "--- " << m_remote << " ping statistics ---\n"
+ << m_seq << " packets transmitted, " << m_recv << " received, "
+ << ((m_seq - m_recv) * 100 / m_seq) << "% packet loss, "
+ << "time " << (Simulator::Now () - m_started).GetMilliSeconds () << "ms\n";
+
+ if (m_avgRtt.Count () > 0)
+ os << "rtt min/avg/max/mdev = " << m_avgRtt.Min() << "/" << m_avgRtt.Avg() << "/"
+ << m_avgRtt.Max() << "/" << m_avgRtt.Err()
+ << " ms\n";
+ std::cout << os.str();
+ }
}
diff --git a/src/applications/v4ping/v4ping.h b/src/applications/v4ping/v4ping.h
index ec7ed3820..3eb3e64b3 100644
--- a/src/applications/v4ping/v4ping.h
+++ b/src/applications/v4ping/v4ping.h
@@ -1,9 +1,27 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
#ifndef V4PING_H
#define V4PING_H
#include "ns3/application.h"
#include "ns3/traced-callback.h"
#include "ns3/nstime.h"
+#include "ns3/average.h"
+#include "ns3/simulator.h"
+#include
namespace ns3 {
@@ -35,11 +53,32 @@ private:
virtual void DoDispose (void);
uint32_t GetApplicationId (void) const;
void Receive (Ptr socket);
+ void Send ();
+ /// Remote address
Ipv4Address m_remote;
+ /// Wait interval seconds between sending each packet
+ Time m_interval;
+ /**
+ * Specifies the number of data bytes to be sent.
+ * The default is 56, which translates into 64 ICMP data bytes when combined with the 8 bytes of ICMP header data.
+ */
+ uint32_t m_size;
Ptr m_socket;
uint16_t m_seq;
TracedCallback m_traceRtt;
+ /// produce ping-style output if true
+ bool m_verbose;
+ /// received packets counter
+ uint32_t m_recv;
+ /// Start time to report total ping time
+ Time m_started;
+ /// Average rtt is ms
+ Average m_avgRtt;
+ /// Next packet will be sent
+ EventId m_next;
+ /// All sent but not answered packets. Map icmp seqno -> when sent
+ std::map m_sent;
};
} // namespace ns3
diff --git a/src/contrib/average.h b/src/contrib/average.h
new file mode 100644
index 000000000..fdb9e0da2
--- /dev/null
+++ b/src/contrib/average.h
@@ -0,0 +1,82 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2009 IITP RAS
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Authors: Pavel Boyko
+ */
+
+#ifndef AVERAGE_H
+#define AVERAGE_H
+#include
+#include
+#include
+
+/// Simple average, min, max and std. deviation calculator
+template
+class Average
+{
+public:
+ Average () :
+ size (0), min (std::numeric_limits::max ()), max (0), avg (0), avg2 (0)
+ {
+ }
+
+ /// Add new value
+ void Update (T const & x)
+ {
+ min = std::min (x, min);
+ max = std::max (x, max);
+ avg = (size * avg + x) / (size + 1);
+ avg2 = (size * avg2 + x * x) / (size + 1);
+ size++;
+ }
+ /// Reset statistics
+ void Reset ()
+ {
+ size = 0;
+ min = std::numeric_limits::max ();
+ max = 0;
+ avg = 0;
+ avg2 = 0;
+ }
+
+ ///\name Access results
+ //\{
+ uint32_t Count () const { return size; }
+ T Min () const { return min; }
+ T Max () const { return max; }
+ double Avg () const { return avg; }
+ double Err () const { return sqrt ((avg2 - avg*avg)/(size - 1)); }
+ //\}
+
+private:
+ uint32_t size;
+ T min, max;
+ double avg, avg2;
+};
+
+/// Print avg (err) [min, max]
+template
+std::ostream & operator<< (std::ostream & os, Average const & x)
+{
+ if (x.Count () != 0)
+ os << x.Avg () << " (" << x.Err () << ") [" << x.Min () << ", " << x.Max () << "]";
+ else
+ os << "NA"; // not avaliable
+ return os;
+}
+
+#endif /* AVERAGE_H */
diff --git a/src/contrib/wscript b/src/contrib/wscript
index 1a32d13c9..09c857581 100644
--- a/src/contrib/wscript
+++ b/src/contrib/wscript
@@ -43,6 +43,7 @@ def build(bld):
'file-config.h',
'config-store.h',
'flow-id-tag.h',
+ 'average.h',
]
if bld.env['ENABLE_GTK_CONFIG_STORE']:
diff --git a/src/devices/point-to-point/ppp-header.cc b/src/devices/point-to-point/ppp-header.cc
index 04fa8bc5e..5a2ec273c 100644
--- a/src/devices/point-to-point/ppp-header.cc
+++ b/src/devices/point-to-point/ppp-header.cc
@@ -56,7 +56,20 @@ PppHeader::GetInstanceTypeId (void) const
void
PppHeader::Print (std::ostream &os) const
{
- os << "Point-to-Point Protocol: " << m_protocol;
+ std::string proto;
+
+ switch(m_protocol)
+ {
+ case 0x0021: /* IPv4 */
+ proto = "IP (0x0021)";
+ break;
+ case 0x0057: /* IPv6 */
+ proto = "IPv6 (0x0057)";
+ break;
+ default:
+ NS_ASSERT_MSG(false, "PPP Protocol number not defined!");
+ }
+ os << "Point-to-Point Protocol: " << proto;
}
uint32_t
diff --git a/src/devices/wifi/adhoc-wifi-mac.cc b/src/devices/wifi/adhoc-wifi-mac.cc
index 3c11aa718..44af9e4d8 100644
--- a/src/devices/wifi/adhoc-wifi-mac.cc
+++ b/src/devices/wifi/adhoc-wifi-mac.cc
@@ -28,6 +28,7 @@
#include "ns3/pointer.h"
#include "ns3/packet.h"
#include "ns3/log.h"
+#include "ns3/trace-source-accessor.h"
NS_LOG_COMPONENT_DEFINE ("AdhocWifiMac");
@@ -48,6 +49,16 @@ AdhocWifiMac::GetTypeId (void)
PointerValue (),
MakePointerAccessor (&AdhocWifiMac::GetDcaTxop),
MakePointerChecker ())
+ .AddTraceSource ( "TxOkHeader",
+ "The header of successfully transmitted packet",
+ MakeTraceSourceAccessor (
+ &AdhocWifiMac::m_txOkCallback)
+ )
+ .AddTraceSource ( "TxErrHeader",
+ "The header of unsuccessfully transmitted packet",
+ MakeTraceSourceAccessor (
+ &AdhocWifiMac::m_txErrCallback)
+ )
;
return tid;
}
@@ -67,6 +78,7 @@ AdhocWifiMac::AdhocWifiMac ()
m_dca = CreateObject ();
m_dca->SetLow (m_low);
m_dca->SetManager (m_dcfManager);
+ m_dca->SetTxFailedCallback (MakeCallback (&AdhocWifiMac::TxFailed, this));
}
AdhocWifiMac::~AdhocWifiMac ()
{}
@@ -276,6 +288,14 @@ AdhocWifiMac::FinishConfigureStandard (enum WifiPhyStandard standard)
break;
}
}
-
-
+void
+AdhocWifiMac::TxOk (const WifiMacHeader &hdr)
+{
+ m_txOkCallback (hdr);
+}
+void
+AdhocWifiMac::TxFailed (const WifiMacHeader &hdr)
+{
+ m_txErrCallback (hdr);
+}
} // namespace ns3
diff --git a/src/devices/wifi/adhoc-wifi-mac.h b/src/devices/wifi/adhoc-wifi-mac.h
index 21bd2d8f2..0d19e5644 100644
--- a/src/devices/wifi/adhoc-wifi-mac.h
+++ b/src/devices/wifi/adhoc-wifi-mac.h
@@ -87,8 +87,9 @@ private:
AdhocWifiMac (const AdhocWifiMac & ctor_arg);
AdhocWifiMac &operator = (const AdhocWifiMac &o);
Ptr GetDcaTxop(void) const;
+ void TxOk (WifiMacHeader const &hdr);
+ void TxFailed (WifiMacHeader const &hdr);
virtual void FinishConfigureStandard (enum WifiPhyStandard standard);
-
Ptr m_dca;
Callback, Mac48Address, Mac48Address> m_upCallback;
Ptr m_stationManager;
@@ -97,6 +98,8 @@ private:
MacRxMiddle *m_rxMiddle;
Ptr m_low;
Ssid m_ssid;
+ TracedCallback m_txOkCallback;
+ TracedCallback m_txErrCallback;
};
} // namespace ns3
diff --git a/src/devices/wifi/wifi-net-device.cc b/src/devices/wifi/wifi-net-device.cc
index 8d34f5b6c..0f58265c2 100644
--- a/src/devices/wifi/wifi-net-device.cc
+++ b/src/devices/wifi/wifi-net-device.cc
@@ -91,6 +91,15 @@ WifiNetDevice::DoDispose (void)
NetDevice::DoDispose ();
}
+void
+WifiNetDevice::DoStart (void)
+{
+ m_phy->Start ();
+ m_mac->Start ();
+ m_stationManager->Start ();
+ NetDevice::DoStart ();
+}
+
void
WifiNetDevice::CompleteConfig (void)
{
diff --git a/src/devices/wifi/wifi-net-device.h b/src/devices/wifi/wifi-net-device.h
index 63190e340..1e9f4fb6d 100644
--- a/src/devices/wifi/wifi-net-device.h
+++ b/src/devices/wifi/wifi-net-device.h
@@ -104,6 +104,7 @@ public:
private:
virtual void DoDispose (void);
+ virtual void DoStart (void);
void ForwardUp (Ptr packet, Mac48Address from, Mac48Address to);
void LinkUp (void);
void LinkDown (void);
diff --git a/src/helper/aodv-helper.cc b/src/helper/aodv-helper.cc
new file mode 100644
index 000000000..e0e8f79af
--- /dev/null
+++ b/src/helper/aodv-helper.cc
@@ -0,0 +1,55 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2009 IITP RAS
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Authors: Pavel Boyko , written after OlsrHelper by Mathieu Lacage
+ */
+#include "aodv-helper.h"
+#include "ns3/aodv-routing-protocol.h"
+#include "ns3/node-list.h"
+#include "ns3/names.h"
+#include "ns3/ipv4-list-routing.h"
+
+namespace ns3
+{
+
+AodvHelper::AodvHelper() :
+ Ipv4RoutingHelper ()
+{
+ m_agentFactory.SetTypeId ("ns3::aodv::RoutingProtocol");
+}
+
+AodvHelper*
+AodvHelper::Copy (void) const
+{
+ return new AodvHelper (*this);
+}
+
+Ptr
+AodvHelper::Create (Ptr node) const
+{
+ Ptr agent = m_agentFactory.Create ();
+ node->AggregateObject (agent);
+ return agent;
+}
+
+void
+AodvHelper::Set (std::string name, const AttributeValue &value)
+{
+ m_agentFactory.Set (name, value);
+}
+
+}
diff --git a/src/helper/aodv-helper.h b/src/helper/aodv-helper.h
new file mode 100644
index 000000000..c0b7d347b
--- /dev/null
+++ b/src/helper/aodv-helper.h
@@ -0,0 +1,70 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2009 IITP RAS
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Authors: Pavel Boyko , written after OlsrHelper by Mathieu Lacage
+ */
+#ifndef AODVHELPER_H_
+#define AODVHELPER_H_
+
+#include "ns3/object-factory.h"
+#include "ns3/node.h"
+#include "node-container.h"
+#include "ipv4-routing-helper.h"
+
+namespace ns3
+{
+/**
+ * \ingroup aodv
+ * \brief Helper class that adds AODV routing to nodes.
+ */
+class AodvHelper : public Ipv4RoutingHelper
+{
+public:
+ AodvHelper();
+
+ /**
+ * \internal
+ * \returns pointer to clone of this OlsrHelper
+ *
+ * This method is mainly for internal use by the other helpers;
+ * clients are expected to free the dynamic memory allocated by this method
+ */
+ AodvHelper* Copy (void) const;
+
+ /**
+ * \param node the node on which the routing protocol will run
+ * \returns a newly-created routing protocol
+ *
+ * This method will be called by ns3::InternetStackHelper::Install
+ *
+ * TODO: support installing AODV on the subset of all available IP interfaces
+ */
+ virtual Ptr Create (Ptr node) const;
+ /**
+ * \param name the name of the attribute to set
+ * \param value the value of the attribute to set.
+ *
+ * This method controls the attributes of ns3::aodv::RoutingProtocol
+ */
+ void Set (std::string name, const AttributeValue &value);
+
+private:
+ ObjectFactory m_agentFactory;
+};
+
+}
+#endif /* AODVHELPER_H_ */
diff --git a/src/helper/v4ping-helper.cc b/src/helper/v4ping-helper.cc
index 0e2467205..e8767db76 100644
--- a/src/helper/v4ping-helper.cc
+++ b/src/helper/v4ping-helper.cc
@@ -30,6 +30,12 @@ V4PingHelper::V4PingHelper (Ipv4Address remote)
m_factory.Set ("Remote", Ipv4AddressValue (remote));
}
+void
+V4PingHelper::SetAttribute (std::string name, const AttributeValue &value)
+{
+ m_factory.Set (name, value);
+}
+
ApplicationContainer
V4PingHelper::Install (Ptr node) const
{
diff --git a/src/helper/v4ping-helper.h b/src/helper/v4ping-helper.h
index 1e2f5617e..a26029c78 100644
--- a/src/helper/v4ping-helper.h
+++ b/src/helper/v4ping-helper.h
@@ -55,6 +55,12 @@ public:
*/
ApplicationContainer Install (std::string nodeName) const;
+ /**
+ * \brief Configure ping applications attribute
+ * \param name attribute's name
+ * \param value attribute's value
+ */
+ void SetAttribute (std::string name, const AttributeValue &value);
private:
/**
* \internal
diff --git a/src/helper/wscript b/src/helper/wscript
index 1d6ddd850..6c845735c 100644
--- a/src/helper/wscript
+++ b/src/helper/wscript
@@ -1,7 +1,7 @@
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
def build(bld):
- helper = bld.create_ns3_module('helper', ['internet-stack', 'wifi', 'point-to-point', 'csma', 'olsr', 'nix-vector-routing', 'global-routing', 'onoff', 'packet-sink', 'udp-echo'])
+ helper = bld.create_ns3_module('helper', ['internet-stack', 'wifi', 'point-to-point', 'csma', 'olsr', 'global-routing', 'onoff', 'packet-sink', 'udp-echo'])
helper.source = [
'node-container.cc',
'net-device-container.cc',
@@ -29,6 +29,7 @@ def build(bld):
'ipv4-global-routing-helper.cc',
'ipv4-list-routing-helper.cc',
'ipv4-routing-helper.cc',
+ 'aodv-helper.cc',
'mesh-helper.cc',
'dot11s-installer.cc',
'flame-installer.cc',
@@ -68,9 +69,10 @@ def build(bld):
'nqos-wifi-mac-helper.h',
'qos-wifi-mac-helper.h',
'ipv4-nix-vector-helper.h',
- 'ipv4-global-routing-helper.h',
+ 'ipv4-global-routing-helper.h',
'ipv4-list-routing-helper.h',
'ipv4-routing-helper.h',
+ 'aodv-helper.h',
'mesh-helper.h',
'mesh-stack-installer.h',
'dot11s-installer.h',
diff --git a/src/internet-stack/icmpv4-l4-protocol.cc b/src/internet-stack/icmpv4-l4-protocol.cc
index 93bd54467..d62c8cd79 100644
--- a/src/internet-stack/icmpv4-l4-protocol.cc
+++ b/src/internet-stack/icmpv4-l4-protocol.cc
@@ -86,6 +86,7 @@ Icmpv4L4Protocol::SendMessage (Ptr packet, Ipv4Address dest, uint8_t typ
NS_ASSERT (ipv4 != 0 && ipv4->GetRoutingProtocol () != 0);
Ipv4Header header;
header.SetDestination (dest);
+ header.SetProtocol (PROT_NUMBER);
Socket::SocketErrno errno_;
Ptr route;
uint32_t oif = 0; //specify non-zero if bound to a source address
diff --git a/src/internet-stack/ipv4-interface.cc b/src/internet-stack/ipv4-interface.cc
index c54155152..9ca20cfa2 100644
--- a/src/internet-stack/ipv4-interface.cc
+++ b/src/internet-stack/ipv4-interface.cc
@@ -42,7 +42,8 @@ Ipv4Interface::GetTypeId (void)
.AddAttribute ("ArpCache",
"The arp cache for this ipv4 interface",
PointerValue (0),
- MakePointerAccessor (&Ipv4Interface::m_cache),
+ MakePointerAccessor (&Ipv4Interface::SetArpCache,
+ &Ipv4Interface::GetArpCache),
MakePointerChecker ())
;
;
@@ -128,6 +129,18 @@ Ipv4Interface::GetMetric (void) const
return m_metric;
}
+void
+Ipv4Interface::SetArpCache (Ptr a)
+{
+ m_cache = a;
+}
+
+Ptr
+Ipv4Interface::GetArpCache () const
+{
+ return m_cache;
+}
+
/**
* These are IP interface states and may be distinct from
* NetDevice states, such as found in real implementations
diff --git a/src/internet-stack/ipv4-interface.h b/src/internet-stack/ipv4-interface.h
index 0dcf732bb..671d58f07 100644
--- a/src/internet-stack/ipv4-interface.h
+++ b/src/internet-stack/ipv4-interface.h
@@ -56,12 +56,17 @@ public:
void SetNode (Ptr node);
void SetDevice (Ptr device);
+ void SetArpCache (Ptr);
/**
* \returns the underlying NetDevice. This method cannot return zero.
*/
Ptr GetDevice (void) const;
-
+ /**
+ * \return ARP cache used by this interface
+ */
+ Ptr GetArpCache () const;
+
/**
* \param metric configured routing metric (cost) of this interface
*
diff --git a/src/internet-stack/ipv4-l3-protocol.h b/src/internet-stack/ipv4-l3-protocol.h
index e3996559c..d56ea3754 100644
--- a/src/internet-stack/ipv4-l3-protocol.h
+++ b/src/internet-stack/ipv4-l3-protocol.h
@@ -241,7 +241,6 @@ private:
bool m_ipForward;
L4List_t m_protocols;
Ipv4InterfaceList m_interfaces;
- uint32_t m_nInterfaces;
uint8_t m_defaultTtl;
uint16_t m_identification;
Ptr m_node;
diff --git a/src/internet-stack/ipv4-raw-socket-impl.cc b/src/internet-stack/ipv4-raw-socket-impl.cc
index fe7a307b8..1a9777246 100644
--- a/src/internet-stack/ipv4-raw-socket-impl.cc
+++ b/src/internet-stack/ipv4-raw-socket-impl.cc
@@ -174,6 +174,7 @@ Ipv4RawSocketImpl::SendTo (Ptr p, uint32_t flags,
{
Ipv4Header header;
header.SetDestination (dst);
+ header.SetProtocol (m_protocol);
SocketErrno errno_ = ERROR_NOTERROR;//do not use errno as it is the standard C last error number
Ptr route;
uint32_t oif = 0; //specify non-zero if bound to a source address
@@ -247,6 +248,7 @@ Ipv4RawSocketImpl::ForwardUp (Ptr p, Ipv4Header ipHeader, Ptr p, Ipv4Address dest, uint16_t port)
{
Ipv4Header header;
header.SetDestination (dest);
+ header.SetProtocol (UdpL4Protocol::PROT_NUMBER);
Socket::SocketErrno errno_;
Ptr route;
uint32_t oif = 0; //specify non-zero if bound to a source address
diff --git a/src/internet-stack/wscript b/src/internet-stack/wscript
index 05f512b58..63d4b4e12 100644
--- a/src/internet-stack/wscript
+++ b/src/internet-stack/wscript
@@ -127,6 +127,8 @@ def build(bld):
'sequence-number.h',
'icmpv4.h',
'icmpv6-header.h',
+ # used by routing
+ 'ipv4-interface.h',
'ipv4-l3-protocol.h',
'ipv6-l3-protocol.h',
'ipv6-extension-header.h',
diff --git a/src/node/socket.cc b/src/node/socket.cc
index d75ab7180..33c9c8db6 100644
--- a/src/node/socket.cc
+++ b/src/node/socket.cc
@@ -45,7 +45,9 @@ Ptr
Socket::CreateSocket (Ptr node, TypeId tid)
{
Ptr s;
+ NS_ASSERT (node != 0);
Ptr socketFactory = node->GetObject (tid);
+ NS_ASSERT (socketFactory != 0);
s = socketFactory->CreateSocket ();
NS_ASSERT (s != 0);
return s;
diff --git a/src/routing/manet/aodv/aodv-neighbor.cc b/src/routing/manet/aodv/aodv-neighbor.cc
new file mode 100644
index 000000000..0816bb82b
--- /dev/null
+++ b/src/routing/manet/aodv/aodv-neighbor.cc
@@ -0,0 +1,173 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2009 IITP RAS
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Based on
+ * NS-2 AODV model developed by the CMU/MONARCH group and optimized and
+ * tuned by Samir Das and Mahesh Marina, University of Cincinnati;
+ *
+ * AODV-UU implementation by Erik Nordström of Uppsala University
+ * http://core.it.uu.se/core/index.php/AODV-UU
+ *
+ * Authors: Elena Buchatskaia
+ * Pavel Boyko
+ */
+
+#include "aodv-neighbor.h"
+#include "ns3/log.h"
+#include
+
+NS_LOG_COMPONENT_DEFINE ("AodvNeighbors");
+
+namespace ns3
+{
+namespace aodv
+{
+Neighbors::Neighbors (Time delay) :
+ m_ntimer (Timer::CANCEL_ON_DESTROY)
+{
+ m_ntimer.SetDelay(delay);
+ m_ntimer.SetFunction(&Neighbors::Purge, this);
+ m_txErrorCallback = MakeCallback (& Neighbors::ProcessTxError, this);
+}
+
+bool
+Neighbors::IsNeighbor (Ipv4Address addr)
+{
+ Purge ();
+ for (std::vector::const_iterator i = m_nb.begin ();
+ i != m_nb.end (); ++i)
+ {
+ if (i->m_neighborAddress == addr)
+ return true;
+ }
+ return false;
+}
+
+Time
+Neighbors::GetExpireTime (Ipv4Address addr)
+{
+ Purge ();
+ for (std::vector::const_iterator i = m_nb.begin (); i
+ != m_nb.end (); ++i)
+ {
+ if (i->m_neighborAddress == addr)
+ return (i->m_expireTime - Simulator::Now ());
+ }
+ return Seconds (0);
+}
+
+void
+Neighbors::Update (Ipv4Address addr, Time expire)
+{
+ for (std::vector::iterator i = m_nb.begin (); i != m_nb.end (); ++i)
+ if (i->m_neighborAddress == addr)
+ {
+ i->m_expireTime
+ = std::max (expire + Simulator::Now (), i->m_expireTime);
+ if (i->m_hardwareAddress == Mac48Address ())
+ i->m_hardwareAddress = LookupMacAddress (i->m_neighborAddress);
+ return;
+ }
+
+ NS_LOG_LOGIC ("Open link to " << addr);
+ Neighbor neighbor (addr, LookupMacAddress (addr), expire + Simulator::Now ());
+ m_nb.push_back (neighbor);
+ Purge ();
+}
+
+struct CloseNeighbor
+{
+ bool operator() (const Neighbors::Neighbor & nb) const
+ {
+ return ((nb.m_expireTime < Simulator::Now ()) || nb.close);
+ }
+};
+
+void
+Neighbors::Purge ()
+{
+ if (m_nb.empty ())
+ return;
+
+ CloseNeighbor pred;
+ if (!m_handleLinkFailure.IsNull ())
+ {
+ for (std::vector::iterator j = m_nb.begin (); j != m_nb.end (); ++j)
+ {
+ if (pred (*j))
+ {
+ NS_LOG_LOGIC ("Close link to " << j->m_neighborAddress);
+ m_handleLinkFailure (j->m_neighborAddress);
+ }
+ }
+ }
+ m_nb.erase (std::remove_if (m_nb.begin (), m_nb.end (), pred), m_nb.end ());
+ m_ntimer.Cancel ();
+ m_ntimer.Schedule ();
+}
+
+void
+Neighbors::ScheduleTimer ()
+{
+ m_ntimer.Cancel ();
+ m_ntimer.Schedule ();
+}
+
+void
+Neighbors::AddArpCache (Ptr a)
+{
+ m_arp.push_back (a);
+}
+
+void
+Neighbors::DelArpCache (Ptr a)
+{
+ m_arp.erase (std::remove (m_arp.begin (), m_arp.end (), a), m_arp.end ());
+}
+
+Mac48Address
+Neighbors::LookupMacAddress (Ipv4Address addr)
+{
+ Mac48Address hwaddr;
+ for (std::vector >::const_iterator i = m_arp.begin ();
+ i != m_arp.end (); ++i)
+ {
+ ArpCache::Entry * entry = (*i)->Lookup (addr);
+ if (entry != 0 && entry->IsAlive () && !entry->IsExpired ())
+ {
+ hwaddr = Mac48Address::ConvertFrom (entry->GetMacAddress ());
+ break;
+ }
+ }
+ return hwaddr;
+}
+
+void
+Neighbors::ProcessTxError (WifiMacHeader const & hdr)
+{
+ Mac48Address addr = hdr.GetAddr1 ();
+
+ for (std::vector::iterator i = m_nb.begin (); i != m_nb.end (); ++i)
+ {
+ if (i->m_hardwareAddress == addr)
+ i->close = true;
+ }
+ Purge ();
+}
+}
+}
+
diff --git a/src/routing/manet/aodv/aodv-neighbor.h b/src/routing/manet/aodv/aodv-neighbor.h
new file mode 100644
index 000000000..7709ffc68
--- /dev/null
+++ b/src/routing/manet/aodv/aodv-neighbor.h
@@ -0,0 +1,114 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2009 IITP RAS
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Based on
+ * NS-2 AODV model developed by the CMU/MONARCH group and optimized and
+ * tuned by Samir Das and Mahesh Marina, University of Cincinnati;
+ *
+ * AODV-UU implementation by Erik Nordström of Uppsala University
+ * http://core.it.uu.se/core/index.php/AODV-UU
+ *
+ * Authors: Elena Buchatskaia
+ * Pavel Boyko
+ */
+
+#ifndef AODVNEIGHBOR_H
+#define AODVNEIGHBOR_H
+
+#include "ns3/simulator.h"
+#include "ns3/timer.h"
+#include "ns3/ipv4-address.h"
+#include "ns3/callback.h"
+#include "ns3/wifi-mac-header.h"
+#include "ns3/arp-cache.h"
+#include
+
+namespace ns3
+{
+namespace aodv
+{
+class RoutingProtocol;
+/**
+ * \ingroup aodv
+ * \brief maintain list of active neighbors
+ */
+class Neighbors
+{
+public:
+ /// c-tor
+ Neighbors (Time delay);
+ /// Neighbor description
+ struct Neighbor
+ {
+ Ipv4Address m_neighborAddress;
+ Mac48Address m_hardwareAddress;
+ Time m_expireTime;
+ bool close;
+
+ Neighbor (Ipv4Address ip, Mac48Address mac, Time t) :
+ m_neighborAddress (ip), m_hardwareAddress (mac), m_expireTime (t),
+ close (false)
+ {
+ }
+ };
+ /// Return expire time for neighbor node with address addr, if exists, else return 0.
+ Time GetExpireTime (Ipv4Address addr);
+ /// Check that node with address addr is neighbor
+ bool IsNeighbor (Ipv4Address addr);
+ /// Update expire time for entry with address addr, if it exists, else add new entry
+ void Update (Ipv4Address addr, Time expire);
+ /// Remove all expired entries
+ void Purge ();
+ /// Schedule m_ntimer.
+ void ScheduleTimer ();
+ /// Remove all entries
+ void Clear () { m_nb.clear (); }
+
+ /// Add ARP cache to be used to allow layer 2 notifications processing
+ void AddArpCache (Ptr);
+ /// Don't use given ARP cache any more (interface is down)
+ void DelArpCache (Ptr);
+ /// Get callback to ProcessTxError
+ Callback GetTxErrorCallback () const { return m_txErrorCallback; }
+
+ ///\name Handle link failure callback
+ //\{
+ void SetCallback (Callback cb) { m_handleLinkFailure = cb;}
+ Callback GetCallback () const { return m_handleLinkFailure; }
+ //\}
+private:
+ /// link failure callback
+ Callback m_handleLinkFailure;
+ /// TX error callback
+ Callback m_txErrorCallback;
+ /// Timer for neighbor's list. Schedule Purge().
+ Timer m_ntimer;
+ /// vector of entries
+ std::vector m_nb;
+ /// list of ARP cached to be used for layer 2 notifications processing
+ std::vector > m_arp;
+
+ /// Find MAC address by IP using list of ARP caches
+ Mac48Address LookupMacAddress (Ipv4Address);
+ /// Process layer 2 TX error notification
+ void ProcessTxError (WifiMacHeader const &);
+};
+
+}
+}
+
+#endif /* AODVNEIGHBOR_H */
diff --git a/src/routing/manet/aodv/aodv-packet.cc b/src/routing/manet/aodv/aodv-packet.cc
new file mode 100644
index 000000000..66c67aa09
--- /dev/null
+++ b/src/routing/manet/aodv/aodv-packet.cc
@@ -0,0 +1,580 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2009 IITP RAS
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Based on
+ * NS-2 AODV model developed by the CMU/MONARCH group and optimized and
+ * tuned by Samir Das and Mahesh Marina, University of Cincinnati;
+ *
+ * AODV-UU implementation by Erik Nordström of Uppsala University
+ * http://core.it.uu.se/core/index.php/AODV-UU
+ *
+ * Authors: Elena Buchatskaia
+ * Pavel Boyko
+ */
+#include "aodv-packet.h"
+#include "ns3/address-utils.h"
+#include "ns3/packet.h"
+
+namespace ns3
+{
+namespace aodv
+{
+
+TypeHeader::TypeHeader (MessageType t) :
+ m_type (t), m_valid (true)
+{
+}
+
+TypeId
+TypeHeader::GetInstanceTypeId () const
+{
+ return TypeId ();
+}
+
+uint32_t
+TypeHeader::GetSerializedSize () const
+{
+ return 1;
+}
+
+void
+TypeHeader::Serialize (Buffer::Iterator i) const
+{
+ i.WriteU8 ((uint8_t) m_type);
+}
+
+uint32_t
+TypeHeader::Deserialize (Buffer::Iterator start)
+{
+ Buffer::Iterator i = start;
+ uint8_t type = i.ReadU8 ();
+ m_valid = true;
+ switch (type)
+ {
+ case AODVTYPE_RREQ:
+ case AODVTYPE_RREP:
+ case AODVTYPE_RERR:
+ case AODVTYPE_RREP_ACK:
+ {
+ m_type = (MessageType) type;
+ break;
+ }
+ default:
+ m_valid = false;
+ }
+ uint32_t dist = i.GetDistanceFrom (start);
+ NS_ASSERT (dist == GetSerializedSize ());
+ return dist;
+}
+
+void
+TypeHeader::Print (std::ostream &os) const
+{
+ switch (m_type)
+ {
+ case AODVTYPE_RREQ:
+ {
+ os << "RREQ" << "\n";
+ break;
+ }
+ case AODVTYPE_RREP:
+ {
+ os << "RREP" << "\n";
+ break;
+ }
+ case AODVTYPE_RERR:
+ {
+ os << "RERR" << "\n";
+ break;
+ }
+ case AODVTYPE_RREP_ACK:
+ {
+ os << "RREP_ACK" << "\n";
+ break;
+ }
+ default:
+ os << "UNKNOWN_TYPE";
+ }
+}
+
+bool
+TypeHeader::operator== (TypeHeader const & o) const
+{
+ return (m_type == o.m_type && m_valid == o.m_valid);
+}
+
+std::ostream &
+operator<< (std::ostream & os, TypeHeader const & h)
+{
+ h.Print (os);
+ return os;
+}
+
+//-----------------------------------------------------------------------------
+// RREQ
+//-----------------------------------------------------------------------------
+RreqHeader::RreqHeader (uint8_t flags, uint8_t reserved, uint8_t hopCount, uint32_t requestID, Ipv4Address dst,
+ uint32_t dstSeqNo, Ipv4Address origin, uint32_t originSeqNo) :
+ m_flags (flags), m_reserved (reserved), m_hopCount (hopCount), m_requestID (requestID), m_dst(dst),
+ m_dstSeqNo (dstSeqNo), m_origin(origin), m_originSeqNo (originSeqNo)
+{
+}
+
+TypeId
+RreqHeader::GetInstanceTypeId () const
+{
+ return TypeId ();
+}
+
+uint32_t
+RreqHeader::GetSerializedSize () const
+{
+ return 23;
+}
+
+void
+RreqHeader::Serialize (Buffer::Iterator i) const
+{
+ i.WriteU8 (m_flags);
+ i.WriteU8 (m_reserved);
+ i.WriteU8 (m_hopCount);
+ i.WriteHtonU32 (m_requestID);
+ WriteTo (i, m_dst);
+ i.WriteHtonU32 (m_dstSeqNo);
+ WriteTo (i, m_origin);
+ i.WriteHtonU32 (m_originSeqNo);
+}
+
+uint32_t
+RreqHeader::Deserialize (Buffer::Iterator start)
+{
+ Buffer::Iterator i = start;
+ m_flags = i.ReadU8 ();
+ m_reserved = i.ReadU8 ();
+ m_hopCount = i.ReadU8 ();
+ m_requestID = i.ReadNtohU32 ();
+ ReadFrom (i, m_dst);
+ m_dstSeqNo = i.ReadNtohU32 ();
+ ReadFrom (i, m_origin);
+ m_originSeqNo = i.ReadNtohU32 ();
+
+ uint32_t dist = i.GetDistanceFrom (start);
+ NS_ASSERT (dist == GetSerializedSize ());
+ return dist;
+}
+
+void
+RreqHeader::Print (std::ostream &os) const
+{
+ os << "RREQ ID " << m_requestID << "\n" << "destination: ipv4 " << m_dst
+ << " " << "sequence number " << m_dstSeqNo << "\n" << "source: ipv4 "
+ << m_origin << " " << "sequence number " << m_originSeqNo << "\n"
+ << "flags:\n" << "Gratuitous RREP " << (*this).GetGratiousRrep () << "\n"
+ << "Destination only " << (*this).GetDestinationOnly () << "\n"
+ << "Unknown sequence number " << (*this).GetUnknownSeqno () << "\n";
+}
+
+std::ostream &
+operator<< (std::ostream & os, RreqHeader const & h)
+{
+ h.Print (os);
+ return os;
+}
+
+void
+RreqHeader::SetGratiousRrep (bool f)
+{
+ if (f)
+ m_flags |= (1 << 5);
+ else
+ m_flags &= ~(1 << 5);
+}
+
+bool
+RreqHeader::GetGratiousRrep () const
+{
+ return (m_flags & (1 << 5));
+}
+
+void
+RreqHeader::SetDestinationOnly (bool f)
+{
+ if (f)
+ m_flags |= (1 << 4);
+ else
+ m_flags &= ~(1 << 4);
+}
+
+bool
+RreqHeader::GetDestinationOnly () const
+{
+ return (m_flags & (1 << 4));
+}
+
+void
+RreqHeader::SetUnknownSeqno (bool f)
+{
+ if (f)
+ m_flags |= (1 << 3);
+ else
+ m_flags &= ~(1 << 3);
+}
+
+bool
+RreqHeader::GetUnknownSeqno () const
+{
+ return (m_flags & (1 << 3));
+}
+
+bool
+RreqHeader::operator== (RreqHeader const & o) const
+{
+ return (m_flags == o.m_flags && m_reserved == o.m_reserved &&
+ m_hopCount == o.m_hopCount && m_requestID == o.m_requestID &&
+ m_dst == o.m_dst && m_dstSeqNo == o.m_dstSeqNo &&
+ m_origin == o.m_origin && m_originSeqNo == o.m_originSeqNo);
+}
+
+//-----------------------------------------------------------------------------
+// RREP
+//-----------------------------------------------------------------------------
+
+RrepHeader::RrepHeader (uint8_t prefixSize, uint8_t hopCount, Ipv4Address dst,
+ uint32_t dstSeqNo, Ipv4Address origin, Time lifeTime) :
+ m_flags (0), m_prefixSize (prefixSize), m_hopCount (hopCount),
+ m_dst (dst), m_dstSeqNo (dstSeqNo), m_origin (origin)
+{
+ m_lifeTime = uint32_t (lifeTime.GetMilliSeconds ());
+}
+
+TypeId
+RrepHeader::GetInstanceTypeId () const
+{
+ return TypeId ();
+}
+
+uint32_t
+RrepHeader::GetSerializedSize () const
+{
+ return 19;
+}
+
+void
+RrepHeader::Serialize (Buffer::Iterator i) const
+{
+ i.WriteU8 (m_flags);
+ i.WriteU8 (m_prefixSize);
+ i.WriteU8 (m_hopCount);
+ WriteTo (i, m_dst);
+ i.WriteHtonU32 (m_dstSeqNo);
+ WriteTo (i, m_origin);
+ i.WriteHtonU32 (m_lifeTime);
+}
+
+uint32_t
+RrepHeader::Deserialize (Buffer::Iterator start)
+{
+ Buffer::Iterator i = start;
+
+ m_flags = i.ReadU8 ();
+ m_prefixSize = i.ReadU8 ();
+ m_hopCount = i.ReadU8 ();
+ ReadFrom (i, m_dst);
+ m_dstSeqNo = i.ReadNtohU32 ();
+ ReadFrom (i, m_origin);
+ m_lifeTime = i.ReadNtohU32 ();
+
+ uint32_t dist = i.GetDistanceFrom (start);
+ NS_ASSERT (dist == GetSerializedSize ());
+ return dist;
+}
+
+void
+RrepHeader::Print (std::ostream &os) const
+{
+ os << "destination: ipv4 " << m_dst << "sequence number " << m_dstSeqNo;
+ if (m_prefixSize != 0)
+ os << "prefix size " << m_prefixSize << "\n";
+ else
+ os << "\n";
+ os << "source ipv4 " << m_origin << "\n" << "life time " << m_lifeTime
+ << "\n" << "acknowledgment required flag " << (*this).GetAckRequired ()
+ << "\n";
+}
+
+void
+RrepHeader::SetLifeTime (Time t)
+{
+ m_lifeTime = t.GetMilliSeconds ();
+}
+
+Time
+RrepHeader::GetLifeTime () const
+{
+ Time t (MilliSeconds (m_lifeTime));
+ return t;
+}
+
+void
+RrepHeader::SetAckRequired (bool f)
+{
+ if (f)
+ m_flags |= (1 << 6);
+ else
+ m_flags &= ~(1 << 6);
+}
+
+bool
+RrepHeader::GetAckRequired () const
+{
+ return (m_flags & (1 << 6));
+}
+
+void
+RrepHeader::SetPrefixSize (uint8_t sz)
+{
+ m_prefixSize = sz;
+}
+
+uint8_t
+RrepHeader::GetPrefixSize () const
+{
+ return m_prefixSize;
+}
+
+bool
+RrepHeader::operator== (RrepHeader const & o) const
+{
+ return (m_flags == o.m_flags && m_prefixSize == o.m_prefixSize &&
+ m_hopCount == o.m_hopCount && m_dst == o.m_dst && m_dstSeqNo == o.m_dstSeqNo &&
+ m_origin == o.m_origin && m_lifeTime == o.m_lifeTime);
+}
+
+void
+RrepHeader::SetHello (Ipv4Address origin, uint32_t srcSeqNo, Time lifetime)
+{
+ m_flags = 0;
+ m_prefixSize = 0;
+ m_hopCount = 0;
+ m_dst = origin;
+ m_dstSeqNo = srcSeqNo;
+ m_origin = origin;
+ m_lifeTime = lifetime.GetMilliSeconds ();
+}
+
+std::ostream &
+operator<< (std::ostream & os, RrepHeader const & h)
+{
+ h.Print (os);
+ return os;
+}
+
+//-----------------------------------------------------------------------------
+// RREP-ACK
+//-----------------------------------------------------------------------------
+
+RrepAckHeader::RrepAckHeader () :
+ m_reserved (0)
+{
+}
+
+TypeId
+RrepAckHeader::GetInstanceTypeId () const
+{
+ return TypeId ();
+}
+
+uint32_t
+RrepAckHeader::GetSerializedSize () const
+{
+ return 1;
+}
+
+void
+RrepAckHeader::Serialize (Buffer::Iterator i ) const
+{
+ i.WriteU8 (m_reserved);
+}
+
+uint32_t
+RrepAckHeader::Deserialize (Buffer::Iterator start )
+{
+ Buffer::Iterator i = start;
+ m_reserved = i.ReadU8 ();
+ uint32_t dist = i.GetDistanceFrom (start);
+ NS_ASSERT (dist == GetSerializedSize ());
+ return dist;
+}
+
+void
+RrepAckHeader::Print (std::ostream &os ) const
+{
+}
+
+bool
+RrepAckHeader::operator== (RrepAckHeader const & o ) const
+{
+ return m_reserved == o.m_reserved;
+}
+
+std::ostream &
+operator<< (std::ostream & os, RrepAckHeader const & h )
+{
+ h.Print (os);
+ return os;
+}
+
+//-----------------------------------------------------------------------------
+// RERR
+//-----------------------------------------------------------------------------
+RerrHeader::RerrHeader () :
+ m_flag (0), m_reserved (0)
+{
+}
+
+TypeId
+RerrHeader::GetInstanceTypeId () const
+{
+ return TypeId ();
+}
+
+uint32_t
+RerrHeader::GetSerializedSize () const
+{
+ return (3 + 8 * GetDestCount ());
+}
+
+void
+RerrHeader::Serialize (Buffer::Iterator i ) const
+{
+ i.WriteU8 (m_flag);
+ i.WriteU8 (m_reserved);
+ i.WriteU8 (GetDestCount ());
+ std::map::const_iterator j;
+ for (j = m_unreachableDstSeqNo.begin (); j != m_unreachableDstSeqNo.end (); ++j)
+ {
+ WriteTo (i, (*j).first);
+ i.WriteHtonU32 ((*j).second);
+ }
+}
+
+uint32_t
+RerrHeader::Deserialize (Buffer::Iterator start )
+{
+ Buffer::Iterator i = start;
+ m_flag = i.ReadU8 ();
+ m_reserved = i.ReadU8 ();
+ uint8_t dest = i.ReadU8 ();
+ m_unreachableDstSeqNo.clear ();
+ Ipv4Address address;
+ uint32_t seqNo;
+ for (uint8_t k = 0; k < dest; ++k)
+ {
+ ReadFrom (i, address);
+ seqNo = i.ReadNtohU32 ();
+ m_unreachableDstSeqNo.insert (std::make_pair (address, seqNo));
+ }
+
+ uint32_t dist = i.GetDistanceFrom (start);
+ NS_ASSERT (dist == GetSerializedSize ());
+ return dist;
+}
+
+void
+RerrHeader::Print (std::ostream &os ) const
+{
+ os << "Unreachable destination (ipv4 address, seq. number):\n";
+ std::map::const_iterator j;
+ for (j = m_unreachableDstSeqNo.begin (); j != m_unreachableDstSeqNo.end (); ++j)
+ {
+ os << (*j).first << ", " << (*j).second << "\n";
+ }
+ os << "No delete flag " << (*this).GetNoDelete () << "\n";
+}
+
+void
+RerrHeader::SetNoDelete (bool f )
+{
+ if (f)
+ m_flag |= (1 << 0);
+ else
+ m_flag &= ~(1 << 0);
+}
+
+bool
+RerrHeader::GetNoDelete () const
+{
+ return (m_flag & (1 << 0));
+}
+
+bool
+RerrHeader::AddUnDestination (Ipv4Address dst, uint32_t seqNo )
+{
+ if (m_unreachableDstSeqNo.find (dst) != m_unreachableDstSeqNo.end ())
+ return true;
+
+ NS_ASSERT (GetDestCount() < 255); // can't support more than 255 destinations in single RERR
+ m_unreachableDstSeqNo.insert (std::make_pair (dst, seqNo));
+ return true;
+}
+
+bool
+RerrHeader::RemoveUnDestination (std::pair & un )
+{
+ if (m_unreachableDstSeqNo.empty ())
+ return false;
+ std::map::iterator i = m_unreachableDstSeqNo.begin ();
+ un = *i;
+ m_unreachableDstSeqNo.erase (i);
+ return true;
+}
+
+void
+RerrHeader::Clear ()
+{
+ m_unreachableDstSeqNo.clear ();
+ m_flag = 0;
+ m_reserved = 0;
+}
+
+bool
+RerrHeader::operator== (RerrHeader const & o ) const
+{
+ if (m_flag != o.m_flag || m_reserved != o.m_reserved || GetDestCount () != o.GetDestCount ())
+ return false;
+
+ std::map::const_iterator j = m_unreachableDstSeqNo.begin ();
+ std::map::const_iterator k = o.m_unreachableDstSeqNo.begin ();
+ for (uint8_t i = 0; i < GetDestCount (); ++i)
+ {
+ if ((j->first != k->first) || (j->second != k->second))
+ return false;
+
+ j++;
+ k++;
+ }
+ return true;
+}
+
+std::ostream &
+operator<< (std::ostream & os, RerrHeader const & h )
+{
+ h.Print (os);
+ return os;
+}
+}
+}
diff --git a/src/routing/manet/aodv/aodv-packet.h b/src/routing/manet/aodv/aodv-packet.h
new file mode 100644
index 000000000..374272b06
--- /dev/null
+++ b/src/routing/manet/aodv/aodv-packet.h
@@ -0,0 +1,330 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2009 IITP RAS
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Based on
+ * NS-2 AODV model developed by the CMU/MONARCH group and optimized and
+ * tuned by Samir Das and Mahesh Marina, University of Cincinnati;
+ *
+ * AODV-UU implementation by Erik Nordström of Uppsala University
+ * http://core.it.uu.se/core/index.php/AODV-UU
+ *
+ * Authors: Elena Buchatskaia
+ * Pavel Boyko
+ */
+#ifndef AODVPACKET_H
+#define AODVPACKET_H
+
+#include
+#include "ns3/header.h"
+#include "ns3/enum.h"
+#include "ns3/ipv4-address.h"
+#include
+#include "ns3/nstime.h"
+
+namespace ns3 {
+namespace aodv {
+
+enum MessageType
+{
+ AODVTYPE_RREQ = 1, //!< AODVTYPE_RREQ
+ AODVTYPE_RREP = 2, //!< AODVTYPE_RREP
+ AODVTYPE_RERR = 3, //!< AODVTYPE_RERR
+ AODVTYPE_RREP_ACK = 4 //!< AODVTYPE_RREP_ACK
+};
+
+/**
+* \ingroup aodv
+* \brief AODV types
+*/
+class TypeHeader : public Header
+{
+public:
+ /// c-tor
+ TypeHeader (MessageType t);
+
+ ///\name Header serialization/deserialization
+ //\{
+ TypeId GetInstanceTypeId () const;
+ uint32_t GetSerializedSize () const;
+ void Serialize (Buffer::Iterator start) const;
+ uint32_t Deserialize (Buffer::Iterator start);
+ void Print (std::ostream &os) const;
+ //\}
+
+ /// Return type
+ MessageType Get () const { return m_type; }
+ /// Check that type if valid
+ bool IsValid () const { return m_valid; }
+ bool operator== (TypeHeader const & o) const;
+private:
+ MessageType m_type;
+ bool m_valid;
+};
+
+std::ostream & operator<< (std::ostream & os, TypeHeader const & h);
+
+/**
+* \ingroup aodv
+* \brief Route Request (RREQ) Message Format
+ \verbatim
+ 0 1 2 3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Type |J|R|G|D|U| Reserved | Hop Count |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | RREQ ID |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Destination IP Address |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Destination Sequence Number |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Originator IP Address |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Originator Sequence Number |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ \endverbatim
+*/
+class RreqHeader : public Header
+{
+public:
+ /// c-tor
+ RreqHeader (uint8_t flags = 0, uint8_t reserved = 0, uint8_t hopCount = 0,
+ uint32_t requestID = 0, Ipv4Address dst = Ipv4Address (),
+ uint32_t dstSeqNo = 0, Ipv4Address origin = Ipv4Address (),
+ uint32_t originSeqNo = 0);
+
+ ///\name Header serialization/deserialization
+ //\{
+ TypeId GetInstanceTypeId () const;
+ uint32_t GetSerializedSize () const;
+ void Serialize (Buffer::Iterator start) const;
+ uint32_t Deserialize (Buffer::Iterator start);
+ void Print (std::ostream &os) const;
+ //\}
+
+ ///\name Fields
+ //\{
+ void SetHopCount (uint8_t count) { m_hopCount = count; }
+ uint8_t GetHopCount () const { return m_hopCount; }
+ void SetId (uint32_t id) { m_requestID = id; }
+ uint8_t GetId () const { return m_requestID; }
+ void SetDst (Ipv4Address a) { m_dst = a; }
+ Ipv4Address GetDst () const { return m_dst; }
+ void SetDstSeqno (uint32_t s) { m_dstSeqNo = s; }
+ uint32_t GetDstSeqno () const { return m_dstSeqNo; }
+ void SetOrigin (Ipv4Address a) { m_origin = a; }
+ Ipv4Address GetOrigin () const { return m_origin; }
+ void SetOriginSeqno (uint32_t s) { m_originSeqNo = s; }
+ uint32_t GetOriginSeqno () const { return m_originSeqNo; }
+ //\}
+
+ ///\name Flags
+ //\{
+ void SetGratiousRrep (bool f);
+ bool GetGratiousRrep () const;
+ void SetDestinationOnly (bool f);
+ bool GetDestinationOnly () const;
+ void SetUnknownSeqno (bool f);
+ bool GetUnknownSeqno () const;
+ //\}
+
+ bool operator== (RreqHeader const & o) const;
+private:
+ uint8_t m_flags; ///< |J|R|G|D|U| bit flags, see RFC
+ uint8_t m_reserved; ///< Not used
+ uint8_t m_hopCount; ///< Hop Count
+ uint32_t m_requestID; ///< RREQ ID
+ Ipv4Address m_dst; ///< Destination IP Address
+ uint32_t m_dstSeqNo; ///< Destination Sequence Number
+ Ipv4Address m_origin; ///< Originator IP Address
+ uint32_t m_originSeqNo; ///< Source Sequence Number
+};
+
+std::ostream & operator<< (std::ostream & os, RreqHeader const &);
+
+/**
+* \ingroup aodv
+* \brief Route Reply (RREP) Message Format
+ \verbatim
+ 0 1 2 3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Type |R|A| Reserved |Prefix Sz| Hop Count |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Destination IP address |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Destination Sequence Number |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Originator IP address |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Lifetime |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ \endverbatim
+*/
+class RrepHeader : public Header
+{
+public:
+ /// c-tor
+ RrepHeader (uint8_t prefixSize = 0, uint8_t hopCount = 0, Ipv4Address dst =
+ Ipv4Address (), uint32_t dstSeqNo = 0, Ipv4Address origin =
+ Ipv4Address (), Time lifetime = MilliSeconds (0));
+ ///\name Header serialization/deserialization
+ //\{
+ TypeId GetInstanceTypeId () const;
+ uint32_t GetSerializedSize () const;
+ void Serialize (Buffer::Iterator start) const;
+ uint32_t Deserialize (Buffer::Iterator start);
+ void Print (std::ostream &os) const;
+ //\}
+
+ ///\name Fields
+ //\{
+ void SetHopCount (uint8_t count) { m_hopCount = count; }
+ uint8_t GetHopCount () const { return m_hopCount; }
+ void SetDst (Ipv4Address a) { m_dst = a; }
+ Ipv4Address GetDst () const { return m_dst; }
+ void SetDstSeqno (uint32_t s) { m_dstSeqNo = s; }
+ uint32_t GetDstSeqno () const { return m_dstSeqNo; }
+ void SetOrigin (Ipv4Address a) { m_origin = a; }
+ Ipv4Address GetOrigin () const { return m_origin; }
+ void SetLifeTime (Time t);
+ Time GetLifeTime () const;
+ //\}
+
+ ///\name Flags
+ //\{
+ void SetAckRequired (bool f);
+ bool GetAckRequired () const;
+ void SetPrefixSize (uint8_t sz);
+ uint8_t GetPrefixSize () const;
+ //\}
+
+ /// Configure RREP to be a Hello message
+ void SetHello (Ipv4Address src, uint32_t srcSeqNo, Time lifetime);
+
+ bool operator== (RrepHeader const & o) const;
+private:
+ uint8_t m_flags; ///< A - acknowledgment required flag
+ uint8_t m_prefixSize; ///< Prefix Size
+ uint8_t m_hopCount; ///< Hop Count
+ Ipv4Address m_dst; ///< Destination IP Address
+ uint32_t m_dstSeqNo; ///< Destination Sequence Number
+ Ipv4Address m_origin; ///< Source IP Address
+ uint32_t m_lifeTime; ///< Lifetime (in milliseconds)
+};
+
+std::ostream & operator<< (std::ostream & os, RrepHeader const &);
+
+/**
+* \ingroup aodv
+* \brief Route Reply Acknowledgment (RREP-ACK) Message Format
+ \verbatim
+ 0 1
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Type | Reserved |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ \endverbatim
+*/
+class RrepAckHeader : public Header
+{
+public:
+ /// c-tor
+ RrepAckHeader ();
+
+ ///\name Header serialization/deserialization
+ //\{
+ TypeId GetInstanceTypeId () const;
+ uint32_t GetSerializedSize () const;
+ void Serialize (Buffer::Iterator start) const;
+ uint32_t Deserialize (Buffer::Iterator start);
+ void Print (std::ostream &os) const;
+ //\}
+
+ bool operator== (RrepAckHeader const & o) const;
+private:
+ uint8_t m_reserved;
+};
+std::ostream & operator<< (std::ostream & os, RrepAckHeader const &);
+
+
+/**
+* \ingroup aodv
+* \brief Route Error (RERR) Message Format
+ \verbatim
+ 0 1 2 3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Type |N| Reserved | DestCount |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Unreachable Destination IP Address (1) |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ | Unreachable Destination Sequence Number (1) |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-|
+ | Additional Unreachable Destination IP Addresses (if needed) |
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ |Additional Unreachable Destination Sequence Numbers (if needed)|
+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ \endverbatim
+*/
+class RerrHeader : public Header
+{
+public:
+ /// c-tor
+ RerrHeader ();
+
+ ///\name Header serialization/deserialization
+ //\{
+ TypeId GetInstanceTypeId () const;
+ uint32_t GetSerializedSize () const;
+ void Serialize (Buffer::Iterator i) const;
+ uint32_t Deserialize (Buffer::Iterator start);
+ void Print (std::ostream &os) const;
+ //\}
+
+ ///\name No delete flag
+ //\{
+ void SetNoDelete (bool f);
+ bool GetNoDelete () const;
+ //\}
+
+ /**
+ * Add unreachable node address and its sequence number in RERR header
+ *\return false if we already added maximum possible number of unreachable destinations
+ */
+ bool AddUnDestination (Ipv4Address dst, uint32_t seqNo);
+ /** Delete pair (address + sequence number) from REER header, if the number of unreachable destinations > 0
+ * \return true on success
+ */
+ bool RemoveUnDestination (std::pair & un);
+ /// Clear header
+ void Clear();
+ /// Return number of unreachable destinations in RERR message
+ uint8_t GetDestCount () const { return (uint8_t)m_unreachableDstSeqNo.size(); }
+ bool operator== (RerrHeader const & o) const;
+private:
+ uint8_t m_flag; ///< No delete flag
+ uint8_t m_reserved; ///< Not used
+
+ /// List of Unreachable destination: IP addresses and sequence numbers
+ std::map m_unreachableDstSeqNo;
+};
+
+std::ostream & operator<< (std::ostream & os, RerrHeader const &);
+}
+}
+#endif /* AODVPACKET_H */
diff --git a/src/routing/manet/aodv/aodv-routing-protocol.cc b/src/routing/manet/aodv/aodv-routing-protocol.cc
new file mode 100644
index 000000000..aeb07b0b5
--- /dev/null
+++ b/src/routing/manet/aodv/aodv-routing-protocol.cc
@@ -0,0 +1,1498 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2009 IITP RAS
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Based on
+ * NS-2 AODV model developed by the CMU/MONARCH group and optimized and
+ * tuned by Samir Das and Mahesh Marina, University of Cincinnati;
+ *
+ * AODV-UU implementation by Erik Nordström of Uppsala University
+ * http://core.it.uu.se/core/index.php/AODV-UU
+ *
+ * Authors: Elena Buchatskaia
+ * Pavel Boyko
+ */
+#include "aodv-routing-protocol.h"
+#include "ns3/log.h"
+#include "ns3/random-variable.h"
+#include "ns3/inet-socket-address.h"
+#include "ns3/trace-source-accessor.h"
+#include "ns3/udp-socket-factory.h"
+#include "ns3/wifi-net-device.h"
+#include "ns3/adhoc-wifi-mac.h"
+#include
+
+NS_LOG_COMPONENT_DEFINE ("AodvRoutingProtocol");
+
+namespace ns3
+{
+namespace aodv
+{
+NS_OBJECT_ENSURE_REGISTERED (RoutingProtocol);
+
+/// UDP Port for AODV control traffic
+const uint32_t RoutingProtocol::AODV_PORT = 654;
+
+RoutingProtocol::RoutingProtocol () :
+ RreqRetries (2),
+ RreqRateLimit (10),
+ ActiveRouteTimeout (Seconds (3)),
+ NetDiameter (35),
+ NodeTraversalTime (MilliSeconds (40)),
+ NetTraversalTime (Scalar (2 * NetDiameter) * NodeTraversalTime),
+ PathDiscoveryTime ( Scalar (2) * NetTraversalTime),
+ MyRouteTimeout (Scalar (2) * std::max (PathDiscoveryTime, ActiveRouteTimeout)),
+ HelloInterval(Seconds (1)),
+ AllowedHelloLoss (2),
+ DeletePeriod (Scalar(5) * std::max(ActiveRouteTimeout, HelloInterval)),
+ NextHopWait (NodeTraversalTime + MilliSeconds (10)),
+ TimeoutBuffer (2),
+ BlackListTimeout(Scalar (RreqRetries) * NetTraversalTime),
+ MaxQueueLen (64),
+ MaxQueueTime (Seconds(30)),
+ DestinationOnly (false),
+ GratuitousReply (true),
+ EnableHello (true),
+ m_routingTable (DeletePeriod),
+ m_queue (MaxQueueLen, MaxQueueTime),
+ m_requestId (0),
+ m_seqNo (0),
+ m_rreqIdCache (PathDiscoveryTime),
+ m_dpd (PathDiscoveryTime),
+ m_nb(HelloInterval),
+ m_rreqCount (0),
+ m_htimer (Timer::CANCEL_ON_DESTROY),
+ m_rreqRateLimitTimer (Timer::CANCEL_ON_DESTROY)
+{
+ if (EnableHello)
+ {
+ m_nb.SetCallback (MakeCallback (&RoutingProtocol::SendRerrWhenBreaksLinkToNextHop, this));
+ }
+}
+
+TypeId
+RoutingProtocol::GetTypeId (void)
+{
+ static TypeId tid = TypeId ("ns3::aodv::RoutingProtocol")
+ .SetParent ()
+ .AddConstructor ()
+ .AddAttribute ("HelloInterval", "HELLO messages emission interval.",
+ TimeValue (Seconds (1)),
+ MakeTimeAccessor (&RoutingProtocol::HelloInterval),
+ MakeTimeChecker ())
+ .AddAttribute ("RreqRetries", "Maximum number of retransmissions of RREQ to discover a route",
+ UintegerValue (2),
+ MakeUintegerAccessor (&RoutingProtocol::RreqRetries),
+ MakeUintegerChecker ())
+ .AddAttribute ("RreqRateLimit", "Maximum number of RREQ per second.",
+ UintegerValue (10),
+ MakeUintegerAccessor (&RoutingProtocol::RreqRateLimit),
+ MakeUintegerChecker ())
+ .AddAttribute ("NodeTraversalTime", "Conservative estimate of the average one hop traversal time for packets and should include "
+ "queuing delays, interrupt processing times and transfer times.",
+ TimeValue (MilliSeconds (40)),
+ MakeTimeAccessor (&RoutingProtocol::NodeTraversalTime),
+ MakeTimeChecker ())
+ .AddAttribute ("NextHopWait", "Period of our waiting for the neighbour's RREP_ACK = 10 ms + NodeTraversalTime",
+ TimeValue (MilliSeconds (50)),
+ MakeTimeAccessor (&RoutingProtocol::NextHopWait),
+ MakeTimeChecker ())
+ .AddAttribute ("ActiveRouteTimeout", "Period of time during which the route is considered to be valid",
+ TimeValue (Seconds (3)),
+ MakeTimeAccessor (&RoutingProtocol::ActiveRouteTimeout),
+ MakeTimeChecker ())
+ .AddAttribute ("MyRouteTimeout", "Value of lifetime field in RREP generating by this node = 2 * max(ActiveRouteTimeout, PathDiscoveryTime)",
+ TimeValue (Seconds (11.2)),
+ MakeTimeAccessor (&RoutingProtocol::MyRouteTimeout),
+ MakeTimeChecker ())
+ .AddAttribute ("BlackListTimeout", "Time for which the node is put into the blacklist = RreqRetries * NetTraversalTime",
+ TimeValue (Seconds (5.6)),
+ MakeTimeAccessor (&RoutingProtocol::BlackListTimeout),
+ MakeTimeChecker ())
+ .AddAttribute ("DeletePeriod", "DeletePeriod is intended to provide an upper bound on the time for which an upstream node A "
+ "can have a neighbor B as an active next hop for destination D, while B has invalidated the route to D."
+ " = 5 * max (HelloInterval, ActiveRouteTimeout)",
+ TimeValue (Seconds (15)),
+ MakeTimeAccessor (&RoutingProtocol::DeletePeriod),
+ MakeTimeChecker ())
+ .AddAttribute ("TimeoutBuffer", "Its purpose is to provide a buffer for the timeout so that if the RREP is delayed"
+ " due to congestion, a timeout is less likely to occur while the RREP is still en route back to the source.",
+ UintegerValue (2),
+ MakeUintegerAccessor (&RoutingProtocol::TimeoutBuffer),
+ MakeUintegerChecker ())
+ .AddAttribute ("NetDiameter", "Net diameter measures the maximum possible number of hops between two nodes in the network",
+ UintegerValue (35),
+ MakeUintegerAccessor (&RoutingProtocol::NetDiameter),
+ MakeUintegerChecker ())
+ .AddAttribute ("NetTraversalTime", "Estimate of the average net traversal time = 2 * NodeTraversalTime * NetDiameter",
+ TimeValue (Seconds (2.8)),
+ MakeTimeAccessor (&RoutingProtocol::NetTraversalTime),
+ MakeTimeChecker ())
+ .AddAttribute ("PathDiscoveryTime", "Estimate of maximum time needed to find route in network = 2 * NetTraversalTime",
+ TimeValue (Seconds (5.6)),
+ MakeTimeAccessor (&RoutingProtocol::PathDiscoveryTime),
+ MakeTimeChecker ())
+ .AddAttribute ("MaxQueueLen", "Maximum number of packets that we allow a routing protocol to buffer.",
+ UintegerValue (64),
+ MakeUintegerAccessor (&RoutingProtocol::MaxQueueLen),
+ MakeUintegerChecker ())
+ .AddAttribute ("MaxQueueTime", "Maximum time packets can be queued (in seconds)",
+ TimeValue (Seconds (30)),
+ MakeTimeAccessor (&RoutingProtocol::MaxQueueTime),
+ MakeTimeChecker ())
+ .AddAttribute ("AllowedHelloLoss", "Number of hello messages which may be loss for valid link.",
+ UintegerValue (2),
+ MakeUintegerAccessor (&RoutingProtocol::AllowedHelloLoss),
+ MakeUintegerChecker ())
+ .AddAttribute ("GratuitousReply", "Indicates whether a gratuitous RREP should be unicast to the node originated route discovery.",
+ BooleanValue (true),
+ MakeBooleanAccessor (&RoutingProtocol::SetGratuitousReplyFlag,
+ &RoutingProtocol::GetGratuitousReplyFlag),
+ MakeBooleanChecker ())
+ .AddAttribute ("DestinationOnly", "Indicates only the destination may respond to this RREQ.",
+ BooleanValue (false),
+ MakeBooleanAccessor (&RoutingProtocol::SetDesinationOnlyFlag,
+ &RoutingProtocol::GetDesinationOnlyFlag),
+ MakeBooleanChecker ())
+ .AddAttribute ("EnableHello", "Indicates whether a hello messages enable.",
+ BooleanValue (true),
+ MakeBooleanAccessor (&RoutingProtocol::SetHelloEnable,
+ &RoutingProtocol::GetHelloEnable),
+ MakeBooleanChecker ())
+ .AddAttribute ("EnableBroadcast", "Indicates whether a broadcast data packets forwarding enable.",
+ BooleanValue (true),
+ MakeBooleanAccessor (&RoutingProtocol::SetBroadcastEnable,
+ &RoutingProtocol::GetBroadcastEnable),
+ MakeBooleanChecker ())
+ ;
+ return tid;
+}
+
+RoutingProtocol::~RoutingProtocol ()
+{
+}
+
+void
+RoutingProtocol::DoDispose ()
+{
+ m_ipv4 = 0;
+ for (std::map , Ipv4InterfaceAddress>::iterator iter =
+ m_socketAddresses.begin (); iter != m_socketAddresses.end (); iter++)
+ {
+ iter->first->Close ();
+ }
+ m_socketAddresses.clear ();
+ Ipv4RoutingProtocol::DoDispose ();
+}
+
+void
+RoutingProtocol::Start ()
+{
+ m_scb = MakeCallback (&RoutingProtocol::Send, this);
+ m_ecb = MakeCallback (&RoutingProtocol::Drop, this);
+
+ if (EnableHello)
+ {
+ m_nb.ScheduleTimer ();
+ }
+ m_rreqRateLimitTimer.SetFunction (&RoutingProtocol::RreqRateLimitTimerExpire,
+ this);
+ m_rreqRateLimitTimer.Schedule (Seconds (1));
+}
+
+Ptr
+RoutingProtocol::RouteOutput (Ptr p, const Ipv4Header &header,
+ uint32_t oif, Socket::SocketErrno &sockerr)
+{
+ NS_LOG_FUNCTION (this << header.GetDestination ());
+ if (m_socketAddresses.empty ())
+ {
+ sockerr = Socket::ERROR_NOROUTETOHOST;
+ NS_LOG_LOGIC ("No aodv interfaces");
+ Ptr route;
+ return route;
+ }
+ sockerr = Socket::ERROR_NOTERROR;
+ Ptr route;
+ Ipv4Address dst = header.GetDestination ();
+ RoutingTableEntry rt;
+ if (m_routingTable.LookupRoute (dst, rt))
+ {
+ if (rt.GetFlag () == VALID)
+ {
+ route = rt.GetRoute ();
+ NS_ASSERT (route != 0);
+ NS_LOG_LOGIC("exist route to " << route->GetDestination() << " from interface " << route->GetSource());
+ UpdateRouteLifeTime (dst, ActiveRouteTimeout);
+ UpdateRouteLifeTime (route->GetGateway (), ActiveRouteTimeout);
+ }
+ else
+ {
+ bool result = true;
+ // May be null pointer (e.g. tcp-socket give null pointer)
+ if (p != Ptr ())
+ {
+ QueueEntry newEntry (p, header, m_scb, m_ecb);
+ result = m_queue.Enqueue (newEntry);
+ if (result)
+ NS_LOG_LOGIC ("Add packet " << p->GetUid() << " to queue");
+
+ }
+ if ((rt.GetFlag () == INVALID) && result)
+ {
+ SendRequest (dst);
+ }
+ }
+ }
+ else
+ {
+ bool result = true;
+ if (p != Ptr ())
+ {
+ QueueEntry newEntry (p, header, m_scb, m_ecb);
+ // Some protocols may ask route several times for a single packet.
+ result = m_queue.Enqueue (newEntry);
+ if (result)
+ NS_LOG_LOGIC ("Add packet " << p->GetUid() << " to queue. Protocol " << (uint16_t) header.GetProtocol ());
+ }
+ if (result)
+ SendRequest (dst);
+ }
+ return route;
+}
+
+bool
+RoutingProtocol::RouteInput (Ptr p, const Ipv4Header &header,
+ Ptr idev, UnicastForwardCallback ucb,
+ MulticastForwardCallback mcb, LocalDeliverCallback lcb, ErrorCallback ecb)
+{
+ NS_LOG_FUNCTION (this << p->GetUid() << header.GetDestination() << idev->GetAddress());
+ if (m_socketAddresses.empty ())
+ {
+ NS_LOG_LOGIC ("No aodv interfaces");
+ return false;
+ }
+ NS_ASSERT (m_ipv4 != 0);
+ // Check if input device supports IP
+ NS_ASSERT (m_ipv4->GetInterfaceForDevice (idev) >= 0);
+ int32_t iif = m_ipv4->GetInterfaceForDevice (idev);
+
+ Ipv4Address dst = header.GetDestination ();
+ Ipv4Address origin = header.GetSource ();
+
+ if (IsMyOwnAddress (origin))
+ return true;
+
+ // Local delivery to AODV interfaces
+ for (std::map , Ipv4InterfaceAddress>::const_iterator j =
+ m_socketAddresses.begin (); j != m_socketAddresses.end (); ++j)
+ {
+ Ipv4InterfaceAddress iface = j->second;
+ if (m_ipv4->GetInterfaceForAddress (iface.GetLocal ()) == iif)
+ if (dst == iface.GetBroadcast ())
+ {
+ if (!EnableBroadcast)
+ {
+ return true;
+ }
+ if (m_dpd.IsDuplicate (p, header))
+ {
+ NS_LOG_DEBUG ("Duplicated packet " << p->GetUid () << " from " << origin << ". Drop.");
+ return true;
+ }
+ UpdateRouteLifeTime (origin, ActiveRouteTimeout);
+ NS_LOG_LOGIC ("Broadcast local delivery to " << iface.GetLocal ());
+ Ptr packet = p->Copy ();
+ lcb (p, header, iif);
+ if (header.GetTtl () > 1)
+ {
+ NS_LOG_LOGIC ("Forward broadcast. TTL " << (uint16_t) header.GetTtl ());
+ RoutingTableEntry toBroadcast;
+ if (m_routingTable.LookupRoute (dst, toBroadcast))
+ {
+ Ptr route = toBroadcast.GetRoute ();
+ ucb (route, packet, header);
+ }
+ else
+ {
+ NS_LOG_DEBUG ("No route to forward broadcast. Drop packet " << p->GetUid ());
+ }
+ }
+ else
+ {
+ NS_LOG_DEBUG ("TTL exceeded. Drop packet " << p->GetUid ());
+ }
+ return true;
+ }
+ }
+ for (std::map , Ipv4InterfaceAddress>::const_iterator j =
+ m_socketAddresses.begin (); j != m_socketAddresses.end (); ++j)
+ {
+ Ipv4InterfaceAddress iface = j->second;
+ if (dst == iface.GetLocal ())
+ {
+ UpdateRouteLifeTime (origin, ActiveRouteTimeout);
+ RoutingTableEntry toOrigin;
+ if (m_routingTable.LookupRoute (origin, toOrigin))
+ {
+ UpdateRouteLifeTime (toOrigin.GetNextHop (), ActiveRouteTimeout);
+ m_nb.Update (toOrigin.GetNextHop (), ActiveRouteTimeout);
+ }
+ NS_LOG_LOGIC ("Unicast local delivery to " << iface.GetLocal ());
+ lcb (p, header, iif);
+ return true;
+ }
+ }
+
+ // Forwarding
+ return Forwarding (p, header, ucb, ecb);
+}
+
+bool
+RoutingProtocol::Forwarding (Ptr p, const Ipv4Header & header,
+ UnicastForwardCallback ucb, ErrorCallback ecb)
+{
+ Ipv4Address dst = header.GetDestination ();
+ Ipv4Address origin = header.GetSource ();
+ m_routingTable.Purge ();
+ RoutingTableEntry toDst;
+ if (m_routingTable.LookupRoute (dst, toDst))
+ {
+ if (toDst.GetFlag () == VALID)
+ {
+ Ptr route = toDst.GetRoute ();
+ NS_LOG_LOGIC (route->GetSource()<<" forwarding to " << dst << " from " << origin << " packet " << p->GetUid ());
+
+ /*
+ * Each time a route is used to forward a data packet, its Active Route
+ * Lifetime field of the source, destination and the next hop on the
+ * path to the destination is updated to be no less than the current
+ * time plus ActiveRouteTimeout.
+ */
+ UpdateRouteLifeTime (origin, ActiveRouteTimeout);
+ UpdateRouteLifeTime (dst, ActiveRouteTimeout);
+ UpdateRouteLifeTime (route->GetGateway (), ActiveRouteTimeout);
+ /*
+ * Since the route between each originator and destination pair is expected to be symmetric, the
+ * Active Route Lifetime for the previous hop, along the reverse path back to the IP source, is also updated
+ * to be no less than the current time plus ActiveRouteTimeout
+ */
+ RoutingTableEntry toOrigin;
+ m_routingTable.LookupRoute (origin, toOrigin);
+ UpdateRouteLifeTime (toOrigin.GetNextHop (), ActiveRouteTimeout);
+
+ m_nb.Update (route->GetGateway (), ActiveRouteTimeout);
+ m_nb.Update (toOrigin.GetNextHop (), ActiveRouteTimeout);
+
+ ucb (route, p, header);
+ return true;
+ }
+ else
+ {
+ if (toDst.GetValidSeqNo ())
+ {
+ SendRerrWhenNoRouteToForward (dst, toDst.GetSeqNo (), origin);
+ NS_LOG_DEBUG ("Drop packet " << p->GetUid () << " because no route to forward it.");
+ return false;
+ }
+ }
+ }
+ NS_LOG_LOGIC ("route not found to "<< dst << ". Send RERR message.");
+ NS_LOG_DEBUG ("Drop packet " << p->GetUid () << " because no route to forward it.");
+ SendRerrWhenNoRouteToForward (dst, 0, origin);
+ return false;
+}
+
+void
+RoutingProtocol::SetIpv4 (Ptr ipv4)
+{
+ NS_ASSERT (ipv4 != 0);
+ NS_ASSERT (m_ipv4 == 0);
+
+ if (EnableHello)
+ {
+ m_htimer.SetFunction (&RoutingProtocol::HelloTimerExpire, this);
+ m_htimer.Schedule (MilliSeconds (UniformVariable ().GetInteger (0, 100)));
+ }
+
+ m_ipv4 = ipv4;
+ Simulator::ScheduleNow (&RoutingProtocol::Start, this);
+}
+
+void
+RoutingProtocol::NotifyInterfaceUp (uint32_t i)
+{
+ NS_LOG_FUNCTION (this << m_ipv4->GetAddress (i, 0).GetLocal ());
+ Ptr l3 = m_ipv4->GetObject ();
+ if (l3->GetNAddresses (i) > 1)
+ {
+ NS_LOG_WARN ("AODV does not work with more then one address per each interface.");
+ }
+ Ipv4InterfaceAddress iface = l3->GetAddress (i, 0);
+ if (iface.GetLocal () == Ipv4Address ("127.0.0.1"))
+ return;
+
+ // Create a socket to listen only on this interface
+ Ptr socket = Socket::CreateSocket (GetObject (),
+ UdpSocketFactory::GetTypeId ());
+ NS_ASSERT (socket != 0);
+ socket->SetRecvCallback (MakeCallback (&RoutingProtocol::RecvAodv, this));
+ socket->Bind (InetSocketAddress (iface.GetLocal (), AODV_PORT));
+ socket->Connect (InetSocketAddress (iface.GetBroadcast (), AODV_PORT));
+ socket->SetAttribute ("IpTtl", UintegerValue (1));
+ m_socketAddresses.insert (std::make_pair (socket, iface));
+
+ // Add local broadcast record to the routing table
+ Ptr dev = m_ipv4->GetNetDevice (m_ipv4->GetInterfaceForAddress (iface.GetLocal ()));
+ RoutingTableEntry rt (/*device=*/dev, /*dst=*/iface.GetBroadcast (), /*know seqno=*/true, /*seqno=*/0, /*iface=*/iface,
+ /*hops=*/1, /*next hop=*/iface.GetBroadcast (), /*lifetime=*/Simulator::GetMaximumSimulationTime ());
+ m_routingTable.AddRoute (rt);
+
+ // Allow neighbor manager use this interface for layer 2 feedback if possible
+ Ptr wifi = dev->GetObject ();
+ if (wifi == 0)
+ return;
+ Ptr mac = wifi->GetMac ();
+ if (mac == 0)
+ return;
+
+ mac->TraceConnectWithoutContext ("TxErrHeader", m_nb.GetTxErrorCallback ());
+ m_nb.AddArpCache (l3->GetInterface (i)->GetArpCache ());
+}
+
+void
+RoutingProtocol::NotifyInterfaceDown (uint32_t i)
+{
+ NS_LOG_FUNCTION (this << m_ipv4->GetAddress (i, 0).GetLocal ());
+
+ // Disable layer 2 link state monitoring (if possible)
+ Ptr l3 = m_ipv4->GetObject ();
+ Ptr dev = l3->GetNetDevice (i);
+ Ptr wifi = dev->GetObject ();
+ if (wifi != 0)
+ {
+ Ptr mac = wifi->GetMac ()->GetObject ();
+ if (mac != 0)
+ {
+ mac->TraceDisconnectWithoutContext ("TxErrHeader",
+ m_nb.GetTxErrorCallback ());
+ m_nb.DelArpCache (l3->GetInterface (i)->GetArpCache ());
+ }
+ }
+
+ // Close socket
+ Ptr socket = FindSocketWithInterfaceAddress (m_ipv4->GetAddress (i, 0));
+ NS_ASSERT (socket);
+ socket->Close ();
+ m_socketAddresses.erase (socket);
+ if (m_socketAddresses.empty ())
+ {
+ NS_LOG_LOGIC ("No aodv interfaces");
+ m_htimer.Cancel ();
+ m_nb.Clear ();
+ m_routingTable.Clear ();
+ return;
+ }
+ m_routingTable.DeleteAllRoutesFromInterface (m_ipv4->GetAddress (i, 0));
+}
+
+void
+RoutingProtocol::NotifyAddAddress (uint32_t i, Ipv4InterfaceAddress address)
+{
+ NS_LOG_FUNCTION (this << " interface " << i << " address " << address);
+ Ptr l3 = m_ipv4->GetObject ();
+ if (!l3->IsUp (i))
+ return;
+ if (l3->GetNAddresses (i) == 1)
+ {
+ Ipv4InterfaceAddress iface = l3->GetAddress (i, 0);
+ Ptr socket = FindSocketWithInterfaceAddress (iface);
+ if (!socket)
+ {
+ if (iface.GetLocal () == Ipv4Address ("127.0.0.1"))
+ return;
+ // Create a socket to listen only on this interface
+ Ptr socket = Socket::CreateSocket (GetObject (),
+ UdpSocketFactory::GetTypeId ());
+ NS_ASSERT (socket != 0);
+ socket->SetRecvCallback (MakeCallback (&RoutingProtocol::RecvAodv,this));
+ socket->Bind (InetSocketAddress (iface.GetLocal (), AODV_PORT));
+ socket->Connect (InetSocketAddress (iface.GetBroadcast (), AODV_PORT));
+ m_socketAddresses.insert (std::make_pair (socket, iface));
+
+ // Add local broadcast record to the routing table
+ Ptr dev = m_ipv4->GetNetDevice (
+ m_ipv4->GetInterfaceForAddress (iface.GetLocal ()));
+ RoutingTableEntry rt (/*device=*/dev, /*dst=*/iface.GetBroadcast (), /*know seqno=*/true,
+ /*seqno=*/0, /*iface=*/iface, /*hops=*/1,
+ /*next hop=*/iface.GetBroadcast (), /*lifetime=*/Simulator::GetMaximumSimulationTime ());
+ m_routingTable.AddRoute (rt);
+ }
+ }
+ else
+ {
+ NS_LOG_LOGIC ("AODV does not work with more then one address per each interface. Ignore added address");
+ }
+}
+
+void
+RoutingProtocol::NotifyRemoveAddress (uint32_t i, Ipv4InterfaceAddress address)
+{
+ NS_LOG_FUNCTION (this);
+ Ptr socket = FindSocketWithInterfaceAddress (address);
+ if (socket)
+ {
+ m_routingTable.DeleteAllRoutesFromInterface (address);
+ m_socketAddresses.erase (socket);
+ Ptr l3 = m_ipv4->GetObject ();
+ if (l3->GetNAddresses (i))
+ {
+ Ipv4InterfaceAddress iface = l3->GetAddress (i, 0);
+ // Create a socket to listen only on this interface
+ Ptr socket = Socket::CreateSocket (GetObject (),
+ UdpSocketFactory::GetTypeId ());
+ NS_ASSERT (socket != 0);
+ socket->SetRecvCallback (MakeCallback (&RoutingProtocol::RecvAodv, this));
+ socket->Bind (InetSocketAddress (iface.GetLocal (), AODV_PORT));
+ socket->Connect (InetSocketAddress (iface.GetBroadcast (), AODV_PORT));
+ m_socketAddresses.insert (std::make_pair (socket, iface));
+
+ // Add local broadcast record to the routing table
+ Ptr dev = m_ipv4->GetNetDevice (m_ipv4->GetInterfaceForAddress (iface.GetLocal ()));
+ RoutingTableEntry rt (/*device=*/dev, /*dst=*/iface.GetBroadcast (), /*know seqno=*/true, /*seqno=*/0, /*iface=*/iface,
+ /*hops=*/1, /*next hop=*/iface.GetBroadcast (), /*lifetime=*/Simulator::GetMaximumSimulationTime ());
+ m_routingTable.AddRoute (rt);
+ }
+ if (m_socketAddresses.empty ())
+ {
+ NS_LOG_LOGIC ("No aodv interfaces");
+ m_htimer.Cancel ();
+ m_nb.Clear ();
+ m_routingTable.Clear ();
+ return;
+ }
+ }
+ else
+ {
+ NS_LOG_LOGIC ("Remove address not participating in AODV operation");
+ }
+}
+
+bool
+RoutingProtocol::IsMyOwnAddress (Ipv4Address src)
+{
+ for (std::map , Ipv4InterfaceAddress>::const_iterator j =
+ m_socketAddresses.begin (); j != m_socketAddresses.end (); ++j)
+ {
+ Ipv4InterfaceAddress iface = j->second;
+ if (src == iface.GetLocal ())
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+void
+RoutingProtocol::SendRequest (Ipv4Address dst)
+{
+ NS_LOG_FUNCTION ( this << dst);
+ // A node SHOULD NOT originate more than RREQ_RATELIMIT RREQ messages per second.
+ if (m_rreqCount == RreqRateLimit)
+ {
+ Simulator::Schedule (m_rreqRateLimitTimer.GetDelayLeft () + MicroSeconds (100),
+ &RoutingProtocol::SendRequest, this, dst);
+ return;
+ }
+ else
+ m_rreqCount++;
+ // Create RREQ header
+ RreqHeader rreqHeader;
+ rreqHeader.SetDst (dst);
+
+ RoutingTableEntry rt;
+ if (m_routingTable.LookupRoute (dst, rt))
+ {
+ rreqHeader.SetHopCount (rt.GetHop ());
+ if (rt.GetValidSeqNo ())
+ rreqHeader.SetDstSeqno (rt.GetSeqNo ());
+ else
+ rreqHeader.SetUnknownSeqno (true);
+ rt.SetFlag (IN_SEARCH);
+ m_routingTable.AddRoute (rt);
+ }
+ else
+ {
+ rreqHeader.SetUnknownSeqno (true);
+ RoutingTableEntry newEntry;
+ newEntry.SetFlag (IN_SEARCH);
+ m_routingTable.AddRoute (newEntry);
+ }
+
+ if (GratuitousReply)
+ rreqHeader.SetGratiousRrep (true);
+ if (DestinationOnly)
+ rreqHeader.SetDestinationOnly (true);
+
+ m_seqNo++;
+ rreqHeader.SetOriginSeqno (m_seqNo);
+ m_requestId++;
+ rreqHeader.SetId (m_requestId);
+ rreqHeader.SetHopCount (0);
+
+ // Send RREQ as subnet directed broadcast from each interface used by aodv
+ for (std::map , Ipv4InterfaceAddress>::const_iterator j =
+ m_socketAddresses.begin (); j != m_socketAddresses.end (); ++j)
+ {
+ Ptr socket = j->first;
+ Ipv4InterfaceAddress iface = j->second;
+
+ rreqHeader.SetOrigin (iface.GetLocal ());
+ m_rreqIdCache.IsDuplicate (iface.GetLocal (), m_requestId);
+
+ Ptr packet = Create ();
+ packet->AddHeader (rreqHeader);
+ TypeHeader tHeader (AODVTYPE_RREQ);
+ packet->AddHeader (tHeader);
+ socket->Send (packet);
+ }
+ ScheduleRreqRetry (dst);
+ if (EnableHello)
+ {
+ m_htimer.Cancel ();
+ m_htimer.Schedule (HelloInterval - Scalar (0.01) * MilliSeconds (UniformVariable ().GetInteger (0, 10)));
+ }
+}
+
+void
+RoutingProtocol::ScheduleRreqRetry (Ipv4Address dst)
+{
+ if (m_addressReqTimer.find (dst) == m_addressReqTimer.end ())
+ {
+ Timer timer (Timer::CANCEL_ON_DESTROY);
+ m_addressReqTimer[dst] = timer;
+ }
+ m_addressReqTimer[dst].SetFunction (&RoutingProtocol::RouteRequestTimerExpire, this);
+ m_addressReqTimer[dst].Remove ();
+ m_addressReqTimer[dst].SetArguments (dst);
+ RoutingTableEntry rt;
+ m_routingTable.LookupRoute (dst, rt);
+ rt.IncrementRreqCnt ();
+ m_routingTable.Update (rt);
+ m_addressReqTimer[dst].Schedule (Scalar (rt.GetRreqCnt ()) * NetTraversalTime);
+}
+
+void
+RoutingProtocol::RecvAodv (Ptr socket)
+{
+ NS_LOG_FUNCTION (this);
+ Address sourceAddress;
+ Ptr packet = socket->RecvFrom (sourceAddress);
+ InetSocketAddress inetSourceAddr = InetSocketAddress::ConvertFrom (sourceAddress);
+ Ipv4Address sender = inetSourceAddr.GetIpv4 ();
+ Ipv4Address receiver = m_socketAddresses[socket].GetLocal ();
+ NS_LOG_DEBUG ("AODV node " << this << " received a AODV packet from " << sender << " to " << receiver);
+
+ UpdateRouteToNeighbor (sender, receiver);
+ TypeHeader tHeader (AODVTYPE_RREQ);
+ packet->RemoveHeader (tHeader);
+ if (!tHeader.IsValid ())
+ {
+ NS_LOG_DEBUG ("AODV message " << packet->GetUid() << " with unknown type received: " << tHeader.Get() << ". Drop");
+ return; // drop
+ }
+ switch (tHeader.Get ())
+ {
+ case AODVTYPE_RREQ:
+ {
+ RecvRequest (packet, receiver, sender);
+ break;
+ }
+ case AODVTYPE_RREP:
+ {
+ RecvReply (packet, receiver, sender);
+ break;
+ }
+ case AODVTYPE_RERR:
+ {
+ RecvError (packet, sender);
+ break;
+ }
+ case AODVTYPE_RREP_ACK:
+ {
+ RecvReplyAck (sender);
+ break;
+ }
+ }
+}
+
+bool
+RoutingProtocol::UpdateRouteLifeTime (Ipv4Address addr, Time lifetime)
+{
+ RoutingTableEntry rt;
+ if (m_routingTable.LookupRoute (addr, rt))
+ {
+ rt.SetFlag (VALID);
+ rt.SetRreqCnt (0);
+ rt.SetLifeTime (std::max (lifetime, rt.GetLifeTime ()));
+ m_routingTable.Update (rt);
+ return true;
+ }
+ return false;
+}
+
+void
+RoutingProtocol::UpdateRouteToNeighbor (Ipv4Address sender, Ipv4Address receiver)
+{
+ NS_LOG_FUNCTION (this << "sender " << sender << " receiver " << receiver);
+ RoutingTableEntry toNeighbor;
+ if (!m_routingTable.LookupRoute (sender, toNeighbor))
+ {
+ Ptr dev = m_ipv4->GetNetDevice (m_ipv4->GetInterfaceForAddress (receiver));
+ RoutingTableEntry newEntry (/*device=*/dev, /*dst=*/sender, /*know seqno=*/false, /*seqno=*/0,
+ /*iface=*/m_ipv4->GetAddress (m_ipv4->GetInterfaceForAddress (receiver), 0),
+ /*hops=*/1, /*next hop=*/sender, /*lifetime=*/ActiveRouteTimeout);
+ m_routingTable.AddRoute (newEntry);
+ }
+ else
+ {
+ Ptr dev = m_ipv4->GetNetDevice (m_ipv4->GetInterfaceForAddress (receiver));
+ RoutingTableEntry newEntry (/*device=*/dev, /*dst=*/sender, /*know seqno=*/false, /*seqno=*/0,
+ /*iface=*/m_ipv4->GetAddress (m_ipv4->GetInterfaceForAddress (receiver), 0),
+ /*hops=*/1, /*next hop=*/sender, /*lifetime=*/std::max (ActiveRouteTimeout, toNeighbor.GetLifeTime ()));
+ m_routingTable.Update (newEntry);
+ }
+}
+
+void
+RoutingProtocol::RecvRequest (Ptr p, Ipv4Address receiver, Ipv4Address src)
+{
+ NS_LOG_FUNCTION (this);
+ RreqHeader rreqHeader;
+ p->RemoveHeader (rreqHeader);
+
+ // A node ignores all RREQs received from any node in its blacklist
+ RoutingTableEntry toPrev;
+ if (m_routingTable.LookupRoute (src, toPrev))
+ {
+ if (toPrev.IsUnidirectional ())
+ return;
+ }
+
+ uint32_t id = rreqHeader.GetId ();
+ Ipv4Address origin = rreqHeader.GetOrigin ();
+
+ /*
+ * Node checks to determine whether it has received a RREQ with the same Originator IP Address and RREQ ID.
+ * If such a RREQ has been received, the node silently discards the newly received RREQ.
+ */
+ if (m_rreqIdCache.IsDuplicate (origin, id))
+ {
+ return;
+ }
+
+ // Increment RREQ hop count
+ uint8_t hop = rreqHeader.GetHopCount () + 1;
+ rreqHeader.SetHopCount (hop);
+
+ /*
+ * When the reverse route is created or updated, the following actions on the route are also carried out:
+ * 1. the Originator Sequence Number from the RREQ is compared to the corresponding destination sequence number
+ * in the route table entry and copied if greater than the existing value there
+ * 2. the valid sequence number field is set to true;
+ * 3. the next hop in the routing table becomes the node from which the RREQ was received
+ * 4. the hop count is copied from the Hop Count in the RREQ message;
+ * 5. the Lifetime is set to be the maximum of (ExistingLifetime, MinimalLifetime), where
+ * MinimalLifetime = current time + 2*NetTraversalTime - 2*HopCount*NodeTraversalTime
+ */
+ RoutingTableEntry toOrigin;
+ if (!m_routingTable.LookupRoute (origin, toOrigin))
+ {
+ Ptr dev = m_ipv4->GetNetDevice (m_ipv4->GetInterfaceForAddress (receiver));
+ RoutingTableEntry newEntry (/*device=*/dev, /*dst=*/origin, /*validSeno=*/true, /*seqNo=*/rreqHeader.GetOriginSeqno (),
+ /*iface=*/m_ipv4->GetAddress (m_ipv4->GetInterfaceForAddress (receiver), 0), /*hops=*/hop,
+ /*nextHop*/src, /*timeLife=*/Scalar (2) * NetTraversalTime - Scalar (2 * hop) * NodeTraversalTime);
+ m_routingTable.AddRoute (newEntry);
+ }
+ else
+ {
+ if (toOrigin.GetValidSeqNo ())
+ {
+ if (int32_t (rreqHeader.GetOriginSeqno ()) - int32_t (toOrigin.GetSeqNo ()) > 0)
+ toOrigin.SetSeqNo (rreqHeader.GetOriginSeqno ());
+ }
+ else
+ toOrigin.SetSeqNo (rreqHeader.GetOriginSeqno ());
+ toOrigin.SetValidSeqNo (true);
+ toOrigin.SetNextHop (src);
+ toOrigin.SetOutputDevice (m_ipv4->GetNetDevice (m_ipv4->GetInterfaceForAddress (receiver)));
+ toOrigin.SetInterface (m_ipv4->GetAddress (m_ipv4->GetInterfaceForAddress (receiver), 0));
+ toOrigin.SetHop (hop);
+ toOrigin.SetLifeTime (std::max (Scalar (2) * NetTraversalTime - Scalar (2 * hop) * NodeTraversalTime, toOrigin.GetLifeTime ()));
+ m_routingTable.Update (toOrigin);
+ }
+ NS_LOG_LOGIC (receiver << " receive RREQ to destination " << rreqHeader.GetDst ());
+
+ // A node generates a RREP if either:
+ // (i) it is itself the destination,
+ if (IsMyOwnAddress (rreqHeader.GetDst ()))
+ {
+ m_routingTable.LookupRoute (origin, toOrigin);
+ SendReply (rreqHeader, toOrigin);
+ return;
+ }
+ /*
+ * (ii) or it has an active route to the destination, the destination sequence number in the node's existing route table entry for the destination
+ * is valid and greater than or equal to the Destination Sequence Number of the RREQ, and the "destination only" flag is NOT set.
+ */
+ RoutingTableEntry toDst;
+ Ipv4Address dst = rreqHeader.GetDst ();
+ if (m_routingTable.LookupRoute (dst, toDst))
+ {
+ /*
+ * The Destination Sequence number for the requested destination is set to the maximum of the corresponding value
+ * received in the RREQ message, and the destination sequence value currently maintained by the node for the requested destination.
+ * However, the forwarding node MUST NOT modify its maintained value for the destination sequence number, even if the value
+ * received in the incoming RREQ is larger than the value currently maintained by the forwarding node.
+ */
+ if (rreqHeader.GetUnknownSeqno () || ( (int32_t (toDst.GetSeqNo ()) - int32_t (rreqHeader.GetDstSeqno ()) > 0)
+ && toDst.GetValidSeqNo () ))
+ {
+ if (!rreqHeader.GetDestinationOnly () && toDst.GetFlag() == VALID)
+ {
+ m_routingTable.LookupRoute (origin, toOrigin);
+ SendReplyByIntermediateNode (toDst, toOrigin, rreqHeader.GetGratiousRrep ());
+ return;
+ }
+ rreqHeader.SetDstSeqno (toDst.GetSeqNo ());
+ rreqHeader.SetUnknownSeqno (false);
+ }
+ }
+
+ for (std::map , Ipv4InterfaceAddress>::const_iterator j =
+ m_socketAddresses.begin (); j != m_socketAddresses.end (); ++j)
+ {
+ Ptr socket = j->first;
+ Ipv4InterfaceAddress iface = j->second;
+ Ptr packet = Create ();
+ packet->AddHeader (rreqHeader);
+ TypeHeader tHeader (AODVTYPE_RREQ);
+ packet->AddHeader (tHeader);
+ socket->Send (packet);
+ }
+
+ if (EnableHello)
+ {
+ m_htimer.Cancel ();
+ m_htimer.Schedule (HelloInterval - Scalar(0.1)*MilliSeconds(UniformVariable().GetInteger (0, 10)));
+ }
+}
+
+void
+RoutingProtocol::SendReply (RreqHeader const & rreqHeader, RoutingTableEntry const & toOrigin)
+{
+ NS_LOG_FUNCTION (this << toOrigin.GetDestination ());
+ /*
+ * Destination node MUST increment its own sequence number by one if the sequence number in the RREQ packet is equal to that
+ * incremented value. Otherwise, the destination does not change its sequence number before generating the RREP message.
+ */
+ if (!rreqHeader.GetUnknownSeqno () && (rreqHeader.GetDstSeqno () == m_seqNo + 1))
+ m_seqNo++;
+ RrepHeader rrepHeader ( /*prefixSize=*/0, /*hops=*/0, /*dst=*/rreqHeader.GetDst (),
+ /*dstSeqNo=*/m_seqNo, /*origin=*/toOrigin.GetDestination (), /*lifeTime=*/MyRouteTimeout);
+ Ptr packet = Create ();
+ packet->AddHeader (rrepHeader);
+ TypeHeader tHeader (AODVTYPE_RREP);
+ packet->AddHeader (tHeader);
+ Ptr socket = FindSocketWithInterfaceAddress (toOrigin.GetInterface ());
+ NS_ASSERT (socket);
+ socket->SendTo (packet, 0, InetSocketAddress (toOrigin.GetNextHop (), AODV_PORT));
+}
+
+void
+RoutingProtocol::SendReplyByIntermediateNode (RoutingTableEntry & toDst, RoutingTableEntry & toOrigin, bool gratRep)
+{
+ NS_LOG_FUNCTION(this);
+ RrepHeader rrepHeader (/*prefix size=*/0, /*hops=*/toDst.GetHop (), /*dst=*/toDst.GetDestination (), /*dst seqno=*/toDst.GetSeqNo (),
+ /*origin=*/toOrigin.GetDestination (), /*lifetime=*/toDst.GetLifeTime ());
+ /* If the node we received a RREQ for is a neighbor we are
+ * probably facing a unidirectional link... Better request a RREP-ack
+ */
+ if (toDst.GetHop () == 1)
+ {
+ rrepHeader.SetAckRequired (true);
+ RoutingTableEntry toNextHop;
+ m_routingTable.LookupRoute (toOrigin.GetNextHop (), toNextHop);
+ toNextHop.m_ackTimer.SetFunction (&RoutingProtocol::AckTimerExpire, this);
+ toNextHop.m_ackTimer.SetArguments (toNextHop.GetDestination (), BlackListTimeout);
+ toNextHop.m_ackTimer.SetDelay (NextHopWait);
+ }
+ toDst.InsertPrecursor (toOrigin.GetNextHop ());
+ toOrigin.InsertPrecursor (toDst.GetNextHop ());
+ m_routingTable.Update (toDst);
+ m_routingTable.Update (toOrigin);
+
+ Ptr packet = Create ();
+ packet->AddHeader (rrepHeader);
+ TypeHeader tHeader (AODVTYPE_RREP);
+ packet->AddHeader (tHeader);
+ Ptr socket = FindSocketWithInterfaceAddress (toOrigin.GetInterface ());
+ NS_ASSERT (socket);
+ socket->SendTo (packet, 0, InetSocketAddress (toOrigin.GetNextHop (), AODV_PORT));
+
+ // Generating gratuitous RREPs
+ if (gratRep)
+ {
+ RrepHeader gratRepHeader (/*prefix size=*/0, /*hops=*/toOrigin.GetHop (), /*dst=*/toOrigin.GetDestination (),
+ /*dst seqno=*/toOrigin.GetSeqNo (), /*origin=*/toDst.GetDestination (),
+ /*lifetime=*/toOrigin.GetLifeTime ());
+ Ptr packetToDst = Create ();
+ packetToDst->AddHeader (gratRepHeader);
+ TypeHeader type (AODVTYPE_RREP);
+ packetToDst->AddHeader (type);
+ Ptr socket = FindSocketWithInterfaceAddress (toDst.GetInterface ());
+ NS_ASSERT (socket);
+ NS_LOG_LOGIC ("Send gratuitous RREP " << packet->GetUid());
+ socket->SendTo (packetToDst, 0, InetSocketAddress (toDst.GetNextHop (), AODV_PORT));
+ }
+}
+
+void
+RoutingProtocol::SendReplyAck (Ipv4Address neighbor)
+{
+ NS_LOG_FUNCTION (this << " to " << neighbor);
+ RrepAckHeader h;
+ TypeHeader typeHeader (AODVTYPE_RREP_ACK);
+ Ptr packet = Create ();
+ packet->AddHeader (h);
+ packet->AddHeader (typeHeader);
+ RoutingTableEntry toNeighbor;
+ m_routingTable.LookupRoute (neighbor, toNeighbor);
+ Ptr socket = FindSocketWithInterfaceAddress (toNeighbor.GetInterface ());
+ NS_ASSERT (socket);
+ socket->SendTo (packet, 0, InetSocketAddress (neighbor, AODV_PORT));
+}
+
+void
+RoutingProtocol::RecvReply (Ptr p, Ipv4Address receiver, Ipv4Address sender)
+{
+ NS_LOG_FUNCTION(this << " src " << sender);
+ RrepHeader rrepHeader;
+ p->RemoveHeader (rrepHeader);
+ Ipv4Address dst = rrepHeader.GetDst ();
+ NS_LOG_LOGIC("RREP destination " << dst << " RREP origin " << rrepHeader.GetOrigin());
+
+ uint8_t hop = rrepHeader.GetHopCount () + 1;
+ rrepHeader.SetHopCount (hop);
+
+ // If RREP is Hello message
+ if (dst == rrepHeader.GetOrigin ())
+ {
+ ProcessHello (rrepHeader, receiver);
+ return;
+ }
+
+ /*
+ * If the route table entry to the destination is created or updated, then the following actions occur:
+ * - the route is marked as active,
+ * - the destination sequence number is marked as valid,
+ * - the next hop in the route entry is assigned to be the node from which the RREP is received,
+ * which is indicated by the source IP address field in the IP header,
+ * - the hop count is set to the value of the hop count from RREP message + 1
+ * - the expiry time is set to the current time plus the value of the Lifetime in the RREP message,
+ * - and the destination sequence number is the Destination Sequence Number in the RREP message.
+ */
+ Ptr dev = m_ipv4->GetNetDevice (m_ipv4->GetInterfaceForAddress (receiver));
+ RoutingTableEntry newEntry (/*device=*/dev, /*dst=*/dst, /*validSeqNo=*/true, /*seqno=*/rrepHeader.GetDstSeqno (),
+ /*iface=*/m_ipv4->GetAddress (m_ipv4->GetInterfaceForAddress (receiver), 0),/*hop=*/hop,
+ /*nextHop=*/sender, /*lifeTime=*/rrepHeader.GetLifeTime ());
+ RoutingTableEntry toDst;
+ if (m_routingTable.LookupRoute (dst, toDst))
+ {
+ /*
+ * The existing entry is updated only in the following circumstances:
+ * (i) the sequence number in the routing table is marked as invalid in route table entry.
+ */
+ if (!toDst.GetValidSeqNo ())
+ {
+ m_routingTable.Update (newEntry);
+ }
+ // (ii)the Destination Sequence Number in the RREP is greater than the node's copy of the destination sequence number and the known value is valid,
+ else if ((int32_t (rrepHeader.GetDstSeqno ()) - int32_t (toDst.GetSeqNo ())) > 0)
+ {
+ m_routingTable.Update (newEntry);
+ }
+ else
+ {
+ // (iii) the sequence numbers are the same, but the route is marked as inactive.
+ if ((rrepHeader.GetDstSeqno () == toDst.GetSeqNo ()) && (toDst.GetFlag () != VALID))
+ {
+ m_routingTable.Update (newEntry);
+ }
+ // (iv) the sequence numbers are the same, and the New Hop Count is smaller than the hop count in route table entry.
+ else if ((rrepHeader.GetDstSeqno () == toDst.GetSeqNo ()) && (hop < toDst.GetHop ()))
+ {
+ m_routingTable.Update (newEntry);
+ }
+ }
+ }
+ else
+ {
+ // The forward route for this destination is created if it does not already exist.
+ NS_LOG_LOGIC ("add new route");
+ m_routingTable.AddRoute (newEntry);
+ }
+ // Acknowledge receipt of the RREP by sending a RREP-ACK message back
+ if (rrepHeader.GetAckRequired ())
+ {
+ SendReplyAck (sender);
+ rrepHeader.SetAckRequired (false);
+ }
+ NS_LOG_LOGIC ("receiver " << receiver << " origin " << rrepHeader.GetOrigin ());
+ if (IsMyOwnAddress (rrepHeader.GetOrigin ()))
+ {
+ if (toDst.GetFlag () == IN_SEARCH)
+ {
+ m_routingTable.Update (newEntry);
+ m_addressReqTimer[dst].Remove ();
+ m_addressReqTimer.erase (dst);
+ }
+ SendPacketFromQueue (rrepHeader.GetDst (), newEntry.GetRoute ());
+ return;
+ }
+
+ RoutingTableEntry toOrigin;
+ if (!m_routingTable.LookupRoute (rrepHeader.GetOrigin (), toOrigin))
+ {
+ return; // Impossible! drop.
+ }
+ toOrigin.SetLifeTime (std::max (ActiveRouteTimeout, toOrigin.GetLifeTime ()));
+ m_routingTable.Update (toOrigin);
+
+ // Update information about precursors
+ m_routingTable.LookupRoute (rrepHeader.GetDst (), toDst);
+ toDst.InsertPrecursor (toOrigin.GetNextHop ());
+ m_routingTable.Update (toDst);
+
+ RoutingTableEntry toNextHopToDst;
+ m_routingTable.LookupRoute (toDst.GetNextHop (), toNextHopToDst);
+ toNextHopToDst.InsertPrecursor (toOrigin.GetNextHop ());
+ m_routingTable.Update (toNextHopToDst);
+
+ toOrigin.InsertPrecursor (toDst.GetNextHop ());
+ m_routingTable.Update (toOrigin);
+
+ RoutingTableEntry toNextHopToOrigin;
+ m_routingTable.LookupRoute (toOrigin.GetNextHop (), toNextHopToOrigin);
+ toNextHopToOrigin.InsertPrecursor (toDst.GetNextHop ());
+ m_routingTable.Update (toNextHopToOrigin);
+
+ Ptr packet = Create ();
+ packet->AddHeader (rrepHeader);
+ TypeHeader tHeader (AODVTYPE_RREP);
+ packet->AddHeader (tHeader);
+ Ptr socket = FindSocketWithInterfaceAddress (toOrigin.GetInterface ());
+ NS_ASSERT (socket);
+ socket->SendTo (packet, 0, InetSocketAddress (toOrigin.GetNextHop (), AODV_PORT));
+}
+
+void
+RoutingProtocol::RecvReplyAck (Ipv4Address neighbor)
+{
+ NS_LOG_FUNCTION (this);
+ RoutingTableEntry rt;
+ if(m_routingTable.LookupRoute(neighbor, rt))
+ {
+ rt.m_ackTimer.Cancel ();
+ rt.SetFlag (VALID);
+ m_routingTable.Update(rt);
+ }
+}
+
+void
+RoutingProtocol::ProcessHello (RrepHeader const & rrepHeader, Ipv4Address receiver )
+{
+ NS_LOG_FUNCTION(this << "from " << rrepHeader.GetDst ());
+ /*
+ * Whenever a node receives a Hello message from a neighbor, the node
+ * SHOULD make sure that it has an active route to the neighbor, and
+ * create one if necessary.
+ */
+ RoutingTableEntry toNeighbor;
+ if (!m_routingTable.LookupRoute (rrepHeader.GetDst (), toNeighbor))
+ {
+ Ptr dev = m_ipv4->GetNetDevice (m_ipv4->GetInterfaceForAddress (receiver));
+ RoutingTableEntry newEntry (/*device=*/dev, /*dst=*/rrepHeader.GetDst (), /*validSeqNo=*/true, /*seqno=*/rrepHeader.GetDstSeqno (),
+ /*iface=*/m_ipv4->GetAddress (m_ipv4->GetInterfaceForAddress (receiver), 0),
+ /*hop=*/1, /*nextHop=*/rrepHeader.GetDst (), /*lifeTime=*/rrepHeader.GetLifeTime ());
+ m_routingTable.AddRoute (newEntry);
+ }
+ else
+ {
+ toNeighbor.SetLifeTime (std::max (Scalar (AllowedHelloLoss) * HelloInterval, toNeighbor.GetLifeTime ()));
+ toNeighbor.SetSeqNo (rrepHeader.GetDstSeqno ());
+ toNeighbor.SetValidSeqNo (true);
+ toNeighbor.SetFlag (VALID);
+ toNeighbor.SetOutputDevice (m_ipv4->GetNetDevice (m_ipv4->GetInterfaceForAddress (receiver)));
+ toNeighbor.SetInterface (m_ipv4->GetAddress (m_ipv4->GetInterfaceForAddress (receiver), 0));
+ m_routingTable.Update (toNeighbor);
+ }
+ if (EnableHello)
+ {
+ m_nb.Update (rrepHeader.GetDst (), Scalar (AllowedHelloLoss) * HelloInterval);
+ }
+}
+
+void
+RoutingProtocol::RecvError (Ptr p, Ipv4Address src )
+{
+ NS_LOG_FUNCTION (this << " from " << src);
+ RerrHeader rerrHeader;
+ p->RemoveHeader (rerrHeader);
+ std::map dstWithNextHopSrc;
+ std::map unreachable;
+ m_routingTable.GetListOfDestinationWithNextHop (src, dstWithNextHopSrc);
+ std::pair un;
+ while (rerrHeader.RemoveUnDestination (un))
+ {
+ if (m_nb.IsNeighbor (un.first))
+ SendRerrWhenBreaksLinkToNextHop (un.first);
+ else
+ {
+ for (std::map::const_iterator i =
+ dstWithNextHopSrc.begin (); i != dstWithNextHopSrc.end (); ++i)
+ {
+ if (i->first == un.first)
+ {
+ Ipv4Address dst = un.first;
+ unreachable.insert (un);
+ }
+ }
+ }
+ }
+
+ std::vector precursors;
+ for (std::map::const_iterator i = unreachable.begin ();
+ i != unreachable.end ();)
+ {
+ if (!rerrHeader.AddUnDestination (i->first, i->second))
+ {
+ TypeHeader typeHeader (AODVTYPE_RERR);
+ Ptr packet = Create ();
+ packet->AddHeader (rerrHeader);
+ packet->AddHeader (typeHeader);
+ SendRerrMessage (packet, precursors);
+ rerrHeader.Clear ();
+ }
+ else
+ {
+ RoutingTableEntry toDst;
+ m_routingTable.LookupRoute (i->first, toDst);
+ toDst.GetPrecursors (precursors);
+ ++i;
+ }
+ }
+ if (rerrHeader.GetDestCount () != 0)
+ {
+ TypeHeader typeHeader (AODVTYPE_RERR);
+ Ptr packet = Create ();
+ packet->AddHeader (rerrHeader);
+ packet->AddHeader (typeHeader);
+ SendRerrMessage (packet, precursors);
+ }
+ m_routingTable.InvalidateRoutesWithDst (unreachable);
+}
+
+void
+RoutingProtocol::RouteRequestTimerExpire (Ipv4Address dst)
+{
+ NS_LOG_LOGIC(this);
+ RoutingTableEntry toDst;
+ m_routingTable.LookupRoute (dst, toDst);
+ if (toDst.GetFlag () == VALID)
+ {
+ SendPacketFromQueue (dst, toDst.GetRoute ());
+ NS_LOG_LOGIC ("route to " << dst << " found");
+ return;
+ }
+ /*
+ * If a route discovery has been attempted RreqRetries times at the maximum TTL without
+ * receiving any RREP, all data packets destined for the corresponding destination SHOULD be
+ * dropped from the buffer and a Destination Unreachable message SHOULD be delivered to the application.
+ */
+ if (toDst.GetRreqCnt () == RreqRetries)
+ {
+ NS_LOG_LOGIC("route discovery to " << dst << " has been attempted RreqRetries times");
+ m_addressReqTimer.erase (dst);
+ m_routingTable.DeleteRoute (dst);
+ NS_LOG_DEBUG ("Route not found. Drop packet with dst " << dst);
+ m_queue.DropPacketWithDst (dst);
+ return;
+ }
+
+ if (toDst.GetFlag () == IN_SEARCH)
+ {
+ NS_LOG_LOGIC ("Send new RREQ to " << dst << " ttl " << NetDiameter);
+ SendRequest (dst);
+ }
+ else
+ {
+ NS_LOG_DEBUG ("Route down. Stop search. Drop packet with destination " << dst);
+ m_addressReqTimer.erase(dst);
+ m_routingTable.DeleteRoute(dst);
+ m_queue.DropPacketWithDst(dst);
+ }
+}
+
+void
+RoutingProtocol::HelloTimerExpire ()
+{
+ NS_LOG_FUNCTION(this);
+ SendHello ();
+ m_htimer.Cancel ();
+ Time t = Scalar(0.01)*MilliSeconds(UniformVariable().GetInteger (0, 100));
+ m_htimer.Schedule (HelloInterval - t);
+}
+
+void
+RoutingProtocol::RreqRateLimitTimerExpire ()
+{
+ m_rreqCount = 0;
+ m_rreqRateLimitTimer.Schedule (Seconds (1));
+}
+
+void
+RoutingProtocol::AckTimerExpire (Ipv4Address neighbor, Time blacklistTimeout)
+{
+ NS_LOG_FUNCTION(this);
+ m_routingTable.MarkLinkAsUnidirectional (neighbor, blacklistTimeout);
+}
+
+void
+RoutingProtocol::SendHello ()
+{
+ NS_LOG_FUNCTION(this);
+ /* Broadcast a RREP with TTL = 1 with the RREP message fields set as follows:
+ * Destination IP Address The node's IP address.
+ * Destination Sequence Number The node's latest sequence number.
+ * Hop Count 0
+ * Lifetime AllowedHelloLoss * HelloInterval
+ */
+ for (std::map , Ipv4InterfaceAddress>::const_iterator j = m_socketAddresses.begin (); j != m_socketAddresses.end (); ++j)
+ {
+ Ptr socket = j->first;
+ Ipv4InterfaceAddress iface = j->second;
+ RrepHeader helloHeader (/*prefix size=*/0, /*hops=*/0, /*dst=*/iface.GetLocal (), /*dst seqno=*/m_seqNo,
+ /*origin=*/iface.GetLocal (),/*lifetime=*/Scalar (AllowedHelloLoss) * HelloInterval);
+ Ptr packet = Create ();
+ packet->AddHeader (helloHeader);
+ TypeHeader tHeader (AODVTYPE_RREP);
+ packet->AddHeader (tHeader);
+ socket->Send (packet);
+ }
+}
+
+void
+RoutingProtocol::SendPacketFromQueue (Ipv4Address dst, Ptr route)
+{
+ NS_LOG_FUNCTION(this);
+ QueueEntry queueEntry;
+ while (m_queue.Dequeue (dst, queueEntry))
+ {
+ UnicastForwardCallback ucb = queueEntry.GetUnicastForwardCallback ();
+ ucb (route, queueEntry.GetPacket (), queueEntry.GetIpv4Header ());
+ }
+}
+
+void
+RoutingProtocol::Send (Ptr route, Ptr packet,
+ const Ipv4Header & header)
+{
+ NS_LOG_FUNCTION (this << packet->GetUid() << (uint16_t) header.GetProtocol());
+ Ptr l3 = m_ipv4->GetObject ();
+ NS_ASSERT(l3 != 0);
+ Ptr p = packet->Copy ();
+ l3->Send (p, route->GetSource (), header.GetDestination (),
+ header.GetProtocol (), route);
+}
+
+void
+RoutingProtocol::SendRerrWhenBreaksLinkToNextHop (Ipv4Address nextHop)
+{
+ NS_LOG_FUNCTION (this << nextHop);
+ RerrHeader rerrHeader;
+ std::vector precursors;
+ std::map unreachable;
+
+ RoutingTableEntry toNextHop;
+ if (!m_routingTable.LookupRoute (nextHop, toNextHop))
+ return;
+ toNextHop.GetPrecursors (precursors);
+ rerrHeader.AddUnDestination (nextHop, toNextHop.GetSeqNo ());
+ m_routingTable.GetListOfDestinationWithNextHop (nextHop, unreachable);
+ for (std::map::const_iterator i = unreachable.begin (); i
+ != unreachable.end ();)
+ {
+ if (!rerrHeader.AddUnDestination (i->first, i->second))
+ {
+ NS_LOG_LOGIC ("Send RERR message with maximum size.");
+ TypeHeader typeHeader (AODVTYPE_RERR);
+ Ptr packet = Create ();
+ packet->AddHeader (rerrHeader);
+ packet->AddHeader (typeHeader);
+ SendRerrMessage (packet, precursors);
+ rerrHeader.Clear ();
+ }
+ else
+ {
+ RoutingTableEntry toDst;
+ m_routingTable.LookupRoute (i->first, toDst);
+ toDst.GetPrecursors (precursors);
+ ++i;
+ }
+ }
+ if (rerrHeader.GetDestCount () != 0)
+ {
+ TypeHeader typeHeader (AODVTYPE_RERR);
+ Ptr packet = Create ();
+ packet->AddHeader (rerrHeader);
+ packet->AddHeader (typeHeader);
+ SendRerrMessage (packet, precursors);
+ }
+ unreachable.insert (std::make_pair (nextHop, toNextHop.GetSeqNo ()));
+ m_routingTable.InvalidateRoutesWithDst (unreachable);
+}
+
+void
+RoutingProtocol::SendRerrWhenNoRouteToForward (Ipv4Address dst,
+ uint32_t dstSeqNo, Ipv4Address origin)
+{
+ NS_LOG_FUNCTION (this);
+ RerrHeader rerrHeader;
+ rerrHeader.AddUnDestination (dst, dstSeqNo);
+ RoutingTableEntry toOrigin;
+ Ptr packet = Create ();
+ packet->AddHeader (rerrHeader);
+ packet->AddHeader (TypeHeader (AODVTYPE_RERR));
+ if (m_routingTable.LookupRoute (origin, toOrigin))
+ {
+ if (toOrigin.GetFlag () == VALID)
+ {
+ Ptr socket = FindSocketWithInterfaceAddress (
+ toOrigin.GetInterface ());
+ NS_ASSERT (socket);
+ NS_LOG_LOGIC ("Unicast RERR to the source of the data transmission");
+ socket->SendTo (packet, 0, InetSocketAddress (toOrigin.GetNextHop (), AODV_PORT));
+ }
+
+ }
+ else
+ {
+ for (std::map , Ipv4InterfaceAddress>::const_iterator i =
+ m_socketAddresses.begin (); i != m_socketAddresses.end (); ++i)
+ {
+ Ptr socket = i->first;
+ Ipv4InterfaceAddress iface = i->second;
+ NS_ASSERT (socket);
+ NS_LOG_LOGIC ("Broadcast RERR message from interface " << iface.GetLocal());
+ socket->Send (packet);
+ }
+ }
+}
+
+void
+RoutingProtocol::SendRerrMessage (Ptr packet, std::vector precursors)
+{
+ NS_LOG_FUNCTION(this);
+
+ if (precursors.empty ())
+ {
+ NS_LOG_LOGIC ("No precursors");
+ return;
+ }
+ // If there is only one precursor, RERR SHOULD be unicast toward that precursor
+ if (precursors.size () == 1)
+ {
+ RoutingTableEntry toPrecursor;
+ if (!m_routingTable.LookupRoute (precursors.front (), toPrecursor))
+ return;
+ Ptr socket = FindSocketWithInterfaceAddress (toPrecursor.GetInterface ());
+ NS_ASSERT (socket);
+ if (toPrecursor.GetFlag () == VALID)
+ {
+ NS_LOG_LOGIC ("one precursor => unicast RERR to " << toPrecursor.GetDestination() << " from " << toPrecursor.GetInterface ().GetLocal ());
+ socket->SendTo (packet, 0, InetSocketAddress (precursors.front (), AODV_PORT));
+ }
+ else
+ NS_LOG_LOGIC ("One precursor, but no valid route to this precursor");
+ return;
+ }
+
+ // Should only transmit RERR on those interfaces which have precursor nodes for the broken route
+ std::vector ifaces;
+ RoutingTableEntry toPrecursor;
+ for (std::vector::const_iterator i = precursors.begin (); i
+ != precursors.end (); ++i)
+ {
+ if (!m_routingTable.LookupRoute (*i, toPrecursor))
+ break;
+ bool result = true;
+ for (std::vector::const_iterator i =
+ ifaces.begin (); i != ifaces.end (); ++i)
+ {
+ if (*i == toPrecursor.GetInterface ())
+ {
+ result = false;
+ break;
+ }
+ }
+ if (result)
+ ifaces.push_back (toPrecursor.GetInterface ());
+ }
+
+ for (std::vector::const_iterator i = ifaces.begin (); i != ifaces.end (); ++i)
+ {
+ Ptr socket = FindSocketWithInterfaceAddress (*i);
+ NS_ASSERT (socket);
+ NS_LOG_LOGIC ("Broadcast RERR message from interface " << i->GetLocal());
+ socket->Send (packet);
+ }
+
+}
+
+Ptr
+RoutingProtocol::FindSocketWithInterfaceAddress (Ipv4InterfaceAddress addr ) const
+{
+ for (std::map , Ipv4InterfaceAddress>::const_iterator j =
+ m_socketAddresses.begin (); j != m_socketAddresses.end (); ++j)
+ {
+ Ptr socket = j->first;
+ Ipv4InterfaceAddress iface = j->second;
+ if (iface == addr)
+ return socket;
+ }
+ Ptr socket;
+ return socket;
+}
+
+void
+RoutingProtocol::Drop(Ptr packet, const Ipv4Header & header, Socket::SocketErrno err)
+{
+ NS_LOG_DEBUG (this <<" drop own packet " << packet->GetUid() << " to " << header.GetDestination () << " from queue. Error " << err);
+}
+
+}
+}
diff --git a/src/routing/manet/aodv/aodv-routing-protocol.h b/src/routing/manet/aodv/aodv-routing-protocol.h
new file mode 100644
index 000000000..07db2c225
--- /dev/null
+++ b/src/routing/manet/aodv/aodv-routing-protocol.h
@@ -0,0 +1,254 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2009 IITP RAS
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Based on
+ * NS-2 AODV model developed by the CMU/MONARCH group and optimized and
+ * tuned by Samir Das and Mahesh Marina, University of Cincinnati;
+ *
+ * AODV-UU implementation by Erik Nordström of Uppsala University
+ * http://core.it.uu.se/core/index.php/AODV-UU
+ *
+ * Authors: Elena Buchatskaia
+ * Pavel Boyko
+ */
+#ifndef AODVROUTINGPROTOCOL_H
+#define AODVROUTINGPROTOCOL_H
+
+#include "aodv-rtable.h"
+#include "aodv-rqueue.h"
+#include "aodv-packet.h"
+#include "aodv-neighbor.h"
+
+#include "ns3/dpd.h"
+#include "ns3/node.h"
+#include "ns3/ipv4-routing-protocol.h"
+#include "ns3/ipv4-interface.h"
+#include "ns3/ipv4-l3-protocol.h"
+#include
+
+namespace ns3
+{
+namespace aodv
+{
+/**
+ * \ingroup aodv
+ *
+ * \brief AODV routing protocol
+ */
+class RoutingProtocol : public Ipv4RoutingProtocol
+{
+public:
+ static TypeId GetTypeId (void);
+ static const uint32_t AODV_PORT;
+
+ /// c-tor
+ RoutingProtocol ();
+ virtual ~RoutingProtocol();
+ virtual void DoDispose ();
+
+ ///\name From Ipv4RoutingProtocol
+ //\{
+ Ptr RouteOutput (Ptr p, const Ipv4Header &header, uint32_t oif, Socket::SocketErrno &sockerr);
+ bool RouteInput (Ptr p, const Ipv4Header &header, Ptr idev,
+ UnicastForwardCallback ucb, MulticastForwardCallback mcb,
+ LocalDeliverCallback lcb, ErrorCallback ecb);
+ virtual void NotifyInterfaceUp (uint32_t interface);
+ virtual void NotifyInterfaceDown (uint32_t interface);
+ virtual void NotifyAddAddress (uint32_t interface, Ipv4InterfaceAddress address);
+ virtual void NotifyRemoveAddress (uint32_t interface, Ipv4InterfaceAddress address);
+ virtual void SetIpv4 (Ptr ipv4);
+ //\}
+
+ ///\name Handle protocol parameters
+ //\{
+ bool GetDesinationOnlyFlag () const { return DestinationOnly; }
+ void SetDesinationOnlyFlag (bool f) { DestinationOnly = f; }
+ bool GetGratuitousReplyFlag () const { return GratuitousReply; }
+ void SetGratuitousReplyFlag (bool f) { GratuitousReply = f; }
+ void SetHelloEnable (bool f) { EnableHello = f; }
+ bool GetHelloEnable () const { return EnableHello; }
+ void SetBroadcastEnable (bool f) { EnableBroadcast = f; }
+ bool GetBroadcastEnable () const { return EnableBroadcast; }
+ //\}
+private:
+ ///\name Protocol parameters.
+ //\{
+ uint32_t RreqRetries; ///< Maximum number of retransmissions of RREQ with TTL = NetDiameter to discover a route
+ uint16_t RreqRateLimit; ///< Maximum number of RREQ per second.
+ Time ActiveRouteTimeout; ///< Period of time during which the route is considered to be valid.
+ uint32_t NetDiameter; ///< Net diameter measures the maximum possible number of hops between two nodes in the network
+ /**
+ * NodeTraversalTime is a conservative estimate of the average one hop traversal time for packets
+ * and should include queuing delays, interrupt processing times and transfer times.
+ */
+ Time NodeTraversalTime;
+ Time NetTraversalTime; ///< Estimate of the average net traversal time.
+ Time PathDiscoveryTime; ///< Estimate of maximum time needed to find route in network.
+ Time MyRouteTimeout; ///< Value of lifetime field in RREP generating by this node.
+ /**
+ * Every HelloInterval the node checks whether it has sent a broadcast within the last HelloInterval.
+ * If it has not, it MAY broadcast a Hello message
+ */
+ Time HelloInterval;
+ uint32_t AllowedHelloLoss; ///< Number of hello messages which may be loss for valid link
+ /**
+ * DeletePeriod is intended to provide an upper bound on the time for which an upstream node A
+ * can have a neighbor B as an active next hop for destination D, while B has invalidated the route to D.
+ */
+ Time DeletePeriod;
+ Time NextHopWait; ///< Period of our waiting for the neighbour's RREP_ACK
+ /**
+ * The TimeoutBuffer is configurable. Its purpose is to provide a buffer for the timeout so that if the RREP is delayed
+ * due to congestion, a timeout is less likely to occur while the RREP is still en route back to the source.
+ */
+ uint16_t TimeoutBuffer;
+ Time BlackListTimeout; ///< Time for which the node is put into the blacklist
+ uint32_t MaxQueueLen; ///< The maximum number of packets that we allow a routing protocol to buffer.
+ Time MaxQueueTime; ///< The maximum period of time that a routing protocol is allowed to buffer a packet for.
+ bool DestinationOnly; ///< Indicates only the destination may respond to this RREQ.
+ bool GratuitousReply; ///< Indicates whether a gratuitous RREP should be unicast to the node originated route discovery.
+ bool EnableHello; ///< Indicates whether a hello messages enable
+ bool EnableBroadcast; ///< Indicates whether a a broadcast data packets forwarding enable
+ //\}
+
+ /// IP protocol
+ Ptr