A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
seventh.cc
Go to the documentation of this file.
1/*
2 * SPDX-License-Identifier: GPL-2.0-only
3 */
4
5#include "tutorial-app.h"
6
7#include "ns3/applications-module.h"
8#include "ns3/core-module.h"
9#include "ns3/internet-module.h"
10#include "ns3/network-module.h"
11#include "ns3/point-to-point-module.h"
12#include "ns3/stats-module.h"
13
14#include <fstream>
15
16using namespace ns3;
17
18NS_LOG_COMPONENT_DEFINE("SeventhScriptExample");
19
20// ===========================================================================
21//
22// node 0 node 1
23// +----------------+ +----------------+
24// | ns-3 TCP | | ns-3 TCP |
25// +----------------+ +----------------+
26// | 10.1.1.1 | | 10.1.1.2 |
27// +----------------+ +----------------+
28// | point-to-point | | point-to-point |
29// +----------------+ +----------------+
30// | |
31// +---------------------+
32// 5 Mbps, 2 ms
33//
34//
35// We want to look at changes in the ns-3 TCP congestion window. We need
36// to crank up a flow and hook the CongestionWindow attribute on the socket
37// of the sender. Normally one would use an on-off application to generate a
38// flow, but this has a couple of problems. First, the socket of the on-off
39// application is not created until Application Start time, so we wouldn't be
40// able to hook the socket (now) at configuration time. Second, even if we
41// could arrange a call after start time, the socket is not public so we
42// couldn't get at it.
43//
44// So, we can cook up a simple version of the on-off application that does what
45// we want. On the plus side we don't need all of the complexity of the on-off
46// application. On the minus side, we don't have a helper, so we have to get
47// a little more involved in the details, but this is trivial.
48//
49// So first, we create a socket and do the trace connect on it; then we pass
50// this socket into the constructor of our simple application which we then
51// install in the source node.
52//
53// NOTE: If this example gets modified, do not forget to update the .png figure
54// in src/stats/docs/seventh-packet-byte-count.png
55// ===========================================================================
56//
57
58/**
59 * Congestion window change callback
60 *
61 * \param stream The output stream file.
62 * \param oldCwnd Old congestion window.
63 * \param newCwnd New congestion window.
64 */
65static void
67{
68 NS_LOG_UNCOND(Simulator::Now().GetSeconds() << "\t" << newCwnd);
69 *stream->GetStream() << Simulator::Now().GetSeconds() << "\t" << oldCwnd << "\t" << newCwnd
70 << std::endl;
71}
72
73/**
74 * Rx drop callback
75 *
76 * \param file The output PCAP file.
77 * \param p The dropped packet.
78 */
79static void
81{
82 NS_LOG_UNCOND("RxDrop at " << Simulator::Now().GetSeconds());
83 file->Write(Simulator::Now(), p);
84}
85
86int
87main(int argc, char* argv[])
88{
89 bool useV6 = false;
90
91 CommandLine cmd(__FILE__);
92 cmd.AddValue("useIpv6", "Use Ipv6", useV6);
93 cmd.Parse(argc, argv);
94
96 nodes.Create(2);
97
99 pointToPoint.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
100 pointToPoint.SetChannelAttribute("Delay", StringValue("2ms"));
101
103 devices = pointToPoint.Install(nodes);
104
106 em->SetAttribute("ErrorRate", DoubleValue(0.00001));
107 devices.Get(1)->SetAttribute("ReceiveErrorModel", PointerValue(em));
108
110 stack.Install(nodes);
111
112 uint16_t sinkPort = 8080;
113 Address sinkAddress;
114 Address anyAddress;
115 std::string probeType;
116 std::string tracePath;
117 if (!useV6)
118 {
120 address.SetBase("10.1.1.0", "255.255.255.0");
121 Ipv4InterfaceContainer interfaces = address.Assign(devices);
122 sinkAddress = InetSocketAddress(interfaces.GetAddress(1), sinkPort);
123 anyAddress = InetSocketAddress(Ipv4Address::GetAny(), sinkPort);
124 probeType = "ns3::Ipv4PacketProbe";
125 tracePath = "/NodeList/*/$ns3::Ipv4L3Protocol/Tx";
126 }
127 else
128 {
130 address.SetBase("2001:0000:f00d:cafe::", Ipv6Prefix(64));
131 Ipv6InterfaceContainer interfaces = address.Assign(devices);
132 sinkAddress = Inet6SocketAddress(interfaces.GetAddress(1, 1), sinkPort);
133 anyAddress = Inet6SocketAddress(Ipv6Address::GetAny(), sinkPort);
134 probeType = "ns3::Ipv6PacketProbe";
135 tracePath = "/NodeList/*/$ns3::Ipv6L3Protocol/Tx";
136 }
137
138 PacketSinkHelper packetSinkHelper("ns3::TcpSocketFactory", anyAddress);
139 ApplicationContainer sinkApps = packetSinkHelper.Install(nodes.Get(1));
140 sinkApps.Start(Seconds(0.));
141 sinkApps.Stop(Seconds(20.));
142
144
146 app->Setup(ns3TcpSocket, sinkAddress, 1040, 1000, DataRate("1Mbps"));
147 nodes.Get(0)->AddApplication(app);
148 app->SetStartTime(Seconds(1.));
149 app->SetStopTime(Seconds(20.));
150
151 AsciiTraceHelper asciiTraceHelper;
152 Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream("seventh.cwnd");
153 ns3TcpSocket->TraceConnectWithoutContext("CongestionWindow",
154 MakeBoundCallback(&CwndChange, stream));
155
156 PcapHelper pcapHelper;
158 pcapHelper.CreateFile("seventh.pcap", std::ios::out, PcapHelper::DLT_PPP);
159 devices.Get(1)->TraceConnectWithoutContext("PhyRxDrop", MakeBoundCallback(&RxDrop, file));
160
161 // Use GnuplotHelper to plot the packet byte count over time
162 GnuplotHelper plotHelper;
163
164 // Configure the plot. The first argument is the file name prefix
165 // for the output files generated. The second, third, and fourth
166 // arguments are, respectively, the plot title, x-axis, and y-axis labels
167 plotHelper.ConfigurePlot("seventh-packet-byte-count",
168 "Packet Byte Count vs. Time",
169 "Time (Seconds)",
170 "Packet Byte Count");
171
172 // Specify the probe type, trace source path (in configuration namespace), and
173 // probe output trace source ("OutputBytes") to plot. The fourth argument
174 // specifies the name of the data series label on the plot. The last
175 // argument formats the plot by specifying where the key should be placed.
176 plotHelper.PlotProbe(probeType,
177 tracePath,
178 "OutputBytes",
179 "Packet Byte Count",
181
182 // Use FileHelper to write out the packet byte count over time
183 FileHelper fileHelper;
184
185 // Configure the file to be written, and the formatting of output data.
186 fileHelper.ConfigureFile("seventh-packet-byte-count", FileAggregator::FORMATTED);
187
188 // Set the labels for this formatted output file.
189 fileHelper.Set2dFormat("Time (Seconds) = %.3e\tPacket Byte Count = %.0f");
190
191 // Specify the probe type, trace source path (in configuration namespace), and
192 // probe output trace source ("OutputBytes") to write.
193 fileHelper.WriteProbe(probeType, tracePath, "OutputBytes");
194
198
199 return 0;
200}
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.
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.
Class for representing data rates.
Definition data-rate.h:78
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition double.h:31
Helper class used to put data values into a file.
Definition file-helper.h:29
void Set2dFormat(const std::string &format)
Sets the 2D format string for the C-style sprintf() function.
void WriteProbe(const std::string &typeId, const std::string &path, const std::string &probeTraceSource)
void ConfigureFile(const std::string &outputFileNameWithoutExtension, FileAggregator::FileType fileType=FileAggregator::SPACE_SEPARATED)
Helper class used to make gnuplot plots.
void ConfigurePlot(const std::string &outputFileNameWithoutExtension, const std::string &title, const std::string &xLegend, const std::string &yLegend, const std::string &terminalType="png")
void PlotProbe(const std::string &typeId, const std::string &path, const std::string &probeTraceSource, const std::string &title, GnuplotAggregator::KeyLocation keyLocation=GnuplotAggregator::KEY_INSIDE)
An Inet6 address class.
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.
static Ipv4Address GetAny()
holds a vector of std::pair of Ptr<Ipv4> and interface index.
Helper class to auto-assign global IPv6 unicast addresses.
static Ipv6Address GetAny()
Get the "any" (::) Ipv6Address.
Keep track of a set of IPv6 interfaces.
Describes an IPv6 prefix.
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 AddApplication(Ptr< Application > application)
Associate an Application to this Node.
Definition node.cc:153
A helper to make it easier to instantiate an ns3::PacketSinkApplication on a set of nodes.
Manage pcap files for device models.
Ptr< PcapFileWrapper > CreateFile(std::string filename, std::ios::openmode filemode, DataLinkType dataLinkType, uint32_t snapLen=std::numeric_limits< uint32_t >::max(), int32_t tzCorrection=0)
Create and initialize a pcap file.
Build a set of PointToPointNetDevice objects.
AttributeValue implementation for Pointer.
Smart pointer class similar to boost::intrusive_ptr.
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
static TypeId GetTypeId()
Get the type ID.
double GetSeconds() const
Get an approximation of the time stored in this instance in the indicated unit.
Definition nstime.h:392
#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
auto MakeBoundCallback(R(*fnPtr)(Args...), BArgs &&... bargs)
Make Callbacks with varying number of bound arguments.
Definition callback.h:745
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:619
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1308
NodeContainer nodes
address
Definition first.py:36
pointToPoint
Definition first.py:27
devices
Definition first.py:31
stack
Definition first.py:33
interfaces
Definition first.py:39
Every class exported by the ns3 library is enclosed in the ns3 namespace.
static void CwndChange(Ptr< OutputStreamWrapper > stream, uint32_t oldCwnd, uint32_t newCwnd)
Congestion window change callback.
Definition seventh.cc:66
static void RxDrop(Ptr< PcapFileWrapper > file, Ptr< const Packet > p)
Rx drop callback.
Definition seventh.cc:80