A Discrete-Event Network Simulator
API
tcp-large-transfer.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 
17 //
18 // Network topology
19 //
20 // 10Mb/s, 10ms 10Mb/s, 10ms
21 // n0-----------------n1-----------------n2
22 //
23 //
24 // - Tracing of queues and packet receptions to file
25 // "tcp-large-transfer.tr"
26 // - pcap traces also generated in the following files
27 // "tcp-large-transfer-$n-$i.pcap" where n and i represent node and interface
28 // numbers respectively
29 // Usage (e.g.): ./ns3 run tcp-large-transfer
30 
31 #include "ns3/applications-module.h"
32 #include "ns3/core-module.h"
33 #include "ns3/internet-module.h"
34 #include "ns3/ipv4-global-routing-helper.h"
35 #include "ns3/network-module.h"
36 #include "ns3/point-to-point-module.h"
37 
38 #include <fstream>
39 #include <iostream>
40 #include <string>
41 
42 using namespace ns3;
43 
44 NS_LOG_COMPONENT_DEFINE("TcpLargeTransfer");
45 
47 static const uint32_t totalTxBytes = 2000000;
49 static uint32_t currentTxBytes = 0;
50 
51 // Perform series of 1040 byte writes (this is a multiple of 26 since
52 // we want to detect data splicing in the output stream)
54 static const uint32_t writeSize = 1040;
56 uint8_t data[writeSize];
57 
58 // These are for starting the writing process, and handling the sending
59 // socket's notification upcalls (events). These two together more or less
60 // implement a sending "Application", although not a proper ns3::Application
61 // subclass.
62 
70 void StartFlow(Ptr<Socket> localSocket, Ipv4Address servAddress, uint16_t servPort);
71 
78 void WriteUntilBufferFull(Ptr<Socket> localSocket, uint32_t txSpace);
79 
86 static void
87 CwndTracer(uint32_t oldval, uint32_t newval)
88 {
89  NS_LOG_INFO("Moving cwnd from " << oldval << " to " << newval);
90 }
91 
92 int
93 main(int argc, char* argv[])
94 {
95  // Users may find it convenient to turn on explicit debugging
96  // for selected modules; the below lines suggest how to do this
97  // LogComponentEnable("TcpL4Protocol", LOG_LEVEL_ALL);
98  // LogComponentEnable("TcpSocketImpl", LOG_LEVEL_ALL);
99  // LogComponentEnable("PacketSink", LOG_LEVEL_ALL);
100  // LogComponentEnable("TcpLargeTransfer", LOG_LEVEL_ALL);
101 
102  CommandLine cmd(__FILE__);
103  cmd.Parse(argc, argv);
104 
105  // initialize the tx buffer.
106  for (uint32_t i = 0; i < writeSize; ++i)
107  {
108  char m = toascii(97 + i % 26);
109  data[i] = m;
110  }
111 
112  // Here, we will explicitly create three nodes. The first container contains
113  // nodes 0 and 1 from the diagram above, and the second one contains nodes
114  // 1 and 2. This reflects the channel connectivity, and will be used to
115  // install the network interfaces and connect them with a channel.
116  NodeContainer n0n1;
117  n0n1.Create(2);
118 
120  n1n2.Add(n0n1.Get(1));
121  n1n2.Create(1);
122 
123  // We create the channels first without any IP addressing information
124  // First make and configure the helper, so that it will put the appropriate
125  // attributes on the network interfaces and channels we are about to install.
126  PointToPointHelper p2p;
127  p2p.SetDeviceAttribute("DataRate", DataRateValue(DataRate(10000000)));
128  p2p.SetChannelAttribute("Delay", TimeValue(MilliSeconds(10)));
129 
130  // And then install devices and channels connecting our topology.
131  NetDeviceContainer dev0 = p2p.Install(n0n1);
132  NetDeviceContainer dev1 = p2p.Install(n1n2);
133 
134  // Now add ip/tcp stack to all nodes.
135  InternetStackHelper internet;
136  internet.InstallAll();
137 
138  // Later, we add IP addresses.
139  Ipv4AddressHelper ipv4;
140  ipv4.SetBase("10.1.3.0", "255.255.255.0");
141  ipv4.Assign(dev0);
142  ipv4.SetBase("10.1.2.0", "255.255.255.0");
143  Ipv4InterfaceContainer ipInterfs = ipv4.Assign(dev1);
144 
145  // and setup ip routing tables to get total ip-level connectivity.
147 
149  // Simulation 1
150  //
151  // Send 2000000 bytes over a connection to server port 50000 at time 0
152  // Should observe SYN exchange, a lot of data segments and ACKS, and FIN
153  // exchange. FIN exchange isn't quite compliant with TCP spec (see release
154  // notes for more info)
155  //
157 
158  uint16_t servPort = 50000;
159 
160  // Create a packet sink to receive these packets on n2...
161  PacketSinkHelper sink("ns3::TcpSocketFactory",
163 
164  ApplicationContainer apps = sink.Install(n1n2.Get(1));
165  apps.Start(Seconds(0.0));
166  apps.Stop(Seconds(3.0));
167 
168  // Create a source to send packets from n0. Instead of a full Application
169  // and the helper APIs you might see in other example files, this example
170  // will use sockets directly and register some socket callbacks as a sending
171  // "Application".
172 
173  // Create and bind the socket...
175  localSocket->Bind();
176 
177  // Trace changes to the congestion window
178  Config::ConnectWithoutContext("/NodeList/0/$ns3::TcpL4Protocol/SocketList/0/CongestionWindow",
180 
181  // ...and schedule the sending "Application"; This is similar to what an
182  // ns3::Application subclass would do internally.
183  Simulator::ScheduleNow(&StartFlow, localSocket, ipInterfs.GetAddress(1), servPort);
184 
185  // One can toggle the comment for the following line on or off to see the
186  // effects of finite send buffer modelling. One can also change the size of
187  // said buffer.
188 
189  // localSocket->SetAttribute("SndBufSize", UintegerValue(4096));
190 
191  // Ask for ASCII and pcap traces of network traffic
192  AsciiTraceHelper ascii;
193  p2p.EnableAsciiAll(ascii.CreateFileStream("tcp-large-transfer.tr"));
194  p2p.EnablePcapAll("tcp-large-transfer");
195 
196  // Finally, set up the simulator to run. The 1000 second hard limit is a
197  // failsafe in case some change above causes the simulation to never end
198  Simulator::Stop(Seconds(1000));
199  Simulator::Run();
201 
202  return 0;
203 }
204 
205 //-----------------------------------------------------------------------------
206 //-----------------------------------------------------------------------------
207 //-----------------------------------------------------------------------------
208 // begin implementation of sending "Application"
209 void
210 StartFlow(Ptr<Socket> localSocket, Ipv4Address servAddress, uint16_t servPort)
211 {
212  NS_LOG_LOGIC("Starting flow at time " << Simulator::Now().GetSeconds());
213  localSocket->Connect(InetSocketAddress(servAddress, servPort)); // connect
214 
215  // tell the tcp implementation to call WriteUntilBufferFull again
216  // if we blocked and new tx buffer space becomes available
218  WriteUntilBufferFull(localSocket, localSocket->GetTxAvailable());
219 }
220 
221 void
222 WriteUntilBufferFull(Ptr<Socket> localSocket, uint32_t txSpace)
223 {
224  while (currentTxBytes < totalTxBytes && localSocket->GetTxAvailable() > 0)
225  {
226  uint32_t left = totalTxBytes - currentTxBytes;
227  uint32_t dataOffset = currentTxBytes % writeSize;
228  uint32_t toWrite = writeSize - dataOffset;
229  toWrite = std::min(toWrite, left);
230  toWrite = std::min(toWrite, localSocket->GetTxAvailable());
231  int amountSent = localSocket->Send(&data[dataOffset], toWrite, 0);
232  if (amountSent < 0)
233  {
234  // we will be called again when new tx space becomes available.
235  return;
236  }
237  currentTxBytes += amountSent;
238  }
240  {
241  localSocket->Close();
242  }
243 }
#define min(a, b)
Definition: 80211b.c:42
NodeContainer n1n2
Nodecontainer n1 + n2.
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.
void EnableAsciiAll(std::string prefix)
Enable ascii trace output on each device (which is of the appropriate type) in the set of all nodes c...
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
AttributeValue implementation for DataRate.
an Inet address class
aggregate IP/TCP/UDP functionality to existing Nodes.
void InstallAll() const
Aggregate IPv4, IPv6, UDP, and TCP stacks to all nodes in the simulation.
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
void SetBase(Ipv4Address network, Ipv4Mask mask, Ipv4Address base="0.0.0.1")
Set the base network number, network mask and base address.
Ipv4InterfaceContainer Assign(const NetDeviceContainer &c)
Assign IP addresses to the net devices specified in the container based on the current network prefix...
Ipv4 addresses are stored in host order in this class.
Definition: ipv4-address.h:43
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.
Ipv4Address GetAddress(uint32_t i, uint32_t j=0) const
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.
void Add(const NodeContainer &nc)
Append the contents of another NodeContainer to the end of this container.
Ptr< Node > Get(uint32_t i) const
Get the Ptr<Node> stored in this container at a given index.
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)
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition: simulator.cc:140
static Time Now()
Return the current simulation virtual time.
Definition: simulator.cc:199
static void Run()
Run the simulation.
Definition: simulator.cc:176
static EventId ScheduleNow(FUNC f, Ts &&... args)
Schedule an event to expire Now.
Definition: simulator.h:606
static void Stop()
Tell the Simulator the calling event should be the last one executed.
Definition: simulator.cc:184
virtual int Send(Ptr< Packet > p, uint32_t flags)=0
Send data (or dummy data) to the remote host.
void SetSendCallback(Callback< void, Ptr< Socket >, uint32_t > sendCb)
Notify application when space in transmit buffer is added.
Definition: socket.cc:119
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
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:72
virtual int Close()=0
Close a socket.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
virtual uint32_t GetTxAvailable() const =0
Returns the number of bytes which can be sent in a single call to Send.
static TypeId GetTypeId()
Get the type ID.
AttributeValue implementation for Time.
Definition: nstime.h:1423
void ConnectWithoutContext(std::string path, const CallbackBase &cb)
Definition: config.cc:951
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:202
#define NS_LOG_LOGIC(msg)
Use NS_LOG to output a message of level LOG_LOGIC.
Definition: log.h:282
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:275
void(* DataRate)(DataRate oldValue, DataRate newValue)
TracedValue callback signature for DataRate.
Definition: data-rate.h:328
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1336
Time MilliSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition: nstime.h:1348
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:707
cmd
Definition: second.py:33
static const uint32_t totalTxBytes
The number of bytes to send in this simulation.
void StartFlow(Ptr< Socket > localSocket, Ipv4Address servAddress, uint16_t servPort)
Start a flow.
static const uint32_t writeSize
Write size.
static uint32_t currentTxBytes
The actual number of sent bytes.
static void CwndTracer(uint32_t oldval, uint32_t newval)
Congestion window tracker function.
uint8_t data[writeSize]
Data to be written.
void WriteUntilBufferFull(Ptr< Socket > localSocket, uint32_t txSpace)
Write to the buffer, filling it.
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition: wifi-tcp.cc:55