A Discrete-Event Network Simulator
API
seventh.cc
Go to the documentation of this file.
1/*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License version 2 as
4 * published by the Free Software Foundation;
5 *
6 * This program is distributed in the hope that it will be useful,
7 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 * GNU General Public License for more details.
10 *
11 * You should have received a copy of the GNU General Public License
12 * along with this program; if not, write to the Free Software
13 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
14 */
15
16#include "tutorial-app.h"
17
18#include "ns3/applications-module.h"
19#include "ns3/core-module.h"
20#include "ns3/internet-module.h"
21#include "ns3/network-module.h"
22#include "ns3/point-to-point-module.h"
23#include "ns3/stats-module.h"
24
25#include <fstream>
26
27using namespace ns3;
28
29NS_LOG_COMPONENT_DEFINE("SeventhScriptExample");
30
31// ===========================================================================
32//
33// node 0 node 1
34// +----------------+ +----------------+
35// | ns-3 TCP | | ns-3 TCP |
36// +----------------+ +----------------+
37// | 10.1.1.1 | | 10.1.1.2 |
38// +----------------+ +----------------+
39// | point-to-point | | point-to-point |
40// +----------------+ +----------------+
41// | |
42// +---------------------+
43// 5 Mbps, 2 ms
44//
45//
46// We want to look at changes in the ns-3 TCP congestion window. We need
47// to crank up a flow and hook the CongestionWindow attribute on the socket
48// of the sender. Normally one would use an on-off application to generate a
49// flow, but this has a couple of problems. First, the socket of the on-off
50// application is not created until Application Start time, so we wouldn't be
51// able to hook the socket (now) at configuration time. Second, even if we
52// could arrange a call after start time, the socket is not public so we
53// couldn't get at it.
54//
55// So, we can cook up a simple version of the on-off application that does what
56// we want. On the plus side we don't need all of the complexity of the on-off
57// application. On the minus side, we don't have a helper, so we have to get
58// a little more involved in the details, but this is trivial.
59//
60// So first, we create a socket and do the trace connect on it; then we pass
61// this socket into the constructor of our simple application which we then
62// install in the source node.
63//
64// NOTE: If this example gets modified, do not forget to update the .png figure
65// in src/stats/docs/seventh-packet-byte-count.png
66// ===========================================================================
67//
68
76static void
78{
79 NS_LOG_UNCOND(Simulator::Now().GetSeconds() << "\t" << newCwnd);
80 *stream->GetStream() << Simulator::Now().GetSeconds() << "\t" << oldCwnd << "\t" << newCwnd
81 << std::endl;
82}
83
90static void
92{
93 NS_LOG_UNCOND("RxDrop at " << Simulator::Now().GetSeconds());
94 file->Write(Simulator::Now(), p);
95}
96
97int
98main(int argc, char* argv[])
99{
100 bool useV6 = false;
101
102 CommandLine cmd(__FILE__);
103 cmd.AddValue("useIpv6", "Use Ipv6", useV6);
104 cmd.Parse(argc, argv);
105
107 nodes.Create(2);
108
110 pointToPoint.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
111 pointToPoint.SetChannelAttribute("Delay", StringValue("2ms"));
112
114 devices = pointToPoint.Install(nodes);
115
116 Ptr<RateErrorModel> em = CreateObject<RateErrorModel>();
117 em->SetAttribute("ErrorRate", DoubleValue(0.00001));
118 devices.Get(1)->SetAttribute("ReceiveErrorModel", PointerValue(em));
119
121 stack.Install(nodes);
122
123 uint16_t sinkPort = 8080;
124 Address sinkAddress;
125 Address anyAddress;
126 std::string probeType;
127 std::string tracePath;
128 if (useV6 == false)
129 {
131 address.SetBase("10.1.1.0", "255.255.255.0");
133 sinkAddress = InetSocketAddress(interfaces.GetAddress(1), sinkPort);
134 anyAddress = InetSocketAddress(Ipv4Address::GetAny(), sinkPort);
135 probeType = "ns3::Ipv4PacketProbe";
136 tracePath = "/NodeList/*/$ns3::Ipv4L3Protocol/Tx";
137 }
138 else
139 {
141 address.SetBase("2001:0000:f00d:cafe::", Ipv6Prefix(64));
143 sinkAddress = Inet6SocketAddress(interfaces.GetAddress(1, 1), sinkPort);
144 anyAddress = Inet6SocketAddress(Ipv6Address::GetAny(), sinkPort);
145 probeType = "ns3::Ipv6PacketProbe";
146 tracePath = "/NodeList/*/$ns3::Ipv6L3Protocol/Tx";
147 }
148
149 PacketSinkHelper packetSinkHelper("ns3::TcpSocketFactory", anyAddress);
150 ApplicationContainer sinkApps = packetSinkHelper.Install(nodes.Get(1));
151 sinkApps.Start(Seconds(0.));
152 sinkApps.Stop(Seconds(20.));
153
154 Ptr<Socket> ns3TcpSocket = Socket::CreateSocket(nodes.Get(0), TcpSocketFactory::GetTypeId());
155
156 Ptr<TutorialApp> app = CreateObject<TutorialApp>();
157 app->Setup(ns3TcpSocket, sinkAddress, 1040, 1000, DataRate("1Mbps"));
158 nodes.Get(0)->AddApplication(app);
159 app->SetStartTime(Seconds(1.));
160 app->SetStopTime(Seconds(20.));
161
162 AsciiTraceHelper asciiTraceHelper;
163 Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream("seventh.cwnd");
164 ns3TcpSocket->TraceConnectWithoutContext("CongestionWindow",
165 MakeBoundCallback(&CwndChange, stream));
166
167 PcapHelper pcapHelper;
169 pcapHelper.CreateFile("seventh.pcap", std::ios::out, PcapHelper::DLT_PPP);
170 devices.Get(1)->TraceConnectWithoutContext("PhyRxDrop", MakeBoundCallback(&RxDrop, file));
171
172 // Use GnuplotHelper to plot the packet byte count over time
173 GnuplotHelper plotHelper;
174
175 // Configure the plot. The first argument is the file name prefix
176 // for the output files generated. The second, third, and fourth
177 // arguments are, respectively, the plot title, x-axis, and y-axis labels
178 plotHelper.ConfigurePlot("seventh-packet-byte-count",
179 "Packet Byte Count vs. Time",
180 "Time (Seconds)",
181 "Packet Byte Count");
182
183 // Specify the probe type, trace source path (in configuration namespace), and
184 // probe output trace source ("OutputBytes") to plot. The fourth argument
185 // specifies the name of the data series label on the plot. The last
186 // argument formats the plot by specifying where the key should be placed.
187 plotHelper.PlotProbe(probeType,
188 tracePath,
189 "OutputBytes",
190 "Packet Byte Count",
191 GnuplotAggregator::KEY_BELOW);
192
193 // Use FileHelper to write out the packet byte count over time
194 FileHelper fileHelper;
195
196 // Configure the file to be written, and the formatting of output data.
197 fileHelper.ConfigureFile("seventh-packet-byte-count", FileAggregator::FORMATTED);
198
199 // Set the labels for this formatted output file.
200 fileHelper.Set2dFormat("Time (Seconds) = %.3e\tPacket Byte Count = %.0f");
201
202 // Specify the probe type, trace source path (in configuration namespace), and
203 // probe output trace source ("OutputBytes") to write.
204 fileHelper.WriteProbe(probeType, tracePath, "OutputBytes");
205
206 Simulator::Stop(Seconds(20));
207 Simulator::Run();
208 Simulator::Destroy();
209
210 return 0;
211}
a polymophic address class
Definition: address.h:100
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.
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 used to put data values into a file.
Definition: file-helper.h:40
void Set2dFormat(const std::string &format)
Sets the 2D format string for the C-style sprintf() function.
Definition: file-helper.cc:377
void WriteProbe(const std::string &typeId, const std::string &path, const std::string &probeTraceSource)
Definition: file-helper.cc:91
void ConfigureFile(const std::string &outputFileNameWithoutExtension, enum FileAggregator::FileType fileType=FileAggregator::SPACE_SEPARATED)
Definition: file-helper.cc:69
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, enum 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.
holds a vector of std::pair of Ptr<Ipv4> and interface index.
Helper class to auto-assign global IPv6 unicast addresses.
Keep track of a set of IPv6 interfaces.
Describes an IPv6 prefix.
Definition: ipv6-address.h:455
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:169
bool TraceConnectWithoutContext(std::string name, const CallbackBase &cb)
Connect a TraceSource to a Callback without a context.
Definition: object-base.cc:311
void SetAttribute(std::string name, const AttributeValue &value)
Set a single attribute, raising fatal errors if unsuccessful.
Definition: object-base.cc:200
std::ostream * GetStream()
Return a pointer to an ostream previously set in the wrapper.
A helper to make it easier to instantiate an ns3::PacketSinkApplication on a set of nodes.
Manage pcap files for device models.
Definition: trace-helper.h:39
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.
Definition: trace-helper.cc:49
Build a set of PointToPointNetDevice objects.
Hold objects of type Ptr<T>.
Definition: pointer.h:37
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
#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
auto MakeBoundCallback(R(*fnPtr)(Args...), BArgs &&... bargs)
Make Callbacks with varying number of bound arguments.
Definition: callback.h:768
void(* DataRate)(DataRate oldValue, DataRate newValue)
TracedValue callback signature for DataRate.
Definition: data-rate.h:327
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
NodeContainer nodes
address
Definition: first.py:40
pointToPoint
Definition: first.py:31
devices
Definition: first.py:35
stack
Definition: first.py:37
interfaces
Definition: first.py:44
Every class exported by the ns3 library is enclosed in the ns3 namespace.
cmd
Definition: second.py:33
static void CwndChange(Ptr< OutputStreamWrapper > stream, uint32_t oldCwnd, uint32_t newCwnd)
Congestion window change callback.
Definition: seventh.cc:77
static void RxDrop(Ptr< PcapFileWrapper > file, Ptr< const Packet > p)
Rx drop callback.
Definition: seventh.cc:91