A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
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
42using namespace ns3;
43
44NS_LOG_COMPONENT_DEFINE("TcpLargeTransfer");
45
46/// The number of bytes to send in this simulation.
47static const uint32_t totalTxBytes = 2000000;
48/// The actual number of sent bytes.
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)
53/// Write size.
54static const uint32_t writeSize = 1040;
55/// Data to be written.
56uint8_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
63/**
64 * Start a flow.
65 *
66 * \param localSocket The local (sending) socket.
67 * \param servAddress The server address.
68 * \param servPort The server port.
69 */
70void StartFlow(Ptr<Socket> localSocket, Ipv4Address servAddress, uint16_t servPort);
71
72/**
73 * Write to the buffer, filling it.
74 *
75 * \param localSocket The socket.
76 * \param txSpace The number of bytes to write.
77 */
78void WriteUntilBufferFull(Ptr<Socket> localSocket, uint32_t txSpace);
79
80/**
81 * Congestion window tracker function.
82 *
83 * \param oldval Old value.
84 * \param newval New value.
85 */
86static void
88{
89 NS_LOG_INFO("Moving cwnd from " << oldval << " to " << newval);
90}
91
92int
93main(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.
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.
136 internet.InstallAll();
137
138 // Later, we add IP addresses.
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
148 ///////////////////////////////////////////////////////////////////////////
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 //
156 ///////////////////////////////////////////////////////////////////////////
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
201
202 return 0;
203}
204
205//-----------------------------------------------------------------------------
206//-----------------------------------------------------------------------------
207//-----------------------------------------------------------------------------
208// begin implementation of sending "Application"
209void
210StartFlow(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
217 localSocket->SetSendCallback(MakeCallback(&WriteUntilBufferFull));
218 WriteUntilBufferFull(localSocket, localSocket->GetTxAvailable());
219}
220
221void
223{
224 while (currentTxBytes < totalTxBytes && localSocket->GetTxAvailable() > 0)
225 {
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}
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.
Manage ASCII trace files for device models.
Definition: trace-helper.h:174
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
Class for representing data rates.
Definition: data-rate.h:89
AttributeValue implementation for DataRate.
Definition: data-rate.h:296
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.
Ipv4 addresses are stored in host order in this class.
Definition: ipv4-address.h:42
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.
Build a set of PointToPointNetDevice objects.
Smart pointer class similar to boost::intrusive_ptr.
Definition: ptr.h:77
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition: simulator.cc:142
static Time Now()
Return the current simulation virtual time.
Definition: simulator.cc:208
static void Run()
Run the simulation.
Definition: simulator.cc:178
static EventId ScheduleNow(FUNC f, Ts &&... args)
Schedule an event to expire Now.
Definition: simulator.h:605
static void Stop()
Tell the Simulator the calling event should be the last one executed.
Definition: simulator.cc:186
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
static TypeId GetTypeId()
Get the type ID.
AttributeValue implementation for Time.
Definition: nstime.h:1406
void ConnectWithoutContext(std::string path, const CallbackBase &cb)
Definition: config.cc:954
#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
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1319
Time MilliSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition: nstime.h:1331
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:706
ns cmd
Definition: second.py:40
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