A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
dsdv-manet.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2010 Hemanth Narra
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Hemanth Narra <hemanth@ittc.ku.com>
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#include "ns3/applications-module.h"
21#include "ns3/core-module.h"
22#include "ns3/dsdv-helper.h"
23#include "ns3/internet-module.h"
24#include "ns3/mobility-module.h"
25#include "ns3/network-module.h"
26#include "ns3/yans-wifi-helper.h"
27
28#include <cmath>
29#include <iostream>
30
31using namespace ns3;
32
33uint16_t port = 9;
34
35NS_LOG_COMPONENT_DEFINE("DsdvManetExample");
36
37/**
38 * \defgroup dsdv-examples DSDV Examples
39 * \ingroup dsdv
40 * \ingroup examples
41 */
42
43/**
44 * \ingroup dsdv-examples
45 *
46 * \brief DSDV Manet example
47 */
49{
50 public:
52 /**
53 * Run function
54 * \param nWifis The total number of nodes
55 * \param nSinks The total number of receivers
56 * \param totalTime The total simulation time
57 * \param rate The network speed
58 * \param phyMode The physical mode
59 * \param nodeSpeed The node speed
60 * \param periodicUpdateInterval The routing update interval
61 * \param settlingTime The routing update settling time
62 * \param dataStart The data transmission start time
63 * \param printRoutes print the routes if true
64 * \param CSVfileName The CSV file name
65 */
66 void CaseRun(uint32_t nWifis,
67 uint32_t nSinks,
68 double totalTime,
69 std::string rate,
70 std::string phyMode,
71 uint32_t nodeSpeed,
72 uint32_t periodicUpdateInterval,
73 uint32_t settlingTime,
74 double dataStart,
75 bool printRoutes,
76 std::string CSVfileName);
77
78 private:
79 uint32_t m_nWifis; ///< total number of nodes
80 uint32_t m_nSinks; ///< number of receiver nodes
81 double m_totalTime; ///< total simulation time (in seconds)
82 std::string m_rate; ///< network bandwidth
83 std::string m_phyMode; ///< remote station manager data mode
84 uint32_t m_nodeSpeed; ///< mobility speed
85 uint32_t m_periodicUpdateInterval; ///< routing update interval
86 uint32_t m_settlingTime; ///< routing setting time
87 double m_dataStart; ///< time to start data transmissions (seconds)
88 uint32_t bytesTotal; ///< total bytes received by all nodes
89 uint32_t packetsReceived; ///< total packets received by all nodes
90 bool m_printRoutes; ///< print routing table
91 std::string m_CSVfileName; ///< CSV file name
92
93 NodeContainer nodes; ///< the collection of nodes
94 NetDeviceContainer devices; ///< the collection of devices
95 Ipv4InterfaceContainer interfaces; ///< the collection of interfaces
96
97 private:
98 /// Create and initialize all nodes
99 void CreateNodes();
100 /**
101 * Create and initialize all devices
102 * \param tr_name The trace file name
103 */
104 void CreateDevices(std::string tr_name);
105 /**
106 * Create network
107 * \param tr_name The trace file name
108 */
109 void InstallInternetStack(std::string tr_name);
110 /// Create data sinks and sources
111 void InstallApplications();
112 /// Setup mobility model
113 void SetupMobility();
114 /**
115 * Packet receive function
116 * \param socket The communication socket
117 */
118 void ReceivePacket(Ptr<Socket> socket);
119 /**
120 * Setup packet receivers
121 * \param addr the receiving IPv4 address
122 * \param node the receiving node
123 * \returns the communication socket
124 */
126 /// Check network throughput
127 void CheckThroughput();
128};
129
130int
131main(int argc, char** argv)
132{
134 uint32_t nWifis = 30;
135 uint32_t nSinks = 10;
136 double totalTime = 100.0;
137 std::string rate("8kbps");
138 std::string phyMode("DsssRate11Mbps");
139 uint32_t nodeSpeed = 10; // in m/s
140 std::string appl = "all";
141 uint32_t periodicUpdateInterval = 15;
142 uint32_t settlingTime = 6;
143 double dataStart = 50.0;
144 bool printRoutingTable = true;
145 std::string CSVfileName = "DsdvManetExample.csv";
146
147 CommandLine cmd(__FILE__);
148 cmd.AddValue("nWifis", "Number of wifi nodes[Default:30]", nWifis);
149 cmd.AddValue("nSinks", "Number of wifi sink nodes[Default:10]", nSinks);
150 cmd.AddValue("totalTime", "Total Simulation time[Default:100]", totalTime);
151 cmd.AddValue("phyMode", "Wifi Phy mode[Default:DsssRate11Mbps]", phyMode);
152 cmd.AddValue("rate", "CBR traffic rate[Default:8kbps]", rate);
153 cmd.AddValue("nodeSpeed", "Node speed in RandomWayPoint model[Default:10]", nodeSpeed);
154 cmd.AddValue("periodicUpdateInterval",
155 "Periodic Interval Time[Default=15]",
156 periodicUpdateInterval);
157 cmd.AddValue("settlingTime",
158 "Settling Time before sending out an update for changed metric[Default=6]",
159 settlingTime);
160 cmd.AddValue("dataStart",
161 "Time at which nodes start to transmit data[Default=50.0]",
162 dataStart);
163 cmd.AddValue("printRoutingTable",
164 "print routing table for nodes[Default:1]",
165 printRoutingTable);
166 cmd.AddValue("CSVfileName",
167 "The name of the CSV output file name[Default:DsdvManetExample.csv]",
168 CSVfileName);
169 cmd.Parse(argc, argv);
170
171 std::ofstream out(CSVfileName);
172 out << "SimulationSecond,"
173 << "ReceiveRate,"
174 << "PacketsReceived,"
175 << "NumberOfSinks," << std::endl;
176 out.close();
177
179
180 Config::SetDefault("ns3::OnOffApplication::PacketSize", StringValue("1000"));
181 Config::SetDefault("ns3::OnOffApplication::DataRate", StringValue(rate));
182 Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue(phyMode));
183 Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue("2000"));
184
186 test.CaseRun(nWifis,
187 nSinks,
188 totalTime,
189 rate,
190 phyMode,
191 nodeSpeed,
192 periodicUpdateInterval,
193 settlingTime,
194 dataStart,
195 printRoutingTable,
196 CSVfileName);
197
198 return 0;
199}
200
202 : bytesTotal(0),
204{
205}
206
207void
209{
210 NS_LOG_UNCOND(Simulator::Now().As(Time::S) << " Received one packet!");
211 Ptr<Packet> packet;
212 while ((packet = socket->Recv()))
213 {
214 bytesTotal += packet->GetSize();
215 packetsReceived += 1;
216 }
217}
218
219void
221{
222 double kbs = (bytesTotal * 8.0) / 1000;
223 bytesTotal = 0;
224
225 std::ofstream out(m_CSVfileName, std::ios::app);
226
227 out << (Simulator::Now()).GetSeconds() << "," << kbs << "," << packetsReceived << ","
228 << m_nSinks << std::endl;
229
230 out.close();
231 packetsReceived = 0;
233}
234
237{
238 TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory");
241 sink->Bind(local);
242 sink->SetRecvCallback(MakeCallback(&DsdvManetExample::ReceivePacket, this));
243
244 return sink;
245}
246
247void
249 uint32_t nSinks,
250 double totalTime,
251 std::string rate,
252 std::string phyMode,
253 uint32_t nodeSpeed,
254 uint32_t periodicUpdateInterval,
255 uint32_t settlingTime,
256 double dataStart,
257 bool printRoutes,
258 std::string CSVfileName)
259{
260 m_nWifis = nWifis;
261 m_nSinks = nSinks;
262 m_totalTime = totalTime;
263 m_rate = rate;
264 m_phyMode = phyMode;
265 m_nodeSpeed = nodeSpeed;
266 m_periodicUpdateInterval = periodicUpdateInterval;
267 m_settlingTime = settlingTime;
268 m_dataStart = dataStart;
269 m_printRoutes = printRoutes;
270 m_CSVfileName = CSVfileName;
271
272 std::stringstream ss;
273 ss << m_nWifis;
274 std::string t_nodes = ss.str();
275
276 std::stringstream ss3;
277 ss3 << m_totalTime;
278 std::string sTotalTime = ss3.str();
279
280 std::string tr_name = "Dsdv_Manet_" + t_nodes + "Nodes_" + sTotalTime + "SimTime";
281 std::cout << "Trace file generated is " << tr_name << ".tr\n";
282
283 CreateNodes();
284 CreateDevices(tr_name);
286 InstallInternetStack(tr_name);
288
289 std::cout << "\nStarting simulation for " << m_totalTime << " s ...\n";
290
292
296}
297
298void
300{
301 std::cout << "Creating " << (unsigned)m_nWifis << " nodes.\n";
304 "Sinks must be less or equal to the number of nodes in network");
305}
306
307void
309{
310 MobilityHelper mobility;
311 ObjectFactory pos;
312 pos.SetTypeId("ns3::RandomRectanglePositionAllocator");
313 pos.Set("X", StringValue("ns3::UniformRandomVariable[Min=0.0|Max=1000.0]"));
314 pos.Set("Y", StringValue("ns3::UniformRandomVariable[Min=0.0|Max=1000.0]"));
315
316 std::ostringstream speedConstantRandomVariableStream;
317 speedConstantRandomVariableStream << "ns3::ConstantRandomVariable[Constant=" << m_nodeSpeed
318 << "]";
319
320 Ptr<PositionAllocator> taPositionAlloc = pos.Create()->GetObject<PositionAllocator>();
321 mobility.SetMobilityModel("ns3::RandomWaypointMobilityModel",
322 "Speed",
323 StringValue(speedConstantRandomVariableStream.str()),
324 "Pause",
325 StringValue("ns3::ConstantRandomVariable[Constant=2.0]"),
326 "PositionAllocator",
327 PointerValue(taPositionAlloc));
328 mobility.SetPositionAllocator(taPositionAlloc);
329 mobility.Install(nodes);
330}
331
332void
334{
335 WifiMacHelper wifiMac;
336 wifiMac.SetType("ns3::AdhocWifiMac");
337 YansWifiPhyHelper wifiPhy;
338 YansWifiChannelHelper wifiChannel;
339 wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
340 wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel");
341 wifiPhy.SetChannel(wifiChannel.Create());
342 WifiHelper wifi;
343 wifi.SetStandard(WIFI_STANDARD_80211b);
344 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
345 "DataMode",
347 "ControlMode",
349 devices = wifi.Install(wifiPhy, wifiMac, nodes);
350
351 AsciiTraceHelper ascii;
352 wifiPhy.EnableAsciiAll(ascii.CreateFileStream(tr_name + ".tr"));
353 wifiPhy.EnablePcapAll(tr_name);
354}
355
356void
358{
359 DsdvHelper dsdv;
360 dsdv.Set("PeriodicUpdateInterval", TimeValue(Seconds(m_periodicUpdateInterval)));
361 dsdv.Set("SettlingTime", TimeValue(Seconds(m_settlingTime)));
363 stack.SetRoutingHelper(dsdv); // has effect on the next Install ()
364 stack.Install(nodes);
365 Ipv4AddressHelper address;
366 address.SetBase("10.1.1.0", "255.255.255.0");
367 interfaces = address.Assign(devices);
368 if (m_printRoutes)
369 {
370 Ptr<OutputStreamWrapper> routingStream =
371 Create<OutputStreamWrapper>((tr_name + ".routes"), std::ios::out);
373 }
374}
375
376void
378{
379 for (uint32_t i = 0; i <= m_nSinks - 1; i++)
380 {
382 Ipv4Address nodeAddress = node->GetObject<Ipv4>()->GetAddress(1, 0).GetLocal();
383 Ptr<Socket> sink = SetupPacketReceive(nodeAddress, node);
384 }
385
386 for (uint32_t clientNode = 0; clientNode <= m_nWifis - 1; clientNode++)
387 {
388 for (uint32_t j = 0; j <= m_nSinks - 1; j++)
389 {
390 OnOffHelper onoff1("ns3::UdpSocketFactory",
392 onoff1.SetAttribute("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=1.0]"));
393 onoff1.SetAttribute("OffTime",
394 StringValue("ns3::ConstantRandomVariable[Constant=0.0]"));
395
396 if (j != clientNode)
397 {
398 ApplicationContainer apps1 = onoff1.Install(nodes.Get(clientNode));
400 apps1.Start(Seconds(var->GetValue(m_dataStart, m_dataStart + 1)));
401 apps1.Stop(Seconds(m_totalTime));
402 }
403 }
404 }
405}
DSDV Manet example.
Definition dsdv-manet.cc:49
uint32_t m_nSinks
number of receiver nodes
Definition dsdv-manet.cc:80
void InstallApplications()
Create data sinks and sources.
NodeContainer nodes
the collection of nodes
Definition dsdv-manet.cc:93
void ReceivePacket(Ptr< Socket > socket)
Packet receive function.
double m_dataStart
time to start data transmissions (seconds)
Definition dsdv-manet.cc:87
std::string m_CSVfileName
CSV file name.
Definition dsdv-manet.cc:91
uint32_t packetsReceived
total packets received by all nodes
Definition dsdv-manet.cc:89
std::string m_rate
network bandwidth
Definition dsdv-manet.cc:82
uint32_t bytesTotal
total bytes received by all nodes
Definition dsdv-manet.cc:88
void CreateNodes()
Create and initialize all nodes.
bool m_printRoutes
print routing table
Definition dsdv-manet.cc:90
void InstallInternetStack(std::string tr_name)
Create network.
uint32_t m_nodeSpeed
mobility speed
Definition dsdv-manet.cc:84
void CreateDevices(std::string tr_name)
Create and initialize all devices.
void CaseRun(uint32_t nWifis, uint32_t nSinks, double totalTime, std::string rate, std::string phyMode, uint32_t nodeSpeed, uint32_t periodicUpdateInterval, uint32_t settlingTime, double dataStart, bool printRoutes, std::string CSVfileName)
Run function.
uint32_t m_settlingTime
routing setting time
Definition dsdv-manet.cc:86
Ipv4InterfaceContainer interfaces
the collection of interfaces
Definition dsdv-manet.cc:95
void CheckThroughput()
Check network throughput.
void SetupMobility()
Setup mobility model.
NetDeviceContainer devices
the collection of devices
Definition dsdv-manet.cc:94
double m_totalTime
total simulation time (in seconds)
Definition dsdv-manet.cc:81
std::string m_phyMode
remote station manager data mode
Definition dsdv-manet.cc:83
Ptr< Socket > SetupPacketReceive(Ipv4Address addr, Ptr< Node > node)
Setup packet receivers.
uint32_t m_periodicUpdateInterval
routing update interval
Definition dsdv-manet.cc:85
uint32_t m_nWifis
total number of nodes
Definition dsdv-manet.cc:79
a polymophic address class
Definition address.h:90
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.
void EnableAsciiAll(std::string prefix)
Enable ascii trace output on each device (which is of the appropriate type) in the set of all nodes c...
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.
Helper class that adds DSDV routing to nodes.
Definition dsdv-helper.h:36
void Set(std::string name, const AttributeValue &value)
an Inet address class
aggregate IP/TCP/UDP functionality to existing Nodes.
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
Ipv4 addresses are stored in host order in this class.
Access to the IPv4 forwarding table, interfaces, and configuration.
Definition ipv4.h:69
holds a vector of std::pair of Ptr<Ipv4> and interface index.
Ipv4Address GetAddress(uint32_t i, uint32_t j=0) const
static void PrintRoutingTableAllAt(Time printTime, Ptr< OutputStreamWrapper > stream, Time::Unit unit=Time::S)
prints the routing tables of all nodes at a particular time.
Helper class used to assign positions and mobility models to nodes.
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.
static Ptr< Node > GetNode(uint32_t n)
Definition node-list.cc:240
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
A helper to make it easier to instantiate an ns3::OnOffApplication on a set of nodes.
void EnablePcapAll(std::string prefix, bool promiscuous=false)
Enable pcap output on each device (which is of the appropriate type) in the set of all nodes created ...
AttributeValue implementation for Pointer.
Allocate a set of positions.
Smart pointer class similar to boost::intrusive_ptr.
static void SetSeed(uint32_t seed)
Set the seed.
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition simulator.h:560
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
@ S
second
Definition nstime.h:105
a unique identifier for an interface.
Definition type-id.h:48
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)
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)
uint16_t port
Definition dsdv-manet.cc:33
auto packetsReceived
Record received pkts by Data Rate (DR) [index 0 -> DR5, index 5 -> DR0].
#define NS_ASSERT_MSG(condition, message)
At runtime, in debugging builds, if this condition is not true, the program prints the message to out...
Definition assert.h:75
void SetDefault(std::string name, const AttributeValue &value)
Definition config.cc:883
#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
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:619
Ptr< T > Create(Ts &&... args)
Create class instances by constructors with varying numbers of arguments and return them by Ptr.
Definition ptr.h:436
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1308
@ WIFI_STANDARD_80211b
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
-ns3 Test suite for the ns3 wrapper script
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition wifi-tcp.cc:44