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 
81 using namespace ns3;
82 using namespace dsr;
83 
84 NS_LOG_COMPONENT_DEFINE ("manet-routing-compare");
85 
87 {
88 public:
90  void Run (int nSinks, double txp, std::string CSVfileName);
91  //static void SetMACParam (ns3::NetDeviceContainer & devices,
92  // int slotDistance);
93  std::string CommandSetup (int argc, char **argv);
94 
95 private:
97  void ReceivePacket (Ptr<Socket> socket);
98  void CheckThroughput ();
99 
100  uint32_t port;
101  uint32_t bytesTotal;
102  uint32_t packetsReceived;
103 
104  std::string m_CSVfileName;
105  int m_nSinks;
106  std::string m_protocolName;
107  double m_txp;
109  uint32_t m_protocol;
110 };
111 
113  : port (9),
114  bytesTotal (0),
115  packetsReceived (0),
116  m_CSVfileName ("manet-routing.output.csv"),
117  m_traceMobility (false),
118  m_protocol (2) // AODV
119 {
120 }
121 
122 static inline std::string
123 PrintReceivedPacket (Ptr<Socket> socket, Ptr<Packet> packet, Address senderAddress)
124 {
125  std::ostringstream oss;
126 
127  oss << Simulator::Now ().GetSeconds () << " " << socket->GetNode ()->GetId ();
128 
129  if (InetSocketAddress::IsMatchingType (senderAddress))
130  {
131  InetSocketAddress addr = InetSocketAddress::ConvertFrom (senderAddress);
132  oss << " received one packet from " << addr.GetIpv4 ();
133  }
134  else
135  {
136  oss << " received one packet!";
137  }
138  return oss.str ();
139 }
140 
141 void
143 {
144  Ptr<Packet> packet;
145  Address senderAddress;
146  while ((packet = socket->RecvFrom (senderAddress)))
147  {
148  bytesTotal += packet->GetSize ();
149  packetsReceived += 1;
150  NS_LOG_UNCOND (PrintReceivedPacket (socket, packet, senderAddress));
151  }
152 }
153 
154 void
156 {
157  double kbs = (bytesTotal * 8.0) / 1000;
158  bytesTotal = 0;
159 
160  std::ofstream out (m_CSVfileName.c_str (), std::ios::app);
161 
162  out << (Simulator::Now ()).GetSeconds () << ","
163  << kbs << ","
164  << packetsReceived << ","
165  << m_nSinks << ","
166  << m_protocolName << ","
167  << m_txp << ""
168  << std::endl;
169 
170  out.close ();
171  packetsReceived = 0;
172  Simulator::Schedule (Seconds (1.0), &RoutingExperiment::CheckThroughput, this);
173 }
174 
177 {
178  TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
179  Ptr<Socket> sink = Socket::CreateSocket (node, tid);
180  InetSocketAddress local = InetSocketAddress (addr, port);
181  sink->Bind (local);
182  sink->SetRecvCallback (MakeCallback (&RoutingExperiment::ReceivePacket, this));
183 
184  return sink;
185 }
186 
187 std::string
188 RoutingExperiment::CommandSetup (int argc, char **argv)
189 {
190  CommandLine cmd (__FILE__);
191  cmd.AddValue ("CSVfileName", "The name of the CSV output file name", m_CSVfileName);
192  cmd.AddValue ("traceMobility", "Enable mobility tracing", m_traceMobility);
193  cmd.AddValue ("protocol", "1=OLSR;2=AODV;3=DSDV;4=DSR", m_protocol);
194  cmd.Parse (argc, argv);
195  return m_CSVfileName;
196 }
197 
198 int
199 main (int argc, char *argv[])
200 {
202  std::string CSVfileName = experiment.CommandSetup (argc,argv);
203 
204  //blank out the last output file and write the column headers
205  std::ofstream out (CSVfileName.c_str ());
206  out << "SimulationSecond," <<
207  "ReceiveRate," <<
208  "PacketsReceived," <<
209  "NumberOfSinks," <<
210  "RoutingProtocol," <<
211  "TransmissionPower" <<
212  std::endl;
213  out.close ();
214 
215  int nSinks = 10;
216  double txp = 7.5;
217 
218  experiment.Run (nSinks, txp, CSVfileName);
219 }
220 
221 void
222 RoutingExperiment::Run (int nSinks, double txp, std::string CSVfileName)
223 {
224  Packet::EnablePrinting ();
225  m_nSinks = nSinks;
226  m_txp = txp;
227  m_CSVfileName = CSVfileName;
228 
229  int nWifis = 50;
230 
231  double TotalTime = 200.0;
232  std::string rate ("2048bps");
233  std::string phyMode ("DsssRate11Mbps");
234  std::string tr_name ("manet-routing-compare");
235  int nodeSpeed = 20; //in m/s
236  int nodePause = 0; //in s
237  m_protocolName = "protocol";
238 
239  Config::SetDefault ("ns3::OnOffApplication::PacketSize",StringValue ("64"));
240  Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue (rate));
241 
242  //Set Non-unicastMode rate to unicast mode
243  Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode",StringValue (phyMode));
244 
245  NodeContainer adhocNodes;
246  adhocNodes.Create (nWifis);
247 
248  // setting up wifi phy and channel using helpers
250  wifi.SetStandard (WIFI_STANDARD_80211b);
251 
252  YansWifiPhyHelper wifiPhy;
253  YansWifiChannelHelper wifiChannel;
254  wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
255  wifiChannel.AddPropagationLoss ("ns3::FriisPropagationLossModel");
256  wifiPhy.SetChannel (wifiChannel.Create ());
257 
258  // Add a mac and disable rate control
259  WifiMacHelper wifiMac;
260  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
261  "DataMode",StringValue (phyMode),
262  "ControlMode",StringValue (phyMode));
263 
264  wifiPhy.Set ("TxPowerStart",DoubleValue (txp));
265  wifiPhy.Set ("TxPowerEnd", DoubleValue (txp));
266 
267  wifiMac.SetType ("ns3::AdhocWifiMac");
268  NetDeviceContainer adhocDevices = wifi.Install (wifiPhy, wifiMac, adhocNodes);
269 
270  MobilityHelper mobilityAdhoc;
271  int64_t streamIndex = 0; // used to get consistent mobility across scenarios
272 
273  ObjectFactory pos;
274  pos.SetTypeId ("ns3::RandomRectanglePositionAllocator");
275  pos.Set ("X", StringValue ("ns3::UniformRandomVariable[Min=0.0|Max=300.0]"));
276  pos.Set ("Y", StringValue ("ns3::UniformRandomVariable[Min=0.0|Max=1500.0]"));
277 
278  Ptr<PositionAllocator> taPositionAlloc = pos.Create ()->GetObject<PositionAllocator> ();
279  streamIndex += taPositionAlloc->AssignStreams (streamIndex);
280 
281  std::stringstream ssSpeed;
282  ssSpeed << "ns3::UniformRandomVariable[Min=0.0|Max=" << nodeSpeed << "]";
283  std::stringstream ssPause;
284  ssPause << "ns3::ConstantRandomVariable[Constant=" << nodePause << "]";
285  mobilityAdhoc.SetMobilityModel ("ns3::RandomWaypointMobilityModel",
286  "Speed", StringValue (ssSpeed.str ()),
287  "Pause", StringValue (ssPause.str ()),
288  "PositionAllocator", PointerValue (taPositionAlloc));
289  mobilityAdhoc.SetPositionAllocator (taPositionAlloc);
290  mobilityAdhoc.Install (adhocNodes);
291  streamIndex += mobilityAdhoc.AssignStreams (adhocNodes, streamIndex);
292  NS_UNUSED (streamIndex); // From this point, streamIndex is unused
293 
294  AodvHelper aodv;
296  DsdvHelper dsdv;
297  DsrHelper dsr;
298  DsrMainHelper dsrMain;
300  InternetStackHelper internet;
301 
302  switch (m_protocol)
303  {
304  case 1:
305  list.Add (olsr, 100);
306  m_protocolName = "OLSR";
307  break;
308  case 2:
309  list.Add (aodv, 100);
310  m_protocolName = "AODV";
311  break;
312  case 3:
313  list.Add (dsdv, 100);
314  m_protocolName = "DSDV";
315  break;
316  case 4:
317  m_protocolName = "DSR";
318  break;
319  default:
320  NS_FATAL_ERROR ("No such protocol:" << m_protocol);
321  }
322 
323  if (m_protocol < 4)
324  {
325  internet.SetRoutingHelper (list);
326  internet.Install (adhocNodes);
327  }
328  else if (m_protocol == 4)
329  {
330  internet.Install (adhocNodes);
331  dsrMain.Install (dsr, adhocNodes);
332  }
333 
334  NS_LOG_INFO ("assigning ip address");
335 
336  Ipv4AddressHelper addressAdhoc;
337  addressAdhoc.SetBase ("10.1.1.0", "255.255.255.0");
338  Ipv4InterfaceContainer adhocInterfaces;
339  adhocInterfaces = addressAdhoc.Assign (adhocDevices);
340 
341  OnOffHelper onoff1 ("ns3::UdpSocketFactory",Address ());
342  onoff1.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1.0]"));
343  onoff1.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0.0]"));
344 
345  for (int i = 0; i < nSinks; i++)
346  {
347  Ptr<Socket> sink = SetupPacketReceive (adhocInterfaces.GetAddress (i), adhocNodes.Get (i));
348 
349  AddressValue remoteAddress (InetSocketAddress (adhocInterfaces.GetAddress (i), port));
350  onoff1.SetAttribute ("Remote", remoteAddress);
351 
352  Ptr<UniformRandomVariable> var = CreateObject<UniformRandomVariable> ();
353  ApplicationContainer temp = onoff1.Install (adhocNodes.Get (i + nSinks));
354  temp.Start (Seconds (var->GetValue (100.0,101.0)));
355  temp.Stop (Seconds (TotalTime));
356  }
357 
358  std::stringstream ss;
359  ss << nWifis;
360  std::string nodes = ss.str ();
361 
362  std::stringstream ss2;
363  ss2 << nodeSpeed;
364  std::string sNodeSpeed = ss2.str ();
365 
366  std::stringstream ss3;
367  ss3 << nodePause;
368  std::string sNodePause = ss3.str ();
369 
370  std::stringstream ss4;
371  ss4 << rate;
372  std::string sRate = ss4.str ();
373 
374  //NS_LOG_INFO ("Configure Tracing.");
375  //tr_name = tr_name + "_" + m_protocolName +"_" + nodes + "nodes_" + sNodeSpeed + "speed_" + sNodePause + "pause_" + sRate + "rate";
376 
377  //AsciiTraceHelper ascii;
378  //Ptr<OutputStreamWrapper> osw = ascii.CreateFileStream ( (tr_name + ".tr").c_str());
379  //wifiPhy.EnableAsciiAll (osw);
380  AsciiTraceHelper ascii;
381  MobilityHelper::EnableAsciiAll (ascii.CreateFileStream (tr_name + ".mob"));
382 
383  //Ptr<FlowMonitor> flowmon;
384  //FlowMonitorHelper flowmonHelper;
385  //flowmon = flowmonHelper.InstallAll ();
386 
387 
388  NS_LOG_INFO ("Run Simulation.");
389 
390  CheckThroughput ();
391 
392  Simulator::Stop (Seconds (TotalTime));
393  Simulator::Run ();
394 
395  //flowmon->SerializeToXmlFile ((tr_name + ".flowmon").c_str(), false, false);
396 
397  Simulator::Destroy ();
398 }
399 
Ptr< Socket > SetupPacketReceive(Ptr< Node > node)
void Run(int nSinks, double txp, std::string CSVfileName)
std::string CommandSetup(int argc, char **argv)
void ReceivePacket(Ptr< Socket > socket)
Ptr< Socket > SetupPacketReceive(Ipv4Address addr, Ptr< Node > node)
a polymophic address class
Definition: address.h:91
AttributeValue implementation for Address.
Definition: address.h:278
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< Node > GetNode(void) const =0
Return the node this socket is associated with.
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.
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:274
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:154
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 ReceivePacket(Ptr< Socket > socket)
void SetDefault(std::string name, const AttributeValue &value)
Definition: config.cc:849
#define NS_UNUSED(x)
Mark a local variable as unused.
Definition: unused.h:51
#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:96
#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