A Discrete-Event Network Simulator
API
seventh.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * This program is free software; you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License version 2 as
5  * published by the Free Software Foundation;
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15  */
16 
17 #include <fstream>
18 #include "ns3/core-module.h"
19 #include "ns3/network-module.h"
20 #include "ns3/internet-module.h"
21 #include "ns3/point-to-point-module.h"
22 #include "ns3/applications-module.h"
23 #include "ns3/stats-module.h"
24 
25 using namespace ns3;
26 
27 NS_LOG_COMPONENT_DEFINE ("SeventhScriptExample");
28 
29 // ===========================================================================
30 //
31 // node 0 node 1
32 // +----------------+ +----------------+
33 // | ns-3 TCP | | ns-3 TCP |
34 // +----------------+ +----------------+
35 // | 10.1.1.1 | | 10.1.1.2 |
36 // +----------------+ +----------------+
37 // | point-to-point | | point-to-point |
38 // +----------------+ +----------------+
39 // | |
40 // +---------------------+
41 // 5 Mbps, 2 ms
42 //
43 //
44 // We want to look at changes in the ns-3 TCP congestion window. We need
45 // to crank up a flow and hook the CongestionWindow attribute on the socket
46 // of the sender. Normally one would use an on-off application to generate a
47 // flow, but this has a couple of problems. First, the socket of the on-off
48 // application is not created until Application Start time, so we wouldn't be
49 // able to hook the socket (now) at configuration time. Second, even if we
50 // could arrange a call after start time, the socket is not public so we
51 // couldn't get at it.
52 //
53 // So, we can cook up a simple version of the on-off application that does what
54 // we want. On the plus side we don't need all of the complexity of the on-off
55 // application. On the minus side, we don't have a helper, so we have to get
56 // a little more involved in the details, but this is trivial.
57 //
58 // So first, we create a socket and do the trace connect on it; then we pass
59 // this socket into the constructor of our simple application which we then
60 // install in the source node.
61 //
62 // NOTE: If this example gets modified, do not forget to update the .png figure
63 // in src/stats/docs/seventh-packet-byte-count.png
64 // ===========================================================================
65 //
66 class MyApp : public Application
67 {
68 public:
69  MyApp ();
70  virtual ~MyApp ();
71 
76  static TypeId GetTypeId (void);
77  void Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate);
78 
79 private:
80  virtual void StartApplication (void);
81  virtual void StopApplication (void);
82 
83  void ScheduleTx (void);
84  void SendPacket (void);
85 
86  Ptr<Socket> m_socket;
87  Address m_peer;
88  uint32_t m_packetSize;
89  uint32_t m_nPackets;
90  DataRate m_dataRate;
91  EventId m_sendEvent;
92  bool m_running;
93  uint32_t m_packetsSent;
94 };
95 
96 MyApp::MyApp ()
97  : m_socket (0),
98  m_peer (),
99  m_packetSize (0),
100  m_nPackets (0),
101  m_dataRate (0),
102  m_sendEvent (),
103  m_running (false),
104  m_packetsSent (0)
105 {
106 }
107 
108 MyApp::~MyApp ()
109 {
110  m_socket = 0;
111 }
112 
113 /* static */
115 {
116  static TypeId tid = TypeId ("MyApp")
118  .SetGroupName ("Tutorial")
119  .AddConstructor<MyApp> ()
120  ;
121  return tid;
122 }
123 
124 void
125 MyApp::Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate)
126 {
127  m_socket = socket;
128  m_peer = address;
130  m_nPackets = nPackets;
131  m_dataRate = dataRate;
132 }
133 
134 void
136 {
137  m_running = true;
138  m_packetsSent = 0;
139  if (InetSocketAddress::IsMatchingType (m_peer))
140  {
141  m_socket->Bind ();
142  }
143  else
144  {
145  m_socket->Bind6 ();
146  }
148  SendPacket ();
149 }
150 
151 void
153 {
154  m_running = false;
155 
156  if (m_sendEvent.IsRunning ())
157  {
158  Simulator::Cancel (m_sendEvent);
159  }
160 
161  if (m_socket)
162  {
163  m_socket->Close ();
164  }
165 }
166 
167 void
168 MyApp::SendPacket (void)
169 {
170  Ptr<Packet> packet = Create<Packet> (m_packetSize);
171  m_socket->Send (packet);
172 
173  if (++m_packetsSent < m_nPackets)
174  {
175  ScheduleTx ();
176  }
177 }
178 
179 void
180 MyApp::ScheduleTx (void)
181 {
182  if (m_running)
183  {
184  Time tNext (Seconds (m_packetSize * 8 / static_cast<double> (m_dataRate.GetBitRate ())));
185  m_sendEvent = Simulator::Schedule (tNext, &MyApp::SendPacket, this);
186  }
187 }
188 
189 static void
190 CwndChange (Ptr<OutputStreamWrapper> stream, uint32_t oldCwnd, uint32_t newCwnd)
191 {
192  NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\t" << newCwnd);
193  *stream->GetStream () << Simulator::Now ().GetSeconds () << "\t" << oldCwnd << "\t" << newCwnd << std::endl;
194 }
195 
196 static void
198 {
199  NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ());
200  file->Write (Simulator::Now (), p);
201 }
202 
203 int
204 main (int argc, char *argv[])
205 {
206  bool useV6 = false;
207 
208  CommandLine cmd (__FILE__);
209  cmd.AddValue ("useIpv6", "Use Ipv6", useV6);
210  cmd.Parse (argc, argv);
211 
213  nodes.Create (2);
214 
216  pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
217  pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
218 
220  devices = pointToPoint.Install (nodes);
221 
222  Ptr<RateErrorModel> em = CreateObject<RateErrorModel> ();
223  em->SetAttribute ("ErrorRate", DoubleValue (0.00001));
224  devices.Get (1)->SetAttribute ("ReceiveErrorModel", PointerValue (em));
225 
227  stack.Install (nodes);
228 
229  uint16_t sinkPort = 8080;
230  Address sinkAddress;
231  Address anyAddress;
232  std::string probeType;
233  std::string tracePath;
234  if (useV6 == false)
235  {
237  address.SetBase ("10.1.1.0", "255.255.255.0");
239  sinkAddress = InetSocketAddress (interfaces.GetAddress (1), sinkPort);
240  anyAddress = InetSocketAddress (Ipv4Address::GetAny (), sinkPort);
241  probeType = "ns3::Ipv4PacketProbe";
242  tracePath = "/NodeList/*/$ns3::Ipv4L3Protocol/Tx";
243  }
244  else
245  {
247  address.SetBase ("2001:0000:f00d:cafe::", Ipv6Prefix (64));
249  sinkAddress = Inet6SocketAddress (interfaces.GetAddress (1,1), sinkPort);
250  anyAddress = Inet6SocketAddress (Ipv6Address::GetAny (), sinkPort);
251  probeType = "ns3::Ipv6PacketProbe";
252  tracePath = "/NodeList/*/$ns3::Ipv6L3Protocol/Tx";
253  }
254 
255  PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", anyAddress);
256  ApplicationContainer sinkApps = packetSinkHelper.Install (nodes.Get (1));
257  sinkApps.Start (Seconds (0.));
258  sinkApps.Stop (Seconds (20.));
259 
260  Ptr<Socket> ns3TcpSocket = Socket::CreateSocket (nodes.Get (0), TcpSocketFactory::GetTypeId ());
261 
262  Ptr<MyApp> app = CreateObject<MyApp> ();
263  app->Setup (ns3TcpSocket, sinkAddress, 1040, 1000, DataRate ("1Mbps"));
264  nodes.Get (0)->AddApplication (app);
265  app->SetStartTime (Seconds (1.));
266  app->SetStopTime (Seconds (20.));
267 
268  AsciiTraceHelper asciiTraceHelper;
269  Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream ("seventh.cwnd");
270  ns3TcpSocket->TraceConnectWithoutContext ("CongestionWindow", MakeBoundCallback (&CwndChange, stream));
271 
272  PcapHelper pcapHelper;
273  Ptr<PcapFileWrapper> file = pcapHelper.CreateFile ("seventh.pcap", std::ios::out, PcapHelper::DLT_PPP);
274  devices.Get (1)->TraceConnectWithoutContext ("PhyRxDrop", MakeBoundCallback (&RxDrop, file));
275 
276  // Use GnuplotHelper to plot the packet byte count over time
277  GnuplotHelper plotHelper;
278 
279  // Configure the plot. The first argument is the file name prefix
280  // for the output files generated. The second, third, and fourth
281  // arguments are, respectively, the plot title, x-axis, and y-axis labels
282  plotHelper.ConfigurePlot ("seventh-packet-byte-count",
283  "Packet Byte Count vs. Time",
284  "Time (Seconds)",
285  "Packet Byte Count");
286 
287  // Specify the probe type, trace source path (in configuration namespace), and
288  // probe output trace source ("OutputBytes") to plot. The fourth argument
289  // specifies the name of the data series label on the plot. The last
290  // argument formats the plot by specifying where the key should be placed.
291  plotHelper.PlotProbe (probeType,
292  tracePath,
293  "OutputBytes",
294  "Packet Byte Count",
295  GnuplotAggregator::KEY_BELOW);
296 
297  // Use FileHelper to write out the packet byte count over time
298  FileHelper fileHelper;
299 
300  // Configure the file to be written, and the formatting of output data.
301  fileHelper.ConfigureFile ("seventh-packet-byte-count",
302  FileAggregator::FORMATTED);
303 
304  // Set the labels for this formatted output file.
305  fileHelper.Set2dFormat ("Time (Seconds) = %.3e\tPacket Byte Count = %.0f");
306 
307  // Specify the probe type, trace source path (in configuration namespace), and
308  // probe output trace source ("OutputBytes") to write.
309  fileHelper.WriteProbe (probeType,
310  tracePath,
311  "OutputBytes");
312 
313  Simulator::Stop (Seconds (20));
314  Simulator::Run ();
315  Simulator::Destroy ();
316 
317  return 0;
318 }
319 
holds a vector of ns3::Application pointers.
Simulation virtual time values and global simulation resolution.
Definition: nstime.h:103
Ptr< Socket > m_socket
Definition: fifth.cc:78
Manage ASCII trace files for device models.
Definition: trace-helper.h:161
an Inet address class
Keep track of a set of IPv6 interfaces.
holds a vector of std::pair of Ptr<Ipv4> and interface index.
virtual int Bind6()=0
Allocate a local IPv6 endpoint for this socket.
Hold variables of type string.
Definition: string.h:41
static const uint32_t packetSize
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)
Manage pcap files for device models.
Definition: trace-helper.h:38
Callback< R > MakeBoundCallback(R(*fnPtr)(TX), ARG a1)
Make Callbacks with one bound argument.
Definition: callback.h:1703
double GetSeconds(void) const
Get an approximation of the time stored in this instance in the indicated unit.
Definition: nstime.h:380
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:205
aggregate IP/TCP/UDP functionality to existing Nodes.
DataRate m_dataRate
Definition: fifth.cc:82
A helper to make it easier to instantiate an ns3::PacketSinkApplication on a set of nodes...
cmd
Definition: second.py:35
Ptr< OutputStreamWrapper > CreateFileStream(std::string filename, std::ios::openmode filemode=std::ios::out)
Create and initialize an output stream object we&#39;ll use to write the traced bits. ...
Build a set of PointToPointNetDevice objects.
Address m_peer
Definition: fifth.cc:79
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
uint64_t GetBitRate() const
Get the underlying bitrate.
Definition: data-rate.cc:287
stack
Definition: first.py:41
a polymophic address class
Definition: address.h:90
Definition: fifth.cc:62
static void CwndChange(Ptr< OutputStreamWrapper > stream, uint32_t oldCwnd, uint32_t newCwnd)
Definition: seventh.cc:190
Class for representing data rates.
Definition: data-rate.h:88
void ConfigurePlot(const std::string &outputFileNameWithoutExtension, const std::string &title, const std::string &xLegend, const std::string &yLegend, const std::string &terminalType="png")
void Setup(Ptr< Socket > socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate)
Definition: fifth.cc:106
nodes
Definition: first.py:32
The base class for all ns3 applications.
Definition: application.h:60
pointToPoint
Definition: first.py:35
holds a vector of ns3::NetDevice pointers
void SendPacket(void)
Definition: fifth.cc:142
An Inet6 address class.
uint32_t m_nPackets
Definition: fifth.cc:81
bool m_running
Definition: fifth.cc:84
Helper class used to put data values into a file.
Definition: file-helper.h:38
uint32_t m_packetsSent
Definition: fifth.cc:85
void Start(Time start)
Arrange for all of the Applications in this container to Start() at the Time given as a parameter...
Parse command-line arguments.
Definition: command-line.h:227
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
virtual ~MyApp()
Definition: fifth.cc:100
bool TraceConnectWithoutContext(std::string name, const CallbackBase &cb)
Connect a TraceSource to a Callback without a context.
Definition: object-base.cc:293
Helper class used to make gnuplot plots.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
Every class exported by the ns3 library is enclosed in the ns3 namespace.
EventId m_sendEvent
Definition: fifth.cc:83
keep track of a set of node pointers.
Hold objects of type Ptr<T>.
Definition: pointer.h:36
address
Definition: first.py:44
#define NS_LOG_UNCOND(msg)
Output the requested message unconditionally.
void ConfigureFile(const std::string &outputFileNameWithoutExtension, enum FileAggregator::FileType fileType=FileAggregator::SPACE_SEPARATED)
Definition: file-helper.cc:68
virtual void StopApplication(void)
Application specific shutdown code.
Definition: fifth.cc:126
virtual void StartApplication(void)
Application specific startup code.
Definition: fifth.cc:116
MyApp()
Definition: fifth.cc:88
void SendPacket(Ptr< NetDevice > sourceDevice, Address &destination)
This example (inspired from tv-trans-example) enables to generate the transmitted spectra of Wi-Fi st...
Helper class to auto-assign global IPv6 unicast addresses.
void Stop(Time stop)
Arrange for all of the Applications in this container to Stop() at the Time given as a parameter...
An identifier for simulation events.
Definition: event-id.h:53
static TypeId GetTypeId(void)
Register this type.
Definition: seventh.cc:114
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1289
interfaces
Definition: first.py:48
bool IsRunning(void) const
This method is syntactic sugar for !IsExpired().
Definition: event-id.cc:71
Describes an IPv6 prefix.
Definition: ipv6-address.h:467
void WriteProbe(const std::string &typeId, const std::string &path, const std::string &probeTraceSource)
Definition: file-helper.cc:90
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
Time Now(void)
create an ns3::Time instance which contains the current simulation time.
Definition: simulator.cc:287
devices
Definition: first.py:39
virtual int Send(Ptr< Packet > p, uint32_t flags)=0
Send data (or dummy data) to the remote host.
virtual int Close(void)=0
Close a socket.
This class can be used to hold variables of floating point type such as &#39;double&#39; or &#39;float&#39;...
Definition: double.h:41
void SetAttribute(std::string name, const AttributeValue &value)
Set a single attribute, raising fatal errors if unsuccessful.
Definition: object-base.cc:185
a unique identifier for an interface.
Definition: type-id.h:58
void ScheduleTx(void)
Definition: fifth.cc:154
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition: type-id.cc:923
static void RxDrop(Ptr< PcapFileWrapper > file, Ptr< const Packet > p)
Definition: seventh.cc:197
std::ostream * GetStream(void)
Return a pointer to an ostream previously set in the wrapper.
void Set2dFormat(const std::string &format)
Sets the 2D format string for the C-style sprintf() function.
Definition: file-helper.cc:379
uint32_t m_packetSize
Definition: fifth.cc:80