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