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 //
63 class MyApp : public Application
64 {
65 public:
66  MyApp ();
67  virtual ~MyApp ();
68 
73  static TypeId GetTypeId (void);
74  void Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate);
75 
76 private:
77  virtual void StartApplication (void);
78  virtual void StopApplication (void);
79 
80  void ScheduleTx (void);
81  void SendPacket (void);
82 
83  Ptr<Socket> m_socket;
84  Address m_peer;
85  uint32_t m_packetSize;
86  uint32_t m_nPackets;
87  DataRate m_dataRate;
88  EventId m_sendEvent;
89  bool m_running;
90  uint32_t m_packetsSent;
91 };
92 
93 MyApp::MyApp ()
94  : m_socket (0),
95  m_peer (),
96  m_packetSize (0),
97  m_nPackets (0),
98  m_dataRate (0),
99  m_sendEvent (),
100  m_running (false),
101  m_packetsSent (0)
102 {
103 }
104 
105 MyApp::~MyApp ()
106 {
107  m_socket = 0;
108 }
109 
110 /* static */
112 {
113  static TypeId tid = TypeId ("MyApp")
115  .SetGroupName ("Tutorial")
116  .AddConstructor<MyApp> ()
117  ;
118  return tid;
119 }
120 
121 void
122 MyApp::Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate)
123 {
124  m_socket = socket;
125  m_peer = address;
127  m_nPackets = nPackets;
128  m_dataRate = dataRate;
129 }
130 
131 void
133 {
134  m_running = true;
135  m_packetsSent = 0;
136  if (InetSocketAddress::IsMatchingType (m_peer))
137  {
138  m_socket->Bind ();
139  }
140  else
141  {
142  m_socket->Bind6 ();
143  }
145  SendPacket ();
146 }
147 
148 void
150 {
151  m_running = false;
152 
153  if (m_sendEvent.IsRunning ())
154  {
155  Simulator::Cancel (m_sendEvent);
156  }
157 
158  if (m_socket)
159  {
160  m_socket->Close ();
161  }
162 }
163 
164 void
165 MyApp::SendPacket (void)
166 {
167  Ptr<Packet> packet = Create<Packet> (m_packetSize);
168  m_socket->Send (packet);
169 
170  if (++m_packetsSent < m_nPackets)
171  {
172  ScheduleTx ();
173  }
174 }
175 
176 void
177 MyApp::ScheduleTx (void)
178 {
179  if (m_running)
180  {
181  Time tNext (Seconds (m_packetSize * 8 / static_cast<double> (m_dataRate.GetBitRate ())));
182  m_sendEvent = Simulator::Schedule (tNext, &MyApp::SendPacket, this);
183  }
184 }
185 
186 static void
187 CwndChange (Ptr<OutputStreamWrapper> stream, uint32_t oldCwnd, uint32_t newCwnd)
188 {
189  NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\t" << newCwnd);
190  *stream->GetStream () << Simulator::Now ().GetSeconds () << "\t" << oldCwnd << "\t" << newCwnd << std::endl;
191 }
192 
193 static void
195 {
196  NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ());
197  file->Write (Simulator::Now (), p);
198 }
199 
200 int
201 main (int argc, char *argv[])
202 {
203  bool useV6 = false;
204 
206  cmd.AddValue ("useIpv6", "Use Ipv6", useV6);
207  cmd.Parse (argc, argv);
208 
210  nodes.Create (2);
211 
213  pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
214  pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
215 
217  devices = pointToPoint.Install (nodes);
218 
219  Ptr<RateErrorModel> em = CreateObject<RateErrorModel> ();
220  em->SetAttribute ("ErrorRate", DoubleValue (0.00001));
221  devices.Get (1)->SetAttribute ("ReceiveErrorModel", PointerValue (em));
222 
224  stack.Install (nodes);
225 
226  uint16_t sinkPort = 8080;
227  Address sinkAddress;
228  Address anyAddress;
229  std::string probeType;
230  std::string tracePath;
231  if (useV6 == false)
232  {
234  address.SetBase ("10.1.1.0", "255.255.255.0");
236  sinkAddress = InetSocketAddress (interfaces.GetAddress (1), sinkPort);
237  anyAddress = InetSocketAddress (Ipv4Address::GetAny (), sinkPort);
238  probeType = "ns3::Ipv4PacketProbe";
239  tracePath = "/NodeList/*/$ns3::Ipv4L3Protocol/Tx";
240  }
241  else
242  {
244  address.SetBase ("2001:0000:f00d:cafe::", Ipv6Prefix (64));
246  sinkAddress = Inet6SocketAddress (interfaces.GetAddress (1,1), sinkPort);
247  anyAddress = Inet6SocketAddress (Ipv6Address::GetAny (), sinkPort);
248  probeType = "ns3::Ipv6PacketProbe";
249  tracePath = "/NodeList/*/$ns3::Ipv6L3Protocol/Tx";
250  }
251 
252  PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", anyAddress);
253  ApplicationContainer sinkApps = packetSinkHelper.Install (nodes.Get (1));
254  sinkApps.Start (Seconds (0.));
255  sinkApps.Stop (Seconds (20.));
256 
257  Ptr<Socket> ns3TcpSocket = Socket::CreateSocket (nodes.Get (0), TcpSocketFactory::GetTypeId ());
258 
259  Ptr<MyApp> app = CreateObject<MyApp> ();
260  app->Setup (ns3TcpSocket, sinkAddress, 1040, 1000, DataRate ("1Mbps"));
261  nodes.Get (0)->AddApplication (app);
262  app->SetStartTime (Seconds (1.));
263  app->SetStopTime (Seconds (20.));
264 
265  AsciiTraceHelper asciiTraceHelper;
266  Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream ("seventh.cwnd");
267  ns3TcpSocket->TraceConnectWithoutContext ("CongestionWindow", MakeBoundCallback (&CwndChange, stream));
268 
269  PcapHelper pcapHelper;
270  Ptr<PcapFileWrapper> file = pcapHelper.CreateFile ("seventh.pcap", std::ios::out, PcapHelper::DLT_PPP);
271  devices.Get (1)->TraceConnectWithoutContext ("PhyRxDrop", MakeBoundCallback (&RxDrop, file));
272 
273  // Use GnuplotHelper to plot the packet byte count over time
274  GnuplotHelper plotHelper;
275 
276  // Configure the plot. The first argument is the file name prefix
277  // for the output files generated. The second, third, and fourth
278  // arguments are, respectively, the plot title, x-axis, and y-axis labels
279  plotHelper.ConfigurePlot ("seventh-packet-byte-count",
280  "Packet Byte Count vs. Time",
281  "Time (Seconds)",
282  "Packet Byte Count");
283 
284  // Specify the probe type, trace source path (in configuration namespace), and
285  // probe output trace source ("OutputBytes") to plot. The fourth argument
286  // specifies the name of the data series label on the plot. The last
287  // argument formats the plot by specifying where the key should be placed.
288  plotHelper.PlotProbe (probeType,
289  tracePath,
290  "OutputBytes",
291  "Packet Byte Count",
292  GnuplotAggregator::KEY_BELOW);
293 
294  // Use FileHelper to write out the packet byte count over time
295  FileHelper fileHelper;
296 
297  // Configure the file to be written, and the formatting of output data.
298  fileHelper.ConfigureFile ("seventh-packet-byte-count",
299  FileAggregator::FORMATTED);
300 
301  // Set the labels for this formatted output file.
302  fileHelper.Set2dFormat ("Time (Seconds) = %.3e\tPacket Byte Count = %.0f");
303 
304  // Specify the probe type, trace source path (in configuration namespace), and
305  // probe output trace source ("OutputBytes") to write.
306  fileHelper.WriteProbe (probeType,
307  tracePath,
308  "OutputBytes");
309 
310  Simulator::Stop (Seconds (20));
311  Simulator::Run ();
312  Simulator::Destroy ();
313 
314  return 0;
315 }
316 
holds a vector of ns3::Application pointers.
Simulation virtual time values and global simulation resolution.
Definition: nstime.h:102
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
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:1686
double GetSeconds(void) const
Get an approximation of the time stored in this instance in the indicated unit.
Definition: nstime.h:355
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:202
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:249
stack
Definition: first.py:34
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:187
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:25
The base class for all ns3 applications.
Definition: application.h:60
pointToPoint
Definition: first.py:28
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:213
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:37
#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:111
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1014
interfaces
Definition: first.py:41
bool IsRunning(void) const
This method is syntactic sugar for !IsExpired().
Definition: event-id.cc:65
Describes an IPv6 prefix.
Definition: ipv6-address.h:428
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:365
static const uint32_t packetSize
devices
Definition: first.py:32
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:915
static void RxDrop(Ptr< PcapFileWrapper > file, Ptr< const Packet > p)
Definition: seventh.cc:194
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