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 http://wiki.ittc.ku.edu/resilinets
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
251void
252RoutingExperiment::Run (int nSinks, double txp, std::string CSVfileName)
253{
254 Packet::EnablePrinting ();
255 m_nSinks = nSinks;
256 m_txp = txp;
257 m_CSVfileName = CSVfileName;
258
259 int nWifis = 50;
260
261 double TotalTime = 200.0;
262 std::string rate ("2048bps");
263 std::string phyMode ("DsssRate11Mbps");
264 std::string tr_name ("manet-routing-compare");
265 int nodeSpeed = 20; //in m/s
266 int nodePause = 0; //in s
267 m_protocolName = "protocol";
268
269 Config::SetDefault ("ns3::OnOffApplication::PacketSize",StringValue ("64"));
270 Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue (rate));
271
272 //Set Non-unicastMode rate to unicast mode
273 Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode",StringValue (phyMode));
274
275 NodeContainer adhocNodes;
276 adhocNodes.Create (nWifis);
277
278 // setting up wifi phy and channel using helpers
280 wifi.SetStandard (WIFI_STANDARD_80211b);
281
282 YansWifiPhyHelper wifiPhy;
283 YansWifiChannelHelper wifiChannel;
284 wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
285 wifiChannel.AddPropagationLoss ("ns3::FriisPropagationLossModel");
286 wifiPhy.SetChannel (wifiChannel.Create ());
287
288 // Add a mac and disable rate control
289 WifiMacHelper wifiMac;
290 wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
291 "DataMode",StringValue (phyMode),
292 "ControlMode",StringValue (phyMode));
293
294 wifiPhy.Set ("TxPowerStart",DoubleValue (txp));
295 wifiPhy.Set ("TxPowerEnd", DoubleValue (txp));
296
297 wifiMac.SetType ("ns3::AdhocWifiMac");
298 NetDeviceContainer adhocDevices = wifi.Install (wifiPhy, wifiMac, adhocNodes);
299
300 MobilityHelper mobilityAdhoc;
301 [[maybe_unused]] int64_t streamIndex = 0; // used to get consistent mobility across scenarios
302
303 ObjectFactory pos;
304 pos.SetTypeId ("ns3::RandomRectanglePositionAllocator");
305 pos.Set ("X", StringValue ("ns3::UniformRandomVariable[Min=0.0|Max=300.0]"));
306 pos.Set ("Y", StringValue ("ns3::UniformRandomVariable[Min=0.0|Max=1500.0]"));
307
308 Ptr<PositionAllocator> taPositionAlloc = pos.Create ()->GetObject<PositionAllocator> ();
309 streamIndex += taPositionAlloc->AssignStreams (streamIndex);
310
311 std::stringstream ssSpeed;
312 ssSpeed << "ns3::UniformRandomVariable[Min=0.0|Max=" << nodeSpeed << "]";
313 std::stringstream ssPause;
314 ssPause << "ns3::ConstantRandomVariable[Constant=" << nodePause << "]";
315 mobilityAdhoc.SetMobilityModel ("ns3::RandomWaypointMobilityModel",
316 "Speed", StringValue (ssSpeed.str ()),
317 "Pause", StringValue (ssPause.str ()),
318 "PositionAllocator", PointerValue (taPositionAlloc));
319 mobilityAdhoc.SetPositionAllocator (taPositionAlloc);
320 mobilityAdhoc.Install (adhocNodes);
321 streamIndex += mobilityAdhoc.AssignStreams (adhocNodes, streamIndex);
322
323 AodvHelper aodv;
325 DsdvHelper dsdv;
326 DsrHelper dsr;
327 DsrMainHelper dsrMain;
329 InternetStackHelper internet;
330
331 switch (m_protocol)
332 {
333 case 1:
334 list.Add (olsr, 100);
335 m_protocolName = "OLSR";
336 break;
337 case 2:
338 list.Add (aodv, 100);
339 m_protocolName = "AODV";
340 break;
341 case 3:
342 list.Add (dsdv, 100);
343 m_protocolName = "DSDV";
344 break;
345 case 4:
346 m_protocolName = "DSR";
347 break;
348 default:
349 NS_FATAL_ERROR ("No such protocol:" << m_protocol);
350 }
351
352 if (m_protocol < 4)
353 {
354 internet.SetRoutingHelper (list);
355 internet.Install (adhocNodes);
356 }
357 else if (m_protocol == 4)
358 {
359 internet.Install (adhocNodes);
360 dsrMain.Install (dsr, adhocNodes);
361 }
362
363 NS_LOG_INFO ("assigning ip address");
364
365 Ipv4AddressHelper addressAdhoc;
366 addressAdhoc.SetBase ("10.1.1.0", "255.255.255.0");
367 Ipv4InterfaceContainer adhocInterfaces;
368 adhocInterfaces = addressAdhoc.Assign (adhocDevices);
369
370 OnOffHelper onoff1 ("ns3::UdpSocketFactory",Address ());
371 onoff1.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1.0]"));
372 onoff1.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0.0]"));
373
374 for (int i = 0; i < nSinks; i++)
375 {
376 Ptr<Socket> sink = SetupPacketReceive (adhocInterfaces.GetAddress (i), adhocNodes.Get (i));
377
378 AddressValue remoteAddress (InetSocketAddress (adhocInterfaces.GetAddress (i), port));
379 onoff1.SetAttribute ("Remote", remoteAddress);
380
381 Ptr<UniformRandomVariable> var = CreateObject<UniformRandomVariable> ();
382 ApplicationContainer temp = onoff1.Install (adhocNodes.Get (i + nSinks));
383 temp.Start (Seconds (var->GetValue (100.0,101.0)));
384 temp.Stop (Seconds (TotalTime));
385 }
386
387 std::stringstream ss;
388 ss << nWifis;
389 std::string nodes = ss.str ();
390
391 std::stringstream ss2;
392 ss2 << nodeSpeed;
393 std::string sNodeSpeed = ss2.str ();
394
395 std::stringstream ss3;
396 ss3 << nodePause;
397 std::string sNodePause = ss3.str ();
398
399 std::stringstream ss4;
400 ss4 << rate;
401 std::string sRate = ss4.str ();
402
403 //NS_LOG_INFO ("Configure Tracing.");
404 //tr_name = tr_name + "_" + m_protocolName +"_" + nodes + "nodes_" + sNodeSpeed + "speed_" + sNodePause + "pause_" + sRate + "rate";
405
406 //AsciiTraceHelper ascii;
407 //Ptr<OutputStreamWrapper> osw = ascii.CreateFileStream ( (tr_name + ".tr").c_str());
408 //wifiPhy.EnableAsciiAll (osw);
409 AsciiTraceHelper ascii;
410 MobilityHelper::EnableAsciiAll (ascii.CreateFileStream (tr_name + ".mob"));
411
412 //Ptr<FlowMonitor> flowmon;
413 //FlowMonitorHelper flowmonHelper;
414 //flowmon = flowmonHelper.InstallAll ();
415
416
417 NS_LOG_INFO ("Run Simulation.");
418
420
421 Simulator::Stop (Seconds (TotalTime));
422 Simulator::Run ();
423
424 //flowmon->SerializeToXmlFile ((tr_name + ".flowmon").c_str(), false, false);
425
426 Simulator::Destroy ();
427}
428
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.
void SetMobilityModel(std::string type, std::string n1="", const AttributeValue &v1=EmptyAttributeValue(), std::string n2="", const AttributeValue &v2=EmptyAttributeValue(), std::string n3="", const AttributeValue &v3=EmptyAttributeValue(), std::string n4="", const AttributeValue &v4=EmptyAttributeValue(), std::string n5="", const AttributeValue &v5=EmptyAttributeValue(), std::string n6="", const AttributeValue &v6=EmptyAttributeValue(), std::string n7="", const AttributeValue &v7=EmptyAttributeValue(), std::string n8="", const AttributeValue &v8=EmptyAttributeValue(), std::string n9="", const AttributeValue &v9=EmptyAttributeValue())
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 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:379
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:323
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:141
manage and create wifi channel objects for the YANS model.
void SetPropagationDelay(std::string name, std::string n0="", const AttributeValue &v0=EmptyAttributeValue(), std::string n1="", const AttributeValue &v1=EmptyAttributeValue(), std::string n2="", const AttributeValue &v2=EmptyAttributeValue(), std::string n3="", const AttributeValue &v3=EmptyAttributeValue(), std::string n4="", const AttributeValue &v4=EmptyAttributeValue(), std::string n5="", const AttributeValue &v5=EmptyAttributeValue(), std::string n6="", const AttributeValue &v6=EmptyAttributeValue(), std::string n7="", const AttributeValue &v7=EmptyAttributeValue())
Ptr< YansWifiChannel > Create(void) const
void AddPropagationLoss(std::string name, std::string n0="", const AttributeValue &v0=EmptyAttributeValue(), std::string n1="", const AttributeValue &v1=EmptyAttributeValue(), std::string n2="", const AttributeValue &v2=EmptyAttributeValue(), std::string n3="", const AttributeValue &v3=EmptyAttributeValue(), std::string n4="", const AttributeValue &v4=EmptyAttributeValue(), std::string n5="", const AttributeValue &v5=EmptyAttributeValue(), std::string n6="", const AttributeValue &v6=EmptyAttributeValue(), std::string n7="", const AttributeValue &v7=EmptyAttributeValue())
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:205
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:281
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:1244
@ WIFI_STANDARD_80211b
static std::string PrintReceivedPacket(Ptr< Socket > socket, Ptr< Packet > packet, Address senderAddress)
nodes
Definition: first.py:32
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Callback< R, Ts... > MakeCallback(R(T::*memPtr)(Ts...), OBJ objPtr)
Build Callbacks for class method members which take varying numbers of arguments and potentially retu...
Definition: callback.h:1648
Definition: olsr.py:1
cmd
Definition: second.py:35
wifi
Definition: third.py:99
#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:70
Ptr< PacketSink > sink
Definition: wifi-tcp.cc:56