A Discrete-Event Network Simulator
API
manet-routing-compare.cc
Go to the documentation of this file.
1/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
2/*
3 * Copyright (c) 2011 University of Kansas
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation;
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 * Author: Justin Rohrer <rohrej@ittc.ku.edu>
19 *
20 * James P.G. Sterbenz <jpgs@ittc.ku.edu>, director
21 * ResiliNets Research Group https://resilinets.org/
22 * Information and Telecommunication Technology Center (ITTC)
23 * and Department of Electrical Engineering and Computer Science
24 * The University of Kansas Lawrence, KS USA.
25 *
26 * Work supported in part by NSF FIND (Future Internet Design) Program
27 * under grant CNS-0626918 (Postmodern Internet Architecture),
28 * NSF grant CNS-1050226 (Multilayer Network Resilience Analysis and Experimentation on GENI),
29 * US Department of Defense (DoD), and ITTC at The University of Kansas.
30 */
31
32/*
33 * This example program allows one to run ns-3 DSDV, AODV, or OLSR under
34 * a typical random waypoint mobility model.
35 *
36 * By default, the simulation runs for 200 simulated seconds, of which
37 * the first 50 are used for start-up time. The number of nodes is 50.
38 * Nodes move according to RandomWaypointMobilityModel with a speed of
39 * 20 m/s and no pause time within a 300x1500 m region. The WiFi is
40 * in ad hoc mode with a 2 Mb/s rate (802.11b) and a Friis loss model.
41 * The transmit power is set to 7.5 dBm.
42 *
43 * It is possible to change the mobility and density of the network by
44 * directly modifying the speed and the number of nodes. It is also
45 * possible to change the characteristics of the network by changing
46 * the transmit power (as power increases, the impact of mobility
47 * decreases and the effective density increases).
48 *
49 * By default, OLSR is used, but specifying a value of 2 for the protocol
50 * will cause AODV to be used, and specifying a value of 3 will cause
51 * DSDV to be used.
52 *
53 * By default, there are 10 source/sink data pairs sending UDP data
54 * at an application rate of 2.048 Kb/s each. This is typically done
55 * at a rate of 4 64-byte packets per second. Application data is
56 * started at a random time between 50 and 51 seconds and continues
57 * to the end of the simulation.
58 *
59 * The program outputs a few items:
60 * - packet receptions are notified to stdout such as:
61 * <timestamp> <node-id> received one packet from <src-address>
62 * - each second, the data reception statistics are tabulated and output
63 * to a comma-separated value (csv) file
64 * - some tracing and flow monitor configuration that used to work is
65 * left commented inline in the program
66 */
67
68#include <fstream>
69#include <iostream>
70#include "ns3/core-module.h"
71#include "ns3/network-module.h"
72#include "ns3/internet-module.h"
73#include "ns3/mobility-module.h"
74#include "ns3/aodv-module.h"
75#include "ns3/olsr-module.h"
76#include "ns3/dsdv-module.h"
77#include "ns3/dsr-module.h"
78#include "ns3/applications-module.h"
79#include "ns3/yans-wifi-helper.h"
80
81using namespace ns3;
82using namespace dsr;
83
84NS_LOG_COMPONENT_DEFINE ("manet-routing-compare");
85
92{
93public:
101 void Run (int nSinks, double txp, std::string CSVfileName);
102 //static void SetMACParam (ns3::NetDeviceContainer & devices,
103 // int slotDistance);
110 std::string CommandSetup (int argc, char **argv);
111
112private:
124 void ReceivePacket (Ptr<Socket> socket);
128 void CheckThroughput ();
129
133
134 std::string m_CSVfileName;
136 std::string m_protocolName;
137 double m_txp;
140};
141
143 : port (9),
144 bytesTotal (0),
145 packetsReceived (0),
146 m_CSVfileName ("manet-routing.output.csv"),
147 m_traceMobility (false),
148 m_protocol (2) // AODV
149{
150}
151
152static inline std::string
153PrintReceivedPacket (Ptr<Socket> socket, Ptr<Packet> packet, Address senderAddress)
154{
155 std::ostringstream oss;
156
157 oss << Simulator::Now ().GetSeconds () << " " << socket->GetNode ()->GetId ();
158
159 if (InetSocketAddress::IsMatchingType (senderAddress))
160 {
161 InetSocketAddress addr = InetSocketAddress::ConvertFrom (senderAddress);
162 oss << " received one packet from " << addr.GetIpv4 ();
163 }
164 else
165 {
166 oss << " received one packet!";
167 }
168 return oss.str ();
169}
170
171void
173{
174 Ptr<Packet> packet;
175 Address senderAddress;
176 while ((packet = socket->RecvFrom (senderAddress)))
177 {
178 bytesTotal += packet->GetSize ();
179 packetsReceived += 1;
180 NS_LOG_UNCOND (PrintReceivedPacket (socket, packet, senderAddress));
181 }
182}
183
184void
186{
187 double kbs = (bytesTotal * 8.0) / 1000;
188 bytesTotal = 0;
189
190 std::ofstream out (m_CSVfileName.c_str (), std::ios::app);
191
192 out << (Simulator::Now ()).GetSeconds () << ","
193 << kbs << ","
194 << packetsReceived << ","
195 << m_nSinks << ","
196 << m_protocolName << ","
197 << m_txp << ""
198 << std::endl;
199
200 out.close ();
201 packetsReceived = 0;
202 Simulator::Schedule (Seconds (1.0), &RoutingExperiment::CheckThroughput, this);
203}
204
207{
208 TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
209 Ptr<Socket> sink = Socket::CreateSocket (node, tid);
211 sink->Bind (local);
212 sink->SetRecvCallback (MakeCallback (&RoutingExperiment::ReceivePacket, this));
213
214 return sink;
215}
216
217std::string
218RoutingExperiment::CommandSetup (int argc, char **argv)
219{
220 CommandLine cmd (__FILE__);
221 cmd.AddValue ("CSVfileName", "The name of the CSV output file name", m_CSVfileName);
222 cmd.AddValue ("traceMobility", "Enable mobility tracing", m_traceMobility);
223 cmd.AddValue ("protocol", "1=OLSR;2=AODV;3=DSDV;4=DSR", m_protocol);
224 cmd.Parse (argc, argv);
225 return m_CSVfileName;
226}
227
228int
229main (int argc, char *argv[])
230{
232 std::string CSVfileName = experiment.CommandSetup (argc,argv);
233
234 //blank out the last output file and write the column headers
235 std::ofstream out (CSVfileName.c_str ());
236 out << "SimulationSecond," <<
237 "ReceiveRate," <<
238 "PacketsReceived," <<
239 "NumberOfSinks," <<
240 "RoutingProtocol," <<
241 "TransmissionPower" <<
242 std::endl;
243 out.close ();
244
245 int nSinks = 10;
246 double txp = 7.5;
247
248 experiment.Run (nSinks, txp, CSVfileName);
249
250 return 0;
251}
252
253void
254RoutingExperiment::Run (int nSinks, double txp, std::string CSVfileName)
255{
256 Packet::EnablePrinting ();
257 m_nSinks = nSinks;
258 m_txp = txp;
259 m_CSVfileName = CSVfileName;
260
261 int nWifis = 50;
262
263 double TotalTime = 200.0;
264 std::string rate ("2048bps");
265 std::string phyMode ("DsssRate11Mbps");
266 std::string tr_name ("manet-routing-compare");
267 int nodeSpeed = 20; //in m/s
268 int nodePause = 0; //in s
269 m_protocolName = "protocol";
270
271 Config::SetDefault ("ns3::OnOffApplication::PacketSize",StringValue ("64"));
272 Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue (rate));
273
274 //Set Non-unicastMode rate to unicast mode
275 Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode",StringValue (phyMode));
276
277 NodeContainer adhocNodes;
278 adhocNodes.Create (nWifis);
279
280 // setting up wifi phy and channel using helpers
282 wifi.SetStandard (WIFI_STANDARD_80211b);
283
284 YansWifiPhyHelper wifiPhy;
285 YansWifiChannelHelper wifiChannel;
286 wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
287 wifiChannel.AddPropagationLoss ("ns3::FriisPropagationLossModel");
288 wifiPhy.SetChannel (wifiChannel.Create ());
289
290 // Add a mac and disable rate control
291 WifiMacHelper wifiMac;
292 wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
293 "DataMode",StringValue (phyMode),
294 "ControlMode",StringValue (phyMode));
295
296 wifiPhy.Set ("TxPowerStart",DoubleValue (txp));
297 wifiPhy.Set ("TxPowerEnd", DoubleValue (txp));
298
299 wifiMac.SetType ("ns3::AdhocWifiMac");
300 NetDeviceContainer adhocDevices = wifi.Install (wifiPhy, wifiMac, adhocNodes);
301
302 MobilityHelper mobilityAdhoc;
303 [[maybe_unused]] int64_t streamIndex = 0; // used to get consistent mobility across scenarios
304
305 ObjectFactory pos;
306 pos.SetTypeId ("ns3::RandomRectanglePositionAllocator");
307 pos.Set ("X", StringValue ("ns3::UniformRandomVariable[Min=0.0|Max=300.0]"));
308 pos.Set ("Y", StringValue ("ns3::UniformRandomVariable[Min=0.0|Max=1500.0]"));
309
310 Ptr<PositionAllocator> taPositionAlloc = pos.Create ()->GetObject<PositionAllocator> ();
311 streamIndex += taPositionAlloc->AssignStreams (streamIndex);
312
313 std::stringstream ssSpeed;
314 ssSpeed << "ns3::UniformRandomVariable[Min=0.0|Max=" << nodeSpeed << "]";
315 std::stringstream ssPause;
316 ssPause << "ns3::ConstantRandomVariable[Constant=" << nodePause << "]";
317 mobilityAdhoc.SetMobilityModel ("ns3::RandomWaypointMobilityModel",
318 "Speed", StringValue (ssSpeed.str ()),
319 "Pause", StringValue (ssPause.str ()),
320 "PositionAllocator", PointerValue (taPositionAlloc));
321 mobilityAdhoc.SetPositionAllocator (taPositionAlloc);
322 mobilityAdhoc.Install (adhocNodes);
323 streamIndex += mobilityAdhoc.AssignStreams (adhocNodes, streamIndex);
324
325 AodvHelper aodv;
327 DsdvHelper dsdv;
328 DsrHelper dsr;
329 DsrMainHelper dsrMain;
331 InternetStackHelper internet;
332
333 switch (m_protocol)
334 {
335 case 1:
336 list.Add (olsr, 100);
337 m_protocolName = "OLSR";
338 break;
339 case 2:
340 list.Add (aodv, 100);
341 m_protocolName = "AODV";
342 break;
343 case 3:
344 list.Add (dsdv, 100);
345 m_protocolName = "DSDV";
346 break;
347 case 4:
348 m_protocolName = "DSR";
349 break;
350 default:
351 NS_FATAL_ERROR ("No such protocol:" << m_protocol);
352 }
353
354 if (m_protocol < 4)
355 {
356 internet.SetRoutingHelper (list);
357 internet.Install (adhocNodes);
358 }
359 else if (m_protocol == 4)
360 {
361 internet.Install (adhocNodes);
362 dsrMain.Install (dsr, adhocNodes);
363 }
364
365 NS_LOG_INFO ("assigning ip address");
366
367 Ipv4AddressHelper addressAdhoc;
368 addressAdhoc.SetBase ("10.1.1.0", "255.255.255.0");
369 Ipv4InterfaceContainer adhocInterfaces;
370 adhocInterfaces = addressAdhoc.Assign (adhocDevices);
371
372 OnOffHelper onoff1 ("ns3::UdpSocketFactory",Address ());
373 onoff1.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1.0]"));
374 onoff1.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0.0]"));
375
376 for (int i = 0; i < nSinks; i++)
377 {
378 Ptr<Socket> sink = SetupPacketReceive (adhocInterfaces.GetAddress (i), adhocNodes.Get (i));
379
380 AddressValue remoteAddress (InetSocketAddress (adhocInterfaces.GetAddress (i), port));
381 onoff1.SetAttribute ("Remote", remoteAddress);
382
383 Ptr<UniformRandomVariable> var = CreateObject<UniformRandomVariable> ();
384 ApplicationContainer temp = onoff1.Install (adhocNodes.Get (i + nSinks));
385 temp.Start (Seconds (var->GetValue (100.0,101.0)));
386 temp.Stop (Seconds (TotalTime));
387 }
388
389 std::stringstream ss;
390 ss << nWifis;
391 std::string nodes = ss.str ();
392
393 std::stringstream ss2;
394 ss2 << nodeSpeed;
395 std::string sNodeSpeed = ss2.str ();
396
397 std::stringstream ss3;
398 ss3 << nodePause;
399 std::string sNodePause = ss3.str ();
400
401 std::stringstream ss4;
402 ss4 << rate;
403 std::string sRate = ss4.str ();
404
405 //NS_LOG_INFO ("Configure Tracing.");
406 //tr_name = tr_name + "_" + m_protocolName +"_" + nodes + "nodes_" + sNodeSpeed + "speed_" + sNodePause + "pause_" + sRate + "rate";
407
408 //AsciiTraceHelper ascii;
409 //Ptr<OutputStreamWrapper> osw = ascii.CreateFileStream ( (tr_name + ".tr").c_str());
410 //wifiPhy.EnableAsciiAll (osw);
411 AsciiTraceHelper ascii;
412 MobilityHelper::EnableAsciiAll (ascii.CreateFileStream (tr_name + ".mob"));
413
414 //Ptr<FlowMonitor> flowmon;
415 //FlowMonitorHelper flowmonHelper;
416 //flowmon = flowmonHelper.InstallAll ();
417
418
419 NS_LOG_INFO ("Run Simulation.");
420
422
423 Simulator::Stop (Seconds (TotalTime));
425
426 //flowmon->SerializeToXmlFile ((tr_name + ".flowmon").c_str(), false, false);
427
428 Simulator::Destroy ();
429}
430
void Run(ObjectFactory &factory, uint32_t pop, uint32_t total, uint32_t runs, Ptr< RandomVariableStream > eventStream, bool calRev)
Perform the runs for a single scheduler type.
Routing experiment class.
uint32_t m_protocol
Protocol type.
void CheckThroughput()
Compute the throughput.
void Run(int nSinks, double txp, std::string CSVfileName)
Run the experiment.
uint32_t packetsReceived
Total received packets.
std::string CommandSetup(int argc, char **argv)
Handles the command-line parmeters.
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
Enavle mobility tracing.
a polymophic address class
Definition: address.h:91
AttributeValue implementation for Address.
Helper class that adds AODV routing to nodes.
Definition: aodv-helper.h:35
holds a vector of ns3::Application pointers.
void Start(Time start)
Arrange for all of the Applications in this container to Start() at the Time given as a parameter.
void Stop(Time stop)
Arrange for all of the Applications in this container to Stop() at the Time given as a parameter.
Manage ASCII trace files for device models.
Definition: trace-helper.h:163
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.
Definition: command-line.h:229
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition: double.h:41
Helper class that adds DSDV routing to nodes.
Definition: dsdv-helper.h:46
DSR helper class to manage creation of DSR routing instance and to insert it on a node as a sublayer ...
Definition: dsr-helper.h:53
Helper class that adds DSR routing to nodes.
void Install(DsrHelper &dsrHelper, NodeContainer nodes)
Install routing to the nodes.
an Inet address class
Ipv4Address GetIpv4(void) const
aggregate IP/TCP/UDP functionality to existing Nodes.
void Install(std::string nodeName) const
Aggregate implementations of the ns3::Ipv4, ns3::Ipv6, ns3::Udp, and ns3::Tcp classes onto the provid...
void SetRoutingHelper(const Ipv4RoutingHelper &routing)
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.
Definition: ipv4-address.h:41
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...
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.
uint32_t GetId(void) const
Definition: node.cc:109
Instantiate subclasses of ns3::Object.
void Set(const std::string &name, const AttributeValue &value, Args &&... args)
Set an attribute to be set during construction.
Ptr< Object > Create(void) const
Create an Object instance of the configured TypeId.
void SetTypeId(TypeId tid)
Set the TypeId of the Objects to be created by this factory.
Ptr< T > GetObject(void) const
Get a pointer to the requested aggregated Object.
Definition: object.h:470
Helper class that adds OLSR routing to nodes.
Definition: olsr-helper.h:41
A helper to make it easier to instantiate an ns3::OnOffApplication on a set of nodes.
Definition: on-off-helper.h:43
ApplicationContainer Install(NodeContainer c) const
Install an ns3::OnOffApplication on each node of the input container configured with all the attribut...
void SetAttribute(std::string name, const AttributeValue &value)
Helper function used to set the underlying application attributes.
uint32_t GetSize(void) const
Returns the the size in bytes of the packet (including the zero-filled initial payload).
Definition: packet.h:856
Hold objects of type Ptr<T>.
Definition: pointer.h:37
Allocate a set of positions.
virtual Ptr< Packet > RecvFrom(uint32_t maxSize, uint32_t flags, Address &fromAddress)=0
Read a single packet from the socket and retrieve the sender address.
virtual Ptr< Node > GetNode(void) const =0
Return the node this socket is associated with.
Hold variables of type string.
Definition: string.h:41
double GetSeconds(void) const
Get an approximation of the time stored in this instance in the indicated unit.
Definition: nstime.h:380
a unique identifier for an interface.
Definition: type-id.h:59
double GetValue(double min, double max)
Get the next random value, as a double in the specified range .
helps to create WifiNetDevice objects
Definition: wifi-helper.h:322
create MAC layers for a ns3::WifiNetDevice.
void SetType(std::string type, Args &&... args)
void Set(std::string name, const AttributeValue &v)
Definition: wifi-helper.cc:162
manage and create wifi channel objects for the YANS model.
Ptr< YansWifiChannel > Create(void) const
void SetPropagationDelay(std::string name, Ts &&... args)
void AddPropagationLoss(std::string name, Ts &&... args)
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)
uint16_t port
Definition: dsdv-manet.cc:45
void SetDefault(std::string name, const AttributeValue &value)
Definition: config.cc:849
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
Definition: fatal-error.h:165
#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:206
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:282
Time Now(void)
create an ns3::Time instance which contains the current simulation time.
Definition: simulator.cc:287
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1245
@ 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:661
Definition: olsr.py:1
cmd
Definition: second.py:43
wifi
Definition: third.py:90
#define list
std::map< Mac48Address, uint64_t > packetsReceived
Map that stores the total packets received per STA (and addressed to that STA)
Definition: wifi-bianchi.cc:71
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition: wifi-tcp.cc:56