A Discrete-Event Network Simulator
API
tcp-large-transfer.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
18//
19// Network topology
20//
21// 10Mb/s, 10ms 10Mb/s, 10ms
22// n0-----------------n1-----------------n2
23//
24//
25// - Tracing of queues and packet receptions to file
26// "tcp-large-transfer.tr"
27// - pcap traces also generated in the following files
28// "tcp-large-transfer-$n-$i.pcap" where n and i represent node and interface
29// numbers respectively
30// Usage (e.g.): ./ns3 run tcp-large-transfer
31
32#include <iostream>
33#include <fstream>
34#include <string>
35
36#include "ns3/core-module.h"
37#include "ns3/applications-module.h"
38#include "ns3/network-module.h"
39#include "ns3/internet-module.h"
40#include "ns3/point-to-point-module.h"
41#include "ns3/ipv4-global-routing-helper.h"
42
43using namespace ns3;
44
45NS_LOG_COMPONENT_DEFINE ("TcpLargeTransfer");
46
48static const uint32_t totalTxBytes = 2000000;
51
52// Perform series of 1040 byte writes (this is a multiple of 26 since
53// we want to detect data splicing in the output stream)
55static const uint32_t writeSize = 1040;
57uint8_t data[writeSize];
58
59// These are for starting the writing process, and handling the sending
60// socket's notification upcalls (events). These two together more or less
61// implement a sending "Application", although not a proper ns3::Application
62// subclass.
63
71void StartFlow (Ptr<Socket> localSocket, Ipv4Address servAddress, uint16_t servPort);
72
79void WriteUntilBufferFull (Ptr<Socket> localSocket, uint32_t txSpace);
80
87static void
89{
90 NS_LOG_INFO ("Moving cwnd from " << oldval << " to " << newval);
91}
92
93int 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.
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.
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.
146 Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
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",
162 InetSocketAddress (Ipv4Address::GetAny (), servPort));
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...
174 Ptr<Socket> localSocket =
175 Socket::CreateSocket (n0n1.Get (0), TcpSocketFactory::GetTypeId ());
176 localSocket->Bind ();
177
178 // Trace changes to the congestion window
179 Config::ConnectWithoutContext ("/NodeList/0/$ns3::TcpL4Protocol/SocketList/0/CongestionWindow", MakeCallback (&CwndTracer));
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,
184 ipInterfs.GetAddress (1), servPort);
185
186 // One can toggle the comment for the following line on or off to see the
187 // effects of finite send buffer modelling. One can also change the size of
188 // said buffer.
189
190 //localSocket->SetAttribute("SndBufSize", UintegerValue(4096));
191
192 //Ask for ASCII and pcap traces of network traffic
193 AsciiTraceHelper ascii;
194 p2p.EnableAsciiAll (ascii.CreateFileStream ("tcp-large-transfer.tr"));
195 p2p.EnablePcapAll ("tcp-large-transfer");
196
197 // Finally, set up the simulator to run. The 1000 second hard limit is a
198 // failsafe in case some change above causes the simulation to never end
199 Simulator::Stop (Seconds (1000));
201 Simulator::Destroy ();
202}
203
204
205//-----------------------------------------------------------------------------
206//-----------------------------------------------------------------------------
207//-----------------------------------------------------------------------------
208//begin implementation of sending "Application"
209void StartFlow (Ptr<Socket> localSocket,
210 Ipv4Address servAddress,
211 uint16_t servPort)
212{
213 NS_LOG_LOGIC ("Starting flow at time " << Simulator::Now ().GetSeconds ());
214 localSocket->Connect (InetSocketAddress (servAddress, servPort)); //connect
215
216 // tell the tcp implementation to call WriteUntilBufferFull again
217 // if we blocked and new tx buffer space becomes available
219 WriteUntilBufferFull (localSocket, localSocket->GetTxAvailable ());
220}
221
222void WriteUntilBufferFull (Ptr<Socket> localSocket, uint32_t txSpace)
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}
#define min(a, b)
Definition: 80211b.c:42
NodeContainer n1n2
Nodecontainer n1 + n2.
void Run(ObjectFactory &factory, uint32_t pop, uint32_t total, uint32_t runs, Ptr< RandomVariableStream > eventStream, bool calRev)
Perform the runs for a single scheduler type.
holds a vector of ns3::Application pointers.
void Start(Time start)
Arrange for all of the Applications in this container to Start() at the Time given as a parameter.
void Stop(Time stop)
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:163
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:229
Class for representing data rates.
Definition: data-rate.h:89
AttributeValue implementation for DataRate.
an Inet address class
aggregate IP/TCP/UDP functionality to existing Nodes.
void InstallAll(void) 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:41
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)
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:121
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
virtual int Close(void)=0
Close a socket.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
virtual uint32_t GetTxAvailable(void) const =0
Returns the number of bytes which can be sent in a single call to Send.
AttributeValue implementation for Time.
Definition: nstime.h:1309
void ConnectWithoutContext(std::string path, const CallbackBase &cb)
Definition: config.cc:901
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:205
#define NS_LOG_LOGIC(msg)
Use NS_LOG to output a message of level LOG_LOGIC.
Definition: log.h:289
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:281
Time Now(void)
create an ns3::Time instance which contains the current simulation time.
Definition: simulator.cc:287
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1245
Time MilliSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition: nstime.h:1253
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:661
cmd
Definition: second.py:43
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:56