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, DSR, 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 100 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 11 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, AODV is used, but specifying a string of 'OLSR', 'DSDV', or
38 * 'DSR' to the protocol command-line argument will change the protocol.
39 *
40 * By default, there are 10 source/sink data pairs sending UDP data
41 * at an application rate of 2.048 Kb/s each. This is typically done
42 * at a rate of 4 64-byte packets per second. Application data is
43 * started at a random time between 100 and 101 seconds and continues
44 * to the end of the simulation.
45 *
46 * The program outputs a few items:
47 * - packet receptions are notified to stdout such as:
48 * <timestamp> <node-id> received one packet from <src-address>
49 * - each second, the data reception statistics are tabulated and output
50 * to a comma-separated value (csv) file
51 * - mobility traces of the nodes are printed to 'manet-routing-compare.mob';
52 * this trace can be disabled using a command-line argument
53 * - some tracing and flow monitor configuration that used to work is
54 * left commented inline in the program
55 */
56
57#include "ns3/aodv-module.h"
58#include "ns3/applications-module.h"
59#include "ns3/core-module.h"
60#include "ns3/dsdv-module.h"
61#include "ns3/dsr-module.h"
62#include "ns3/flow-monitor-module.h"
63#include "ns3/internet-module.h"
64#include "ns3/mobility-module.h"
65#include "ns3/network-module.h"
66#include "ns3/olsr-module.h"
67#include "ns3/yans-wifi-helper.h"
68
69#include <fstream>
70#include <iostream>
71
72using namespace ns3;
73using namespace dsr;
74
75NS_LOG_COMPONENT_DEFINE("manet-routing-compare");
76
77/**
78 * Routing experiment class.
79 *
80 * It handles the creation and run of an experiment.
81 */
83{
84 public:
86 /**
87 * Run the experiment.
88 */
89 void Run();
90
91 /**
92 * Handles the command-line parameters.
93 * @param argc The argument count.
94 * @param argv The argument vector.
95 */
96 void CommandSetup(int argc, char** argv);
97
98 private:
99 /**
100 * Setup the receiving socket in a Sink Node.
101 * @param addr The address of the node.
102 * @param node The node pointer.
103 * @return the socket.
104 */
106 /**
107 * Receive a packet.
108 * @param socket The receiving socket.
109 */
110 void ReceivePacket(Ptr<Socket> socket);
111 /**
112 * Compute the throughput.
113 */
114 void CheckThroughput();
115
116 uint32_t port{9}; //!< Receiving port number.
117 uint32_t bytesTotal{0}; //!< Total received bytes.
118 uint32_t packetsReceived{0}; //!< Total received packets.
119
120 std::string m_CSVfileName{"manet-routing.output.csv"}; //!< CSV filename.
121 int m_nSinks{10}; //!< Number of sink nodes.
122 std::string m_protocolName{"AODV"}; //!< Protocol name.
123 double m_txp{7.5}; //!< Tx power.
124 bool m_traceMobility{true}; //!< Enable mobility tracing.
125 bool m_flowMonitor{false}; //!< Enable FlowMonitor.
126};
127
131
132static inline std::string
134{
135 std::ostringstream oss;
136
137 oss << Simulator::Now().GetSeconds() << " " << socket->GetNode()->GetId();
138
139 if (InetSocketAddress::IsMatchingType(senderAddress))
140 {
142 oss << " received one packet from " << addr.GetIpv4();
143 }
144 else
145 {
146 oss << " received one packet!";
147 }
148 return oss.str();
149}
150
151void
153{
154 Ptr<Packet> packet;
155 Address senderAddress;
156 while ((packet = socket->RecvFrom(senderAddress)))
157 {
158 bytesTotal += packet->GetSize();
159 packetsReceived += 1;
160 NS_LOG_UNCOND(PrintReceivedPacket(socket, packet, senderAddress));
161 }
162}
163
164void
166{
167 double kbs = (bytesTotal * 8.0) / 1000;
168 bytesTotal = 0;
169
170 std::ofstream out(m_CSVfileName, std::ios::app);
171
172 out << (Simulator::Now()).GetSeconds() << "," << kbs << "," << packetsReceived << ","
173 << m_nSinks << "," << m_protocolName << "," << m_txp << "" << std::endl;
174
175 out.close();
176 packetsReceived = 0;
178}
179
182{
183 TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory");
186 sink->Bind(local);
187 sink->SetRecvCallback(MakeCallback(&RoutingExperiment::ReceivePacket, this));
188
189 return sink;
190}
191
192void
194{
195 CommandLine cmd(__FILE__);
196 cmd.AddValue("CSVfileName", "The name of the CSV output file name", m_CSVfileName);
197 cmd.AddValue("traceMobility", "Enable mobility tracing", m_traceMobility);
198 cmd.AddValue("protocol", "Routing protocol (OLSR, AODV, DSDV, DSR)", m_protocolName);
199 cmd.AddValue("flowMonitor", "enable FlowMonitor", m_flowMonitor);
200 cmd.Parse(argc, argv);
201
202 std::vector<std::string> allowedProtocols{"OLSR", "AODV", "DSDV", "DSR"};
203
204 if (std::find(std::begin(allowedProtocols), std::end(allowedProtocols), m_protocolName) ==
205 std::end(allowedProtocols))
206 {
207 NS_FATAL_ERROR("No such protocol:" << m_protocolName);
208 }
209}
210
211int
212main(int argc, char* argv[])
213{
215 experiment.CommandSetup(argc, argv);
216 experiment.Run();
217
218 return 0;
219}
220
221void
223{
225
226 // blank out the last output file and write the column headers
227 std::ofstream out(m_CSVfileName);
228 out << "SimulationSecond,"
229 << "ReceiveRate,"
230 << "PacketsReceived,"
231 << "NumberOfSinks,"
232 << "RoutingProtocol,"
233 << "TransmissionPower" << std::endl;
234 out.close();
235
236 int nWifis = 50;
237
238 double TotalTime = 200.0;
239 std::string rate("2048bps");
240 std::string phyMode("DsssRate11Mbps");
241 std::string tr_name("manet-routing-compare");
242 int nodeSpeed = 20; // in m/s
243 int nodePause = 0; // in s
244
245 Config::SetDefault("ns3::OnOffApplication::PacketSize", StringValue("64"));
246 Config::SetDefault("ns3::OnOffApplication::DataRate", StringValue(rate));
247
248 // Set Non-unicastMode rate to unicast mode
249 Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue(phyMode));
250
251 NodeContainer adhocNodes;
252 adhocNodes.Create(nWifis);
253
254 // setting up wifi phy and channel using helpers
255 WifiHelper wifi;
256 wifi.SetStandard(WIFI_STANDARD_80211b);
257
258 YansWifiPhyHelper wifiPhy;
259 YansWifiChannelHelper wifiChannel;
260 wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
261 wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel");
262 wifiPhy.SetChannel(wifiChannel.Create());
263
264 // Add a mac and disable rate control
265 WifiMacHelper wifiMac;
266 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
267 "DataMode",
268 StringValue(phyMode),
269 "ControlMode",
270 StringValue(phyMode));
271
272 wifiPhy.Set("TxPowerStart", DoubleValue(m_txp));
273 wifiPhy.Set("TxPowerEnd", DoubleValue(m_txp));
274
275 wifiMac.SetType("ns3::AdhocWifiMac");
276 NetDeviceContainer adhocDevices = wifi.Install(wifiPhy, wifiMac, adhocNodes);
277
278 MobilityHelper mobilityAdhoc;
279 int64_t streamIndex = 0; // used to get consistent mobility across scenarios
280
281 ObjectFactory pos;
282 pos.SetTypeId("ns3::RandomRectanglePositionAllocator");
283 pos.Set("X", StringValue("ns3::UniformRandomVariable[Min=0.0|Max=300.0]"));
284 pos.Set("Y", StringValue("ns3::UniformRandomVariable[Min=0.0|Max=1500.0]"));
285
286 Ptr<PositionAllocator> taPositionAlloc = pos.Create()->GetObject<PositionAllocator>();
287 streamIndex += taPositionAlloc->AssignStreams(streamIndex);
288
289 std::stringstream ssSpeed;
290 ssSpeed << "ns3::UniformRandomVariable[Min=0.0|Max=" << nodeSpeed << "]";
291 std::stringstream ssPause;
292 ssPause << "ns3::ConstantRandomVariable[Constant=" << nodePause << "]";
293 mobilityAdhoc.SetMobilityModel("ns3::RandomWaypointMobilityModel",
294 "Speed",
295 StringValue(ssSpeed.str()),
296 "Pause",
297 StringValue(ssPause.str()),
298 "PositionAllocator",
299 PointerValue(taPositionAlloc));
300 mobilityAdhoc.SetPositionAllocator(taPositionAlloc);
301 mobilityAdhoc.Install(adhocNodes);
302 streamIndex += mobilityAdhoc.AssignStreams(adhocNodes, streamIndex);
303
304 AodvHelper aodv;
306 DsdvHelper dsdv;
307 DsrHelper dsr;
308 DsrMainHelper dsrMain;
310 InternetStackHelper internet;
311
312 if (m_protocolName == "OLSR")
313 {
314 list.Add(olsr, 100);
315 internet.SetRoutingHelper(list);
316 internet.Install(adhocNodes);
317 }
318 else if (m_protocolName == "AODV")
319 {
320 list.Add(aodv, 100);
321 internet.SetRoutingHelper(list);
322 internet.Install(adhocNodes);
323 }
324 else if (m_protocolName == "DSDV")
325 {
326 list.Add(dsdv, 100);
327 internet.SetRoutingHelper(list);
328 internet.Install(adhocNodes);
329 }
330 else if (m_protocolName == "DSR")
331 {
332 internet.Install(adhocNodes);
333 dsrMain.Install(dsr, adhocNodes);
334 if (m_flowMonitor)
335 {
336 NS_FATAL_ERROR("Error: FlowMonitor does not work with DSR. Terminating.");
337 }
338 }
339 else
340 {
341 NS_FATAL_ERROR("No such protocol:" << m_protocolName);
342 }
343
344 NS_LOG_INFO("assigning ip address");
345
346 Ipv4AddressHelper addressAdhoc;
347 addressAdhoc.SetBase("10.1.1.0", "255.255.255.0");
348 Ipv4InterfaceContainer adhocInterfaces;
349 adhocInterfaces = addressAdhoc.Assign(adhocDevices);
350
351 OnOffHelper onoff1("ns3::UdpSocketFactory", Address());
352 onoff1.SetAttribute("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=1.0]"));
353 onoff1.SetAttribute("OffTime", StringValue("ns3::ConstantRandomVariable[Constant=0.0]"));
354
355 for (int i = 0; i < m_nSinks; i++)
356 {
357 Ptr<Socket> sink = SetupPacketReceive(adhocInterfaces.GetAddress(i), adhocNodes.Get(i));
358
359 AddressValue remoteAddress(InetSocketAddress(adhocInterfaces.GetAddress(i), port));
360 onoff1.SetAttribute("Remote", remoteAddress);
361
363 ApplicationContainer temp = onoff1.Install(adhocNodes.Get(i + m_nSinks));
364 temp.Start(Seconds(var->GetValue(100.0, 101.0)));
365 temp.Stop(Seconds(TotalTime));
366 }
367
368 std::stringstream ss;
369 ss << nWifis;
370 std::string nodes = ss.str();
371
372 std::stringstream ss2;
373 ss2 << nodeSpeed;
374 std::string sNodeSpeed = ss2.str();
375
376 std::stringstream ss3;
377 ss3 << nodePause;
378 std::string sNodePause = ss3.str();
379
380 std::stringstream ss4;
381 ss4 << rate;
382 std::string sRate = ss4.str();
383
384 // NS_LOG_INFO("Configure Tracing.");
385 // tr_name = tr_name + "_" + m_protocolName +"_" + nodes + "nodes_" + sNodeSpeed + "speed_" +
386 // sNodePause + "pause_" + sRate + "rate";
387
388 // AsciiTraceHelper ascii;
389 // Ptr<OutputStreamWrapper> osw = ascii.CreateFileStream(tr_name + ".tr");
390 // wifiPhy.EnableAsciiAll(osw);
391 AsciiTraceHelper ascii;
392 if (m_traceMobility)
393 {
394 MobilityHelper::EnableAsciiAll(ascii.CreateFileStream(tr_name + ".mob"));
395 }
396
397 FlowMonitorHelper flowmonHelper;
398 Ptr<FlowMonitor> flowmon;
399 if (m_flowMonitor)
400 {
401 flowmon = flowmonHelper.InstallAll();
402 }
403
404 NS_LOG_INFO("Run Simulation.");
405
407
408 Simulator::Stop(Seconds(TotalTime));
410
411 if (m_flowMonitor)
412 {
413 flowmon->SerializeToXmlFile(tr_name + ".flowmon", false, false);
414 }
415
417}
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
AttributeValue implementation for Address.
Definition address.h:275
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:561
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:49
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:886
#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:1345
@ 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