A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
tcp-linux-reno.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2019 NITK Surathkal
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Authors: Apoorva Bhargava <apoorvabhargava13@gmail.com>
7 */
8
9// Network topology
10//
11// n0 ---------- n1 ---------- n2 ---------- n3
12// 10 Mbps 1 Mbps 10 Mbps
13// 1 ms 10 ms 1 ms
14//
15// - TCP flow from n0 to n3 using BulkSendApplication.
16// - The following simulation output is stored in results/ in ns-3 top-level directory:
17// - cwnd traces are stored in cwndTraces folder
18// - queue length statistics are stored in queue-size.dat file
19// - pcaps are stored in pcap folder
20// - queueTraces folder contain the drop statistics at queue
21// - queueStats.txt file contains the queue stats and config.txt file contains
22// the simulation configuration.
23// - The cwnd and queue length traces obtained from this example were tested against
24// the respective traces obtained from Linux Reno by using ns-3 Direct Code Execution.
25// See internet/doc/tcp.rst for more details.
26
27#include "ns3/applications-module.h"
28#include "ns3/core-module.h"
29#include "ns3/internet-module.h"
30#include "ns3/network-module.h"
31#include "ns3/point-to-point-module.h"
32#include "ns3/traffic-control-module.h"
33
34#include <fstream>
35#include <iostream>
36#include <string>
37#include <sys/stat.h>
38
39using namespace ns3;
40std::string dir = "results/";
43
44std::ofstream fPlotQueue;
45std::ofstream fPlotCwnd;
46
47// Function to check queue length of Router 1
48void
50{
51 uint32_t qSize = queue->GetCurrentSize().GetValue();
52
53 // Check queue size every 1/100 of a second
55 fPlotQueue << Simulator::Now().GetSeconds() << " " << qSize << std::endl;
56}
57
58// Function to trace change in cwnd at n0
59static void
60CwndChange(uint32_t oldCwnd, uint32_t newCwnd)
61{
62 fPlotCwnd << Simulator::Now().GetSeconds() << " " << newCwnd / segmentSize << std::endl;
63}
64
65// Function to calculate drops in a particular Queue
66static void
68{
69 *stream->GetStream() << Simulator::Now().GetSeconds() << " 1" << std::endl;
70}
71
72// Trace Function for cwnd
73void
75{
76 Config::ConnectWithoutContext("/NodeList/" + std::to_string(node) +
77 "/$ns3::TcpL4Protocol/SocketList/" +
78 std::to_string(cwndWindow) + "/CongestionWindow",
79 CwndTrace);
80}
81
82// Function to install BulkSend application
83void
85 Ipv4Address address,
86 uint16_t port,
87 std::string socketFactory,
88 uint32_t nodeId,
89 uint32_t cwndWindow,
91{
92 BulkSendHelper source(socketFactory, InetSocketAddress(address, port));
93 source.SetAttribute("MaxBytes", UintegerValue(0));
94 ApplicationContainer sourceApps = source.Install(node);
95 sourceApps.Start(Seconds(10));
96 Simulator::Schedule(Seconds(10) + Seconds(0.001), &TraceCwnd, nodeId, cwndWindow, CwndTrace);
97 sourceApps.Stop(stopTime);
98}
99
100// Function to install sink application
101void
102InstallPacketSink(Ptr<Node> node, uint16_t port, std::string socketFactory)
103{
105 ApplicationContainer sinkApps = sink.Install(node);
106 sinkApps.Start(Seconds(10));
107 sinkApps.Stop(stopTime);
108}
109
110int
111main(int argc, char* argv[])
112{
113 uint32_t stream = 1;
114 std::string socketFactory = "ns3::TcpSocketFactory";
115 std::string tcpTypeId = "ns3::TcpLinuxReno";
116 std::string qdiscTypeId = "ns3::FifoQueueDisc";
117 bool isSack = true;
118 uint32_t delAckCount = 1;
119 std::string recovery = "ns3::TcpClassicRecovery";
120
122 cmd.AddValue("tcpTypeId",
123 "TCP variant to use (e.g., ns3::TcpNewReno, ns3::TcpLinuxReno, etc.)",
124 tcpTypeId);
125 cmd.AddValue("qdiscTypeId", "Queue disc for gateway (e.g., ns3::CoDelQueueDisc)", qdiscTypeId);
126 cmd.AddValue("segmentSize", "TCP segment size (bytes)", segmentSize);
127 cmd.AddValue("delAckCount", "Delayed ack count", delAckCount);
128 cmd.AddValue("enableSack", "Flag to enable/disable sack in TCP", isSack);
129 cmd.AddValue("stopTime",
130 "Stop time for applications / simulation time will be stopTime",
131 stopTime);
132 cmd.AddValue("recovery", "Recovery algorithm type to use (e.g., ns3::TcpPrrRecovery", recovery);
133 cmd.Parse(argc, argv);
134
135 TypeId qdTid;
137 "TypeId " << qdiscTypeId << " not found");
138
139 // Set recovery algorithm and TCP variant
140 Config::SetDefault("ns3::TcpL4Protocol::RecoveryType",
142 TypeId tcpTid;
144 "TypeId " << tcpTypeId << " not found");
145 Config::SetDefault("ns3::TcpL4Protocol::SocketType",
147
148 // Create nodes
149 NodeContainer leftNodes;
150 NodeContainer rightNodes;
151 NodeContainer routers;
152 routers.Create(2);
153 leftNodes.Create(1);
154 rightNodes.Create(1);
155
156 std::vector<NetDeviceContainer> leftToRouter;
157 std::vector<NetDeviceContainer> routerToRight;
158
159 // Create the point-to-point link helpers and connect two router nodes
160 PointToPointHelper pointToPointRouter;
161 pointToPointRouter.SetDeviceAttribute("DataRate", StringValue("1Mbps"));
162 pointToPointRouter.SetChannelAttribute("Delay", StringValue("10ms"));
163 NetDeviceContainer r1r2ND = pointToPointRouter.Install(routers.Get(0), routers.Get(1));
164
165 // Create the point-to-point link helpers and connect leaf nodes to router
166 PointToPointHelper pointToPointLeaf;
167 pointToPointLeaf.SetDeviceAttribute("DataRate", StringValue("10Mbps"));
168 pointToPointLeaf.SetChannelAttribute("Delay", StringValue("1ms"));
169 leftToRouter.push_back(pointToPointLeaf.Install(leftNodes.Get(0), routers.Get(0)));
170 routerToRight.push_back(pointToPointLeaf.Install(routers.Get(1), rightNodes.Get(0)));
171
172 InternetStackHelper internetStack;
173
174 internetStack.Install(leftNodes);
175 internetStack.Install(rightNodes);
176 internetStack.Install(routers);
177
178 // Assign IP addresses to all the network devices
179 Ipv4AddressHelper ipAddresses("10.0.0.0", "255.255.255.0");
180
181 Ipv4InterfaceContainer r1r2IPAddress = ipAddresses.Assign(r1r2ND);
182 ipAddresses.NewNetwork();
183
184 std::vector<Ipv4InterfaceContainer> leftToRouterIPAddress;
185 leftToRouterIPAddress.push_back(ipAddresses.Assign(leftToRouter[0]));
186 ipAddresses.NewNetwork();
187
188 std::vector<Ipv4InterfaceContainer> routerToRightIPAddress;
189 routerToRightIPAddress.push_back(ipAddresses.Assign(routerToRight[0]));
190
192
193 // Set default sender and receiver buffer size as 1MB
194 Config::SetDefault("ns3::TcpSocket::SndBufSize", UintegerValue(1 << 20));
195 Config::SetDefault("ns3::TcpSocket::RcvBufSize", UintegerValue(1 << 20));
196
197 // Set default initial congestion window as 10 segments
198 Config::SetDefault("ns3::TcpSocket::InitialCwnd", UintegerValue(10));
199
200 // Set default delayed ack count to a specified value
201 Config::SetDefault("ns3::TcpSocket::DelAckCount", UintegerValue(delAckCount));
202
203 // Set default segment size of TCP packet to a specified value
204 Config::SetDefault("ns3::TcpSocket::SegmentSize", UintegerValue(segmentSize));
205
206 // Enable/Disable SACK in TCP
207 Config::SetDefault("ns3::TcpSocketBase::Sack", BooleanValue(isSack));
208
209 // Create directories to store dat files
210 struct stat buffer;
211 int retVal [[maybe_unused]];
212 if ((stat(dir.c_str(), &buffer)) == 0)
213 {
214 std::string dirToRemove = "rm -rf " + dir;
215 retVal = system(dirToRemove.c_str());
216 NS_ASSERT_MSG(retVal == 0, "Error in return value");
217 }
218
221 SystemPath::MakeDirectories(dir + "/queueTraces/");
222 SystemPath::MakeDirectories(dir + "/cwndTraces/");
223
224 // Set default parameters for queue discipline
225 Config::SetDefault(qdiscTypeId + "::MaxSize", QueueSizeValue(QueueSize("100p")));
226
227 // Install queue discipline on router
229 tch.SetRootQueueDisc(qdiscTypeId);
231 tch.Uninstall(routers.Get(0)->GetDevice(0));
232 qd.Add(tch.Install(routers.Get(0)->GetDevice(0)).Get(0));
233
234 // Enable BQL
235 tch.SetQueueLimits("ns3::DynamicQueueLimits");
236
237 // Open files for writing queue size and cwnd traces
238 fPlotQueue.open(dir + "queue-size.dat", std::ios::out);
239 fPlotCwnd.open(dir + "cwndTraces/n0.dat", std::ios::out);
240
241 // Calls function to check queue size
243
244 AsciiTraceHelper asciiTraceHelper;
245 Ptr<OutputStreamWrapper> streamWrapper;
246
247 // Create dat to store packets dropped and marked at the router
248 streamWrapper = asciiTraceHelper.CreateFileStream(dir + "/queueTraces/drop-0.dat");
249 qd.Get(0)->TraceConnectWithoutContext("Drop", MakeBoundCallback(&DropAtQueue, streamWrapper));
250
251 // Install packet sink at receiver side
252 uint16_t port = 50000;
253 InstallPacketSink(rightNodes.Get(0), port, "ns3::TcpSocketFactory");
254
255 // Install BulkSend application
256 InstallBulkSend(leftNodes.Get(0),
257 routerToRightIPAddress[0].GetAddress(1),
258 port,
259 socketFactory,
260 2,
261 0,
263
264 // Enable PCAP on all the point to point interfaces
265 pointToPointLeaf.EnablePcapAll(dir + "pcap/ns-3", true);
266
269
270 // Store queue stats in a file
271 std::ofstream myfile;
272 myfile.open(dir + "queueStats.txt", std::fstream::in | std::fstream::out | std::fstream::app);
273 myfile << std::endl;
274 myfile << "Stat for Queue 1";
275 myfile << qd.Get(0)->GetStats();
276 myfile.close();
277
278 // Store configuration of the simulation in a file
279 myfile.open(dir + "config.txt", std::fstream::in | std::fstream::out | std::fstream::app);
280 myfile << "qdiscTypeId " << qdiscTypeId << "\n";
281 myfile << "stream " << stream << "\n";
282 myfile << "segmentSize " << segmentSize << "\n";
283 myfile << "delAckCount " << delAckCount << "\n";
284 myfile << "stopTime " << stopTime.As(Time::S) << "\n";
285 myfile.close();
286
288
289 fPlotQueue.close();
290 fPlotCwnd.close();
291
292 return 0;
293}
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.
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.
AttributeValue implementation for Boolean.
Definition boolean.h:26
A helper to make it easier to instantiate an ns3::BulkSendApplication on a set of nodes.
Callback template class.
Definition callback.h:422
Parse command-line arguments.
an Inet address class
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...
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.
static Ipv4Address GetAny()
static void PopulateRoutingTables()
Build a routing database and initialize the routing tables of the nodes in the simulation.
holds a vector of std::pair of Ptr<Ipv4> and interface index.
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.
Ptr< NetDevice > GetDevice(uint32_t index) const
Retrieve the index-th NetDevice associated to this node.
Definition node.cc:138
bool TraceConnectWithoutContext(std::string name, const CallbackBase &cb)
Connect a TraceSource to a Callback without a context.
A helper to make it easier to instantiate an ns3::PacketSinkApplication 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 ...
Build a set of PointToPointNetDevice objects.
void SetDeviceAttribute(std::string name, const AttributeValue &value)
Set an attribute value to be propagated to each NetDevice created by the helper.
void SetChannelAttribute(std::string name, const AttributeValue &value)
Set an attribute value to be propagated to each Channel created by the helper.
NetDeviceContainer Install(NodeContainer c)
Smart pointer class similar to boost::intrusive_ptr.
Holds a vector of ns3::QueueDisc pointers.
void Add(QueueDiscContainer other)
Append the contents of another QueueDiscContainer to the end of this container.
Ptr< QueueDisc > Get(std::size_t i) const
Get the Ptr<QueueDisc> stored in this container at a given index.
const Stats & GetStats()
Retrieve all the collected statistics.
Class for representing queue sizes.
Definition queue-size.h:85
AttributeValue implementation for QueueSize.
Definition queue-size.h:210
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 EventId ScheduleNow(FUNC f, Ts &&... args)
Schedule an event to expire Now.
Definition simulator.h:594
static void Stop()
Tell the Simulator the calling event should be the last one executed.
Definition simulator.cc:175
Hold variables of type string.
Definition string.h:45
Simulation virtual time values and global simulation resolution.
Definition nstime.h:94
TimeWithUnit As(const Unit unit=Time::AUTO) const
Attach a unit to a Time, to facilitate output in a specific unit.
Definition time.cc:404
double GetSeconds() const
Get an approximation of the time stored in this instance in the indicated unit.
Definition nstime.h:392
@ S
second
Definition nstime.h:105
Build a set of QueueDisc objects.
QueueDiscContainer Install(NetDeviceContainer c)
uint16_t SetRootQueueDisc(const std::string &type, Args &&... args)
Helper function used to set a root queue disc of the given type and with the given attributes.
void SetQueueLimits(std::string type, Args &&... args)
Helper function used to add a queue limits object to the transmission queues of the devices.
void Uninstall(NetDeviceContainer c)
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
static bool LookupByNameFailSafe(std::string name, TypeId *tid)
Get a TypeId by name.
Definition type-id.cc:886
AttributeValue implementation for TypeId.
Definition type-id.h:617
Hold an unsigned integer type.
Definition uinteger.h:34
static void CwndTrace(Ptr< OutputStreamWrapper > stream, uint32_t oldCwnd, uint32_t newCwnd)
uint16_t port
Definition dsdv-manet.cc:33
void InstallBulkSend(Ptr< Node > node, Ipv4Address address, uint16_t port, std::string socketFactory, uint32_t nodeId, uint32_t cwndWindow, Callback< void, uint32_t, uint32_t > CwndTrace)
void TraceCwnd(uint32_t node, uint32_t cwndWindow, Callback< void, uint32_t, uint32_t > CwndTrace)
uint32_t segmentSize
void InstallPacketSink(Ptr< Node > node, uint16_t port, std::string socketFactory)
std::ofstream fPlotCwnd
static void DropAtQueue(Ptr< OutputStreamWrapper > stream, Ptr< const QueueDiscItem > item)
void CheckQueueSize(Ptr< QueueDisc > queue)
Time stopTime
std::ofstream fPlotQueue
static void CwndChange(uint32_t oldCwnd, uint32_t newCwnd)
std::string dir
#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
void ConnectWithoutContext(std::string path, const CallbackBase &cb)
Definition config.cc:943
#define NS_ABORT_MSG_UNLESS(cond, msg)
Abnormal program termination if a condition is false, with a message.
Definition abort.h:133
auto MakeBoundCallback(R(*fnPtr)(Args...), BArgs &&... bargs)
Make Callbacks with varying number of bound arguments.
Definition callback.h:745
void MakeDirectories(std::string path)
Create all the directories leading to path.
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1344
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
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition wifi-tcp.cc:44