A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
manet-routing-compare.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2011 University of Kansas
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Justin Rohrer <rohrej@ittc.ku.edu>
7 *
8 * James P.G. Sterbenz <jpgs@ittc.ku.edu>, director
9 * ResiliNets Research Group https://resilinets.org/
10 * Information and Telecommunication Technology Center (ITTC)
11 * and Department of Electrical Engineering and Computer Science
12 * The University of Kansas Lawrence, KS USA.
13 *
14 * Work supported in part by NSF FIND (Future Internet Design) Program
15 * under grant CNS-0626918 (Postmodern Internet Architecture),
16 * NSF grant CNS-1050226 (Multilayer Network Resilience Analysis and Experimentation on GENI),
17 * US Department of Defense (DoD), and ITTC at The University of Kansas.
18 */
19
20/*
21 * This example program allows one to run ns-3 DSDV, AODV, or OLSR under
22 * a typical random waypoint mobility model.
23 *
24 * By default, the simulation runs for 200 simulated seconds, of which
25 * the first 50 are used for start-up time. The number of nodes is 50.
26 * Nodes move according to RandomWaypointMobilityModel with a speed of
27 * 20 m/s and no pause time within a 300x1500 m region. The WiFi is
28 * in ad hoc mode with a 2 Mb/s rate (802.11b) and a Friis loss model.
29 * The transmit power is set to 7.5 dBm.
30 *
31 * It is possible to change the mobility and density of the network by
32 * directly modifying the speed and the number of nodes. It is also
33 * possible to change the characteristics of the network by changing
34 * the transmit power (as power increases, the impact of mobility
35 * decreases and the effective density increases).
36 *
37 * By default, OLSR is used, but specifying a value of 2 for the protocol
38 * will cause AODV to be used, and specifying a value of 3 will cause
39 * DSDV to be used.
40 *
41 * By default, there are 10 source/sink data pairs sending UDP data
42 * at an application rate of 2.048 Kb/s each. This is typically done
43 * at a rate of 4 64-byte packets per second. Application data is
44 * started at a random time between 50 and 51 seconds and continues
45 * to the end of the simulation.
46 *
47 * The program outputs a few items:
48 * - packet receptions are notified to stdout such as:
49 * <timestamp> <node-id> received one packet from <src-address>
50 * - each second, the data reception statistics are tabulated and output
51 * to a comma-separated value (csv) file
52 * - some tracing and flow monitor configuration that used to work is
53 * left commented inline in the program
54 */
55
56#include "ns3/aodv-module.h"
57#include "ns3/applications-module.h"
58#include "ns3/core-module.h"
59#include "ns3/dsdv-module.h"
60#include "ns3/dsr-module.h"
61#include "ns3/flow-monitor-module.h"
62#include "ns3/internet-module.h"
63#include "ns3/mobility-module.h"
64#include "ns3/network-module.h"
65#include "ns3/olsr-module.h"
66#include "ns3/yans-wifi-helper.h"
67
68#include <fstream>
69#include <iostream>
70
71using namespace ns3;
72using namespace dsr;
73
74NS_LOG_COMPONENT_DEFINE("manet-routing-compare");
75
76/**
77 * Routing experiment class.
78 *
79 * It handles the creation and run of an experiment.
80 */
82{
83 public:
85 /**
86 * Run the experiment.
87 */
88 void Run();
89
90 /**
91 * Handles the command-line parameters.
92 * \param argc The argument count.
93 * \param argv The argument vector.
94 */
95 void CommandSetup(int argc, char** argv);
96
97 private:
98 /**
99 * Setup the receiving socket in a Sink Node.
100 * \param addr The address of the node.
101 * \param node The node pointer.
102 * \return the socket.
103 */
105 /**
106 * Receive a packet.
107 * \param socket The receiving socket.
108 */
109 void ReceivePacket(Ptr<Socket> socket);
110 /**
111 * Compute the throughput.
112 */
113 void CheckThroughput();
114
115 uint32_t port{9}; //!< Receiving port number.
116 uint32_t bytesTotal{0}; //!< Total received bytes.
117 uint32_t packetsReceived{0}; //!< Total received packets.
118
119 std::string m_CSVfileName{"manet-routing.output.csv"}; //!< CSV filename.
120 int m_nSinks{10}; //!< Number of sink nodes.
121 std::string m_protocolName{"AODV"}; //!< Protocol name.
122 double m_txp{7.5}; //!< Tx power.
123 bool m_traceMobility{false}; //!< Enable mobility tracing.
124 bool m_flowMonitor{false}; //!< Enable FlowMonitor.
125};
126
130
131static inline std::string
133{
134 std::ostringstream oss;
135
136 oss << Simulator::Now().GetSeconds() << " " << socket->GetNode()->GetId();
137
138 if (InetSocketAddress::IsMatchingType(senderAddress))
139 {
141 oss << " received one packet from " << addr.GetIpv4();
142 }
143 else
144 {
145 oss << " received one packet!";
146 }
147 return oss.str();
148}
149
150void
152{
153 Ptr<Packet> packet;
154 Address senderAddress;
155 while ((packet = socket->RecvFrom(senderAddress)))
156 {
157 bytesTotal += packet->GetSize();
158 packetsReceived += 1;
159 NS_LOG_UNCOND(PrintReceivedPacket(socket, packet, senderAddress));
160 }
161}
162
163void
165{
166 double kbs = (bytesTotal * 8.0) / 1000;
167 bytesTotal = 0;
168
169 std::ofstream out(m_CSVfileName, std::ios::app);
170
171 out << (Simulator::Now()).GetSeconds() << "," << kbs << "," << packetsReceived << ","
172 << m_nSinks << "," << m_protocolName << "," << m_txp << "" << std::endl;
173
174 out.close();
175 packetsReceived = 0;
177}
178
181{
182 TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory");
185 sink->Bind(local);
186 sink->SetRecvCallback(MakeCallback(&RoutingExperiment::ReceivePacket, this));
187
188 return sink;
189}
190
191void
193{
194 CommandLine cmd(__FILE__);
195 cmd.AddValue("CSVfileName", "The name of the CSV output file name", m_CSVfileName);
196 cmd.AddValue("traceMobility", "Enable mobility tracing", m_traceMobility);
197 cmd.AddValue("protocol", "Routing protocol (OLSR, AODV, DSDV, DSR)", m_protocolName);
198 cmd.AddValue("flowMonitor", "enable FlowMonitor", m_flowMonitor);
199 cmd.Parse(argc, argv);
200
201 std::vector<std::string> allowedProtocols{"OLSR", "AODV", "DSDV", "DSR"};
202
203 if (std::find(std::begin(allowedProtocols), std::end(allowedProtocols), m_protocolName) ==
204 std::end(allowedProtocols))
205 {
206 NS_FATAL_ERROR("No such protocol:" << m_protocolName);
207 }
208}
209
210int
211main(int argc, char* argv[])
212{
214 experiment.CommandSetup(argc, argv);
215 experiment.Run();
216
217 return 0;
218}
219
220void
222{
224
225 // blank out the last output file and write the column headers
226 std::ofstream out(m_CSVfileName);
227 out << "SimulationSecond,"
228 << "ReceiveRate,"
229 << "PacketsReceived,"
230 << "NumberOfSinks,"
231 << "RoutingProtocol,"
232 << "TransmissionPower" << std::endl;
233 out.close();
234
235 int nWifis = 50;
236
237 double TotalTime = 200.0;
238 std::string rate("2048bps");
239 std::string phyMode("DsssRate11Mbps");
240 std::string tr_name("manet-routing-compare");
241 int nodeSpeed = 20; // in m/s
242 int nodePause = 0; // in s
243
244 Config::SetDefault("ns3::OnOffApplication::PacketSize", StringValue("64"));
245 Config::SetDefault("ns3::OnOffApplication::DataRate", StringValue(rate));
246
247 // Set Non-unicastMode rate to unicast mode
248 Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue(phyMode));
249
250 NodeContainer adhocNodes;
251 adhocNodes.Create(nWifis);
252
253 // setting up wifi phy and channel using helpers
254 WifiHelper wifi;
255 wifi.SetStandard(WIFI_STANDARD_80211b);
256
257 YansWifiPhyHelper wifiPhy;
258 YansWifiChannelHelper wifiChannel;
259 wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
260 wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel");
261 wifiPhy.SetChannel(wifiChannel.Create());
262
263 // Add a mac and disable rate control
264 WifiMacHelper wifiMac;
265 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
266 "DataMode",
267 StringValue(phyMode),
268 "ControlMode",
269 StringValue(phyMode));
270
271 wifiPhy.Set("TxPowerStart", DoubleValue(m_txp));
272 wifiPhy.Set("TxPowerEnd", DoubleValue(m_txp));
273
274 wifiMac.SetType("ns3::AdhocWifiMac");
275 NetDeviceContainer adhocDevices = wifi.Install(wifiPhy, wifiMac, adhocNodes);
276
277 MobilityHelper mobilityAdhoc;
278 int64_t streamIndex = 0; // used to get consistent mobility across scenarios
279
280 ObjectFactory pos;
281 pos.SetTypeId("ns3::RandomRectanglePositionAllocator");
282 pos.Set("X", StringValue("ns3::UniformRandomVariable[Min=0.0|Max=300.0]"));
283 pos.Set("Y", StringValue("ns3::UniformRandomVariable[Min=0.0|Max=1500.0]"));
284
285 Ptr<PositionAllocator> taPositionAlloc = pos.Create()->GetObject<PositionAllocator>();
286 streamIndex += taPositionAlloc->AssignStreams(streamIndex);
287
288 std::stringstream ssSpeed;
289 ssSpeed << "ns3::UniformRandomVariable[Min=0.0|Max=" << nodeSpeed << "]";
290 std::stringstream ssPause;
291 ssPause << "ns3::ConstantRandomVariable[Constant=" << nodePause << "]";
292 mobilityAdhoc.SetMobilityModel("ns3::RandomWaypointMobilityModel",
293 "Speed",
294 StringValue(ssSpeed.str()),
295 "Pause",
296 StringValue(ssPause.str()),
297 "PositionAllocator",
298 PointerValue(taPositionAlloc));
299 mobilityAdhoc.SetPositionAllocator(taPositionAlloc);
300 mobilityAdhoc.Install(adhocNodes);
301 streamIndex += mobilityAdhoc.AssignStreams(adhocNodes, streamIndex);
302
303 AodvHelper aodv;
305 DsdvHelper dsdv;
306 DsrHelper dsr;
307 DsrMainHelper dsrMain;
309 InternetStackHelper internet;
310
311 if (m_protocolName == "OLSR")
312 {
313 list.Add(olsr, 100);
314 internet.SetRoutingHelper(list);
315 internet.Install(adhocNodes);
316 }
317 else if (m_protocolName == "AODV")
318 {
319 list.Add(aodv, 100);
320 internet.SetRoutingHelper(list);
321 internet.Install(adhocNodes);
322 }
323 else if (m_protocolName == "DSDV")
324 {
325 list.Add(dsdv, 100);
326 internet.SetRoutingHelper(list);
327 internet.Install(adhocNodes);
328 }
329 else if (m_protocolName == "DSR")
330 {
331 internet.Install(adhocNodes);
332 dsrMain.Install(dsr, adhocNodes);
333 if (m_flowMonitor)
334 {
335 NS_FATAL_ERROR("Error: FlowMonitor does not work with DSR. Terminating.");
336 }
337 }
338 else
339 {
340 NS_FATAL_ERROR("No such protocol:" << m_protocolName);
341 }
342
343 NS_LOG_INFO("assigning ip address");
344
345 Ipv4AddressHelper addressAdhoc;
346 addressAdhoc.SetBase("10.1.1.0", "255.255.255.0");
347 Ipv4InterfaceContainer adhocInterfaces;
348 adhocInterfaces = addressAdhoc.Assign(adhocDevices);
349
350 OnOffHelper onoff1("ns3::UdpSocketFactory", Address());
351 onoff1.SetAttribute("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=1.0]"));
352 onoff1.SetAttribute("OffTime", StringValue("ns3::ConstantRandomVariable[Constant=0.0]"));
353
354 for (int i = 0; i < m_nSinks; i++)
355 {
356 Ptr<Socket> sink = SetupPacketReceive(adhocInterfaces.GetAddress(i), adhocNodes.Get(i));
357
358 AddressValue remoteAddress(InetSocketAddress(adhocInterfaces.GetAddress(i), port));
359 onoff1.SetAttribute("Remote", remoteAddress);
360
362 ApplicationContainer temp = onoff1.Install(adhocNodes.Get(i + m_nSinks));
363 temp.Start(Seconds(var->GetValue(100.0, 101.0)));
364 temp.Stop(Seconds(TotalTime));
365 }
366
367 std::stringstream ss;
368 ss << nWifis;
369 std::string nodes = ss.str();
370
371 std::stringstream ss2;
372 ss2 << nodeSpeed;
373 std::string sNodeSpeed = ss2.str();
374
375 std::stringstream ss3;
376 ss3 << nodePause;
377 std::string sNodePause = ss3.str();
378
379 std::stringstream ss4;
380 ss4 << rate;
381 std::string sRate = ss4.str();
382
383 // NS_LOG_INFO("Configure Tracing.");
384 // tr_name = tr_name + "_" + m_protocolName +"_" + nodes + "nodes_" + sNodeSpeed + "speed_" +
385 // sNodePause + "pause_" + sRate + "rate";
386
387 // AsciiTraceHelper ascii;
388 // Ptr<OutputStreamWrapper> osw = ascii.CreateFileStream(tr_name + ".tr");
389 // wifiPhy.EnableAsciiAll(osw);
390 AsciiTraceHelper ascii;
391 MobilityHelper::EnableAsciiAll(ascii.CreateFileStream(tr_name + ".mob"));
392
393 FlowMonitorHelper flowmonHelper;
394 Ptr<FlowMonitor> flowmon;
395 if (m_flowMonitor)
396 {
397 flowmon = flowmonHelper.InstallAll();
398 }
399
400 NS_LOG_INFO("Run Simulation.");
401
403
404 Simulator::Stop(Seconds(TotalTime));
406
407 if (m_flowMonitor)
408 {
409 flowmon->SerializeToXmlFile(tr_name + ".flowmon", false, false);
410 }
411
413}
Routing experiment class.
void Run()
Run the experiment.
void CommandSetup(int argc, char **argv)
Handles the command-line parameters.
bool m_flowMonitor
Enable FlowMonitor.
void CheckThroughput()
Compute the throughput.
uint32_t packetsReceived
Total received packets.
int m_nSinks
Number of sink nodes.
std::string m_protocolName
Protocol name.
void ReceivePacket(Ptr< Socket > socket)
Receive a packet.
uint32_t bytesTotal
Total received bytes.
std::string m_CSVfileName
CSV filename.
Ptr< Socket > SetupPacketReceive(Ipv4Address addr, Ptr< Node > node)
Setup the receiving socket in a Sink Node.
uint32_t port
Receiving port number.
bool m_traceMobility
Enable mobility tracing.
a polymophic address class
Definition address.h:90
Helper class that adds AODV routing to nodes.
Definition aodv-helper.h:25
holds a vector of ns3::Application pointers.
void Start(Time start) const
Start all of the Applications in this container at the start time given as a parameter.
void Stop(Time stop) const
Arrange for all of the Applications in this container to Stop() at the Time given as a parameter.
ApplicationContainer Install(NodeContainer c)
Install an application on each node of the input container configured with all the attributes set wit...
void SetAttribute(const std::string &name, const AttributeValue &value)
Helper function used to set the underlying application attributes.
Manage ASCII trace files for device models.
Ptr< OutputStreamWrapper > CreateFileStream(std::string filename, std::ios::openmode filemode=std::ios::out)
Create and initialize an output stream object we'll use to write the traced bits.
Parse command-line arguments.
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition double.h:31
Helper class that adds DSDV routing to nodes.
Definition dsdv-helper.h:36
DSR helper class to manage creation of DSR routing instance and to insert it on a node as a sublayer ...
Definition dsr-helper.h:42
Helper class that adds DSR routing to nodes.
void Install(DsrHelper &dsrHelper, NodeContainer nodes)
Install routing to the nodes.
Helper to enable IP flow monitoring on a set of Nodes.
Ptr< FlowMonitor > InstallAll()
Enable flow monitoring on all nodes.
an Inet address class
static bool IsMatchingType(const Address &address)
Ipv4Address GetIpv4() const
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
aggregate IP/TCP/UDP functionality to existing Nodes.
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
void SetBase(Ipv4Address network, Ipv4Mask mask, Ipv4Address base="0.0.0.1")
Set the base network number, network mask and base address.
Ipv4InterfaceContainer Assign(const NetDeviceContainer &c)
Assign IP addresses to the net devices specified in the container based on the current network prefix...
Ipv4 addresses are stored in host order in this class.
holds a vector of std::pair of Ptr<Ipv4> and interface index.
Ipv4Address GetAddress(uint32_t i, uint32_t j=0) const
Helper class that adds ns3::Ipv4ListRouting objects.
Helper class used to assign positions and mobility models to nodes.
int64_t AssignStreams(NodeContainer c, int64_t stream)
Assign a fixed random variable stream number to the random variables used by the mobility models on t...
static void EnableAsciiAll(Ptr< OutputStreamWrapper > stream)
void Install(Ptr< Node > node) const
"Layout" a single node according to the current position allocator type.
void SetMobilityModel(std::string type, Ts &&... args)
void SetPositionAllocator(Ptr< PositionAllocator > allocator)
Set the position allocator which will be used to allocate the initial position of every node initiali...
holds a vector of ns3::NetDevice pointers
keep track of a set of node pointers.
void Create(uint32_t n)
Create n nodes and append pointers to them to the end of this NodeContainer.
Ptr< Node > Get(uint32_t i) const
Get the Ptr<Node> stored in this container at a given index.
Instantiate subclasses of ns3::Object.
Ptr< Object > Create() const
Create an Object instance of the configured TypeId.
void Set(const std::string &name, const AttributeValue &value, Args &&... args)
Set an attribute to be set during construction.
void SetTypeId(TypeId tid)
Set the TypeId of the Objects to be created by this factory.
Ptr< T > GetObject() const
Get a pointer to the requested aggregated Object.
Definition object.h:511
Helper class that adds OLSR routing to nodes.
Definition olsr-helper.h:31
A helper to make it easier to instantiate an ns3::OnOffApplication on a set of nodes.
static void EnablePrinting()
Enable printing packets metadata.
Definition packet.cc:585
AttributeValue implementation for Pointer.
Allocate a set of positions.
Smart pointer class similar to boost::intrusive_ptr.
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition simulator.h:560
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition simulator.cc:131
static Time Now()
Return the current simulation virtual time.
Definition simulator.cc:197
static void Run()
Run the simulation.
Definition simulator.cc:167
static void Stop()
Tell the Simulator the calling event should be the last one executed.
Definition simulator.cc:175
static Ptr< Socket > CreateSocket(Ptr< Node > node, TypeId tid)
This method wraps the creation of sockets that is performed on a given node by a SocketFactory specif...
Definition socket.cc:61
Hold variables of type string.
Definition string.h:45
double GetSeconds() const
Get an approximation of the time stored in this instance in the indicated unit.
Definition nstime.h:392
a unique identifier for an interface.
Definition type-id.h:48
static TypeId LookupByName(std::string name)
Get a TypeId by name.
Definition type-id.cc:872
helps to create WifiNetDevice objects
create MAC layers for a ns3::WifiNetDevice.
void SetType(std::string type, Args &&... args)
void Set(std::string name, const AttributeValue &v)
manage and create wifi channel objects for the YANS model.
void SetPropagationDelay(std::string name, Ts &&... args)
void AddPropagationLoss(std::string name, Ts &&... args)
Ptr< YansWifiChannel > Create() const
Make it easy to create and manage PHY objects for the YANS model.
void SetChannel(Ptr< YansWifiChannel > channel)
void experiment(std::string queue_disc_type)
void SetDefault(std::string name, const AttributeValue &value)
Definition config.cc:883
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
#define NS_LOG_UNCOND(msg)
Output the requested message unconditionally.
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:191
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition log.h:264
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:619
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1308
@ WIFI_STANDARD_80211b
NodeContainer nodes
static std::string PrintReceivedPacket(Ptr< Socket > socket, Ptr< Packet > packet, Address senderAddress)
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Callback< R, Args... > MakeCallback(R(T::*memPtr)(Args...), OBJ objPtr)
Build Callbacks for class method members which take varying numbers of arguments and potentially retu...
Definition callback.h:684
Definition olsr.py:1
#define list
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition wifi-tcp.cc:44