Session 1. NS-3 개요( 환경 구축 및 transport layer model)
이옥환 , 신연철 Multimedia & Wireless Networking Laboratory, SNU
Contents Introduction to NS-3 Starting simulation Conceptual overview Tweaking Transport layer model Tracing system TCP Congestion Window tracing example
Introduction to NS-3
NS-3 NS-3 is targeted at networking research.
Discrete event simulator
Packet level simulator
Layered architecture
Wired and wireless network
NS-3 Status Periodic update
Latest version is ns-3.18
Supporting platform FreeBSD, Linux, SunOS, Solaris, Windows (Cygwin)
Free, open source software project
Website http://www.nsnam.org/ Can find the doxygen, reference manual, and tutorial
NS-3 vs. NS-2 Limitations of NS-2
Complicated architecture C++, Otcl
Simplified layers 2, 3, and applications Single network interface for each node
Advantages of NS-3 Simple architecture
C++ (Can run NS-3 without any knowledge of Python) Provides realistic implementations
NS-3 is not an extension of NS-2
NS-3 Components NS-3 simulator
Pre-processing Traffic / topology generation Alignment with real systems (sockets, device driver
interfaces)
Post-processing NS-3 output file (trace file) analysis
Throughput, delay, jitter, drop Various tracing system Graph
xgraph, gnuplot
NS-3 all-in-one package Directory Structure
ns-allinone-3.13
ns-3.13 nsc-0.5.2Pybindgen-0.15.0.795
bindings examplesdoc src
. . .
. . .
error-model
mobility
. . .
. . .
network
csma
. . .
scratch
Example simulation
scripts
Starting NS-3 Simulation
How to Download NS-3 Ns-3 download: http://www.nsnam.org/ns-3-15/download/
[user@com ~]# tar xvf ns-allinone-3.15.tar.bz2 [user@com ~]# cd ns-allinone-3.15
Ns-3 download using mercurial: [user@com ~]# hg clone http://code.nsnam.org/ns-3-allinone [user@com ~]# cd ns-3-allinone [user@com ~]# ./download.py -n ns-3.15
How to Install NS-3 Building
[user@com ~/ns-allinone-3.15]# ./build.py
Setting environment [user@com~/ns-allinone-3.15/ns-3.15]# ./waf –d optimized configure [user@com ~/ns-allinone-3.15/ns-3.15]# ./waf -d debug --enable-examples
--enable-tests configure [user@com ~/ns-allinone-3.15/ns-3.15]# ./waf [user@com ~/ns-allinone-3.15/ns-3.15]# ./test.py –c core
Simple Example cd ns-allinone-3.15/ns-3.15 /ns-3.15$ ./waf --run scratch/scratch-simulator
Output
Workspace
/ns-allinone-3.15/ns-3.15/scratch
Run program only in the scratch folder
Run program by the commands below ./waf --run scratch/example (or) ./waf --run example
NS-3 in Windows
Officially supported Virtualization products (VirtualBox, Vmware) How to run simulations using VirtualBox
http://www.nsnam.org/wiki/index.php/HOWTO_use_VirtualBox_to_run_simulations_on_Windows_machines
How to run simulations using VMware http://www.nsnam.org/wiki/index.php/HOWTO_use_VM
ware_to_set_up_virtual_networks_(Windows)
Cygwin was supported in the past There might be some problems
Conceptual Overview of NS-3
1. Key Abstractions2. Simulation Procedure3. Simulation Example
Key Abstractions1.Node Host, end system in the Internet Basic computing device abstraction Represented in C++ by the class Node
2.Application A user program that generates some activity to be simulated NS-3 applications run on ns-3 Nodes to drive simulations Represented in C++ by the class Application Ex)OnOffApplication, UdpEchoClientApplication
3.Channel Medium connected by nodes over which data flows Represented in C++ by the class Channel Ex) CsmaChannel, PointToPointChannel, WifiChannel
Key Abstractions
4. Net device Like a specific kind of network cable and a hardware device
(Network Interface Cards; NICs) NICs are controlled using the software driver, net devices Represented in C++ by the class NetDevice Provides methods for managing connection to Node and Channel Ex) CsmaNetDevice (work with CsmaChannel)
WifiNetDevice (work with WifiChannel)
5. Topology helpers Topology helpers make ns-3 core operations as easy as possible Create a NetDevice, add an address, install that net device on a
Node, configure the node’s protocol stack and connect the NetDevice to a Channel
Topology HelpersI. NodeContainer: Provide a convenient way to create, manage and
access any Node object
II. PointToPointHelper: Configure and connect PointToPointNetDevice and PointToPointChannel objects. Set DataRate on NetDevices and Delay on Channel
III. NetDeviceContainer: To install NetDevice at the nodes and create Channel between the nodes
IV. InternetStackHelper: To install an Internet Stack (TCP, UDP, IP, etc.) on each of the nodes in the node container
V. Ipv4AddressHelper: Manage the allocation of IP address and assign addresses to the devices using Ipv4InterfaceContainer
NS-3 Basic Simulation Model
Application Application
Protocol stack
Node
NetDevice NetDevice
Application Application
Protocol stack
Node
NetDevice NetDevice
Sockets-like API
Channel
Channel
Packet(s)
Simulation Procedure
1. Turning on logging
2. Creating network topology
3. Creating application
4. Running simulator
Simulation Procedure-1. Turning on logging -
Define log component NS_LOG_COMPONENT_DEFINE ( name )
Enable log component LogComponentEnable ( name, level )
Simulation Procedure- 2. Creating Network Topology -
Use Topology Helpers
NodeContainer NodeContainer Ptr<Node> NodeContainer::Create (n) n: # of Nodes Example)
NodeContainer nodes;nodes.Create (2);
Simulation Procedure- 2. Creating Network Topology -
PointToPointHelper void PointToPointHelper::SetDeviceAttribute (name, value) void PointToPointHelper::SetChannelAttribute (name, value) NetDeviceContainer PointToPointHelper::Install (NodeContainer c)
NetDeviceContainer NetDeviceContainer Ptr<NetDevice>
ExamplePointToPointHelper pointToPoint;pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));NetDeviceContainer devices;devices = pointToPoint.Install (nodes);
Simulation Procedure- 3. Creating application -
UdpEchoServerHelper UdpEchoServerHelper::UdpEchoServerHelper ( port ) ApplicationContainer UdpEchoServerHelper::Install (NodeContainer c )
UdpEchoClientHelper UdpEchoClientHelper::UdpEchoClientHelper ( ip, port ) void UdpEchoClientHelper::Setattribute ( name, value ) ApplicationContainer UdpEchoClientHelper::Install (NodeContainer c )
ExampleUdpEchoServerHelper echoServer (9);
ApplicationContainer serverApps = echoServer.Install (nodes.Get (1));serverApps.Start (Seconds (1.0));serverApps.Stop (Seconds (10.0));
UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9);echoClient.SetAttribute ("MaxPackets", UintegerValue (1));echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0)));echoClient.SetAttribute ("PacketSize", UintegerValue (1024));ApplicationContainer clientApps = echoClient.Install (nodes.Get (0));clientApps.Start (Seconds (2.0));clientApps.Stop (Seconds (10.0));
Simulation Procedure- 4. Running simulator-
Start Simulator Simulator::Run ();
Destroy Simulator Simulator::Destroy ();
Simulation Example
UDP EchoClient10.1.1.1
UDP EchoServer
10.1.1.2P2P interface P2P interface
Transmit a packet at 1s
Upon receiving the packet, echo it
Data rate: 5Mbps, Delay: 2ms
Simulation Example (1/3)
#include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/internet-module.h" #include "ns3/point-to-point-module.h" #include "ns3/applications-module.h"
using namespace ns3; NS_LOG_COMPONENT_DEFINE ("FirstScriptExample"); int main (int argc, char *argv[])
{ LogComponentEnable("UdpEchoClientApplication", LOG_LEVEL_INFO); LogComponentEnable("UdpEchoServerApplication", LOG_LEVEL_INFO); NodeContainer nodes; nodes.Create (2); PointToPointHelper pointToPoint; pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms")); NetDeviceContainer devices; devices = pointToPoint.Install (nodes);
• Simple point-to-point link between two nodes and echo a single packet
Simulation Example (2/3) InternetStackHelper stack; stack.Install (nodes); Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer interfaces = address.Assign (devices); UdpEchoServerHelper echoServer (9); ApplicationContainer serverApps = echoServer.Install (nodes.Get (1)); serverApps.Start (Seconds (1.0)); serverApps.Stop (Seconds (10.0)); UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9); echoClient.SetAttribute ("MaxPackets", UintegerValue (1)); echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0))); echoClient.SetAttribute ("PacketSize", UintegerValue (1024)); ApplicationContainer clientApps = echoClient.Install (nodes.Get (0)); clientApps.Start (Seconds (2.0)); clientApps.Stop (Seconds (10.0)); Simulator::Run (); Simulator::Destroy (); return 0; }
Simulation Example (3/3)
../ns-3.15] ./waf –-run scratch/example1
OutputSent 1024 bytes to 10.1.1.2Received 1024 bytes from 10.1.1.1Received 1024 bytes from 10.1.1.2
Tweaking1. Logging Modules2. Command Line Arguments3. Tracing System
Logging Module Output messages from modules Useful when debugging NS_LOG environment variable NS_LOG_FUNCTION level information Verbosity level
NS LOG ERROR — Log error messages; NS LOG WARN — Log warning messages; NS LOG DEBUG — Log relatively rare debugging messages; NS LOG INFO — Log informational messages about program progress; NS LOG FUNCTION — Log a message describing each function called; NS LOG LOGIC – Log messages describing logical flow within a function; NS LOG ALL — Log everything. NS LOG UNCOND – Log the associated message unconditionally.
Logging Module Example 1
$ export NS_LOG=UdpEchoClientApplication=level_all $ ./waf --run scratch/example1
Output:’build’ finished successfully (0.404s)UdpEchoClientApplication:UdpEchoClient()UdpEchoClientApplication:SetDataSize(1024)UdpEchoClientApplication:StartApplication()UdpEchoClientApplication:ScheduleTransmit()UdpEchoClientApplication:Send()Sent 1024 bytes to 10.1.1.2Received 1024 bytes from 10.1.1.1UdpEchoClientApplication:HandleRead(0x6241e0, 0x624a20)Received 1024 bytes from 10.1.1.2UdpEchoClientApplication:StopApplication()UdpEchoClientApplication:DoDispose()UdpEchoClientApplication:~UdpEchoClient()
Logging Module Example 2
$ export ‘NS_LOG=UdpEchoClientApplication=level_all|prefix_func|prefix_time’ $ ./waf --run scratch/example1
Output:
0s UdpEchoClientApplication:UdpEchoClient()0s UdpEchoClientApplication:SetDataSize(1024)2s UdpEchoClientApplication:StartApplication()2s UdpEchoClientApplication:ScheduleTransmit()2s UdpEchoClientApplication:Send()2s UdpEchoClientApplication:Send(): Sent 1024 bytes to 10.1.1.2Received 1024 bytes from 10.1.1.12.00737s UdpEchoClientApplication:HandleRead(0x9aead30, 0x9aeb378)2.00737s UdpEchoClientApplication:HandleRead(): Received 1024 bytes from 10.1.1.210s UdpEchoClientApplication:StopApplication()UdpEchoClientApplication:DoDispose()UdpEchoClientApplication:~UdpEchoClient()
Logging Module Example 3
$ export ‘NS_LOG=*=level_all|prefix_func|prefix_time’ $ ./waf --run scratch/example1
It prints out all of the logging ./waf –-run scratch/example1 > log.out 2>&1 2>&1 : stderr > stdout
Example 4 Adding logging to your code
NS_LOG_INFO (“Creating Topology”) in your source code $ export NS_LOG=FirstScriptExample=info ./waf --run scratch/example1
Command Line Arguments Change the simulation parameters using command line
arguments
First declare the command line parser in main functionCommandLine cmd;cmd.Parse (argc, argv);
Example ./waf --run "scratch/example1 –PrintHelp” ./waf –-run “scratch/example1 –
PrintAttributes=ns3::PointToPointNetDevice” ./waf --run “scratch/example1 -
ns3::PointToPointNetDevice::DataRate=5Mbps –ns3::PointToPointChannel::Delay=2ms”
Command Line Arguments When add your own hooks.
cmd.AddValue in main function
Exampleint main (int argc, char *argv[]){
uint32_t nPackets =1;
CommandLine cmd;cmd.AddValue("nPackets", "Number of packets to echo", nPackets);Cmd.Parse (argc, argv);
…echoClient.SetAttribute (“MaxPackets”, UintegerValue (nPackets));
./waf --run “scratch/example1 –nPackets=2”
Tracing System
Tracing is a structured form of simulation output
Tracing System ASCII Tracing
Trace file similar to that of NS-2
AsciiTraceHelper ascii;pointToPoint.EnableAsciiAll (ascii.CreateFileStream(“myfirst.tr”));
Simulator::Run (); Simulator::Destroy (); return 0;
Output (myfirst.tr)+ 2 /NodeList/0/DeviceList/0/$ns3::PointToPointNetDevice/TxQueue/Enqueue ns3::PppHeader (Point-to-Point Protocol: IP (0x0021)) ns3::Ipv4Header (tos 0x0 ttl 64 id 0 protocol 17 offset 0 flags [none] length: 1052 10.1.1.1 > 10.1.1.2) ns3::UdpHeader (length: 1032 49153 > 9) Payload (size=1024)- 2 /NodeList/0/DeviceList/0/$ns3::PointToPointNetDevice/TxQueue/Dequeue ns3::PppHeader (Point-to-Point Protocol: IP (0x0021)) ns3::Ipv4Header (tos 0x0 ttl 64 id 0 protocol 17 offset 0 flags [none] length: 1052 10.1.1.1 > 10.1.1.2) ns3::UdpHeader (length: 1032 49153 > 9) Payload (size=1024)
…
Tracing System Trace file format
00 +01 202 /NodeList/0/DeviceList/0/$ns3::PointToPointNetDevice/TxQueue/Enqueue03 ns3::PppHeader (04 Point-to-Point Protocol: IP (0x0021))05 ns3::Ipv4Header (06 tos 0x0 ttl 64 id 0 protocol 17 offset 0 flags [none]07 length: 1052 10.1.1.1 > 10.1.1.2)08 ns3::UdpHeader (09 length: 1032 49153 > 9)10 Payload (size=1024)
Tracing System PCAP Tracing
.pcap file format Traffic trace analyze pointToPoint.EnablePcapAll (“myfirst”);
Reading output with tcpdump$ tcpdump -nn -tt -r myfirst-0-0.pcapreading from file myfirst-0-0.pcap, link-type PPP (PPP)2.000000 IP 10.1.1.1.49153 > 10.1.1.2.9: UDP, length 10242.514648 IP 10.1.1.2.9 > 10.1.1.1.49153: UDP, length 1024
$ tcpdump -nn -tt -r myfirst-1-0.pcapreading from file myfirst-1-0.pcap, link-type PPP (PPP)2.257324 IP 10.1.1.1.49153 > 10.1.1.2.9: UDP, length 10242.257324 IP 10.1.1.2.9 > 10.1.1.1.49153: UDP, length 1024
Tracing System Reading output with Wireshark http://www.wireshark.org/download.html
Summary of Tweaking 1. Logging Module
Used to output debug messages based on the pre-defined log component
2. Command Line Argument Change parameters without direct modification of main source
code
3. Tracing System Used to generate output for checking the operation and measure
the system performance Use trace source and trace sink (we study the tracing system
further in the 2nd class)
Transport Layer Model in NS-3
TCP Models in NS-3 NS-3 was written to support multiple TCP implementations
Two important abstract base classes Class TcpSocket
Defined in src/node/tcp-socket.{cc,h} Class TcpSocketFactory
Used by applications to create TCP sockets
Limitations Only Tahoe congestion control Limited IPv6 support
TcpSocket Class Attributes
SndBufSize: TcpSocket maximum transmit buffer size (bytes) Set with class: ns3::UintegerValue Underlying type: uint32_t / Initial value: 131072
RcvBufSize: TcpSocket maximum receive buffer size (bytes) Set with class: ns3::UintegerValue Underlying type: uint32_t / Initial value: 131072
SegmentSize: TCP maximum segment size in bytes (may be adjusted based on MTU discovery)
Set with class: ns3::UintegerValue Underlying type: uint32_t / Initial value: 536
SlowStartThreshold: TCP slow start threshold (bytes) Set with class: ns3::UintegerValue Underlying type: uint32_t / Initial value: 65535
InitialCwnd: TCP initial congestion window size (segments) Set with class: ns3::UintegerValue Underlying type: uint32_t / Initial value: 1
ConnTimeout: TCP retransmission timeout when opening connection (seconds)
Set with class: TimeValue Underlying type: Time / Initial value: +3000000000.0ns
ConnCount: Number of connection attempts (SYN retransmissions) before returning failure
Set with class: ns3::UintegerValue Underlying type: uint32_t / Initial value: 6
DelAckTimeout: Timeout value for TCP delayed acks, in seconds Set with class: TimeValue Underlying type: Time / Initial value: +200000000.0ns
DelAckCount: Number of packets to wait before sending a TCP ack Set with class: ns3::UintegerValue Underlying type: uint32_t / Initial value: 2
PersistTimeout: Persist timeout to probe for rx window Set with class: TimeValue Underlying type: Time / Initial value: +6000000000.0ns
TcpSocket Class Attributes
UDP Models in NS-3 Two important abstract base classes
Class UdpSocket Defined in src/node/udp-socket.{cc,h}
Class UdpSocketFactory Used by applications to create UDP sockets.
* Attributes RcvBufSize: UdpSocket maximum receive buffer size (bytes)
Set with class: ns3::UintegerValue Underlying type: uint32_t / Initial value: 131072
IpTtl: socket-specific TTL for unicast IP packets (if non-zero) Set with class: ns3::UintegerValue Underlying type: uint8_t / Initial value: 0
IpMulticastTtl: socket-specific TTL for multicast IP packets (if non-zero) Set with class: ns3::UintegerValue Underlying type: uint8_t / Initial value: 0
IpMulticastIf: interface index for outgoing multicast on this socket; -1 indicates to use default interface Set with class: ns3::IntegerValue Underlying type: int32_t / Initial value: -1
IpMulticastLoop: whether outgoing multicast sent also to loopback interface Set with class: BooleanValue Underlying type: bool / Initial value: false
MtuDiscover: If enabled, every outgoing ip packet will have the DF flag set. Set with class: BooleanValue Underlying type: bool / Initial value: false
SocketFactory Class Object to create transport layer instances that provide a socket API to applications
Public Member Functions virtual Ptr< Socket > CreateSocket (void)=0
Static Public Member Functions static TypeId GetTypeId (void)
This method returns the TypeId associated to ns3::SocketFactory
Tracing System
1. Tracing overview2. Callback3. How to Find and Connect The Trace Source4. Mid, high-level tracing
Tracing Overview Concept: Independent tracing sources and tracing sinks along with a
uniform mechanism for connecting sources to sinks
Trace sources Entities that can signal events and provide access to interesting data (indicate when a
packet is received or when an interesting state change happens) Generator of events
Trace sinks: Entities that consume trace information
Simulator provides a set of pre-configured trace sources
Trace source is a kind of point-to-multipoint information link One trace source can be connected by several trace sinks
Callback and Low-Level Tracing Callback
The object is to allow a piece of code to call a function without any specific inter-module dependency
Treat the address of the called function as a variable, i.e. a pointer-to-function variable
Decouple the calling function from the called class completely
Relation between tracing system and callback A trace source is a callback When a trace sink wants to know information given by a trace source, it
adds its own function to the callback list.
For the further study of the callbacks, it is good to refer callback part in ns-3 manual pp.12-14.
Simple Low-level Tracing Example (1/2)#include "ns3/object.h"#include "ns3/uinteger.h"#include "ns3/traced-value.h"#include "ns3/trace-source-accessor.h"#include <iostream>
using namespace ns3;class MyObject : public Object{public: static TypeId GetTypeId (void) { static TypeId tid = TypeId ("MyObject") .SetParent (Object::GetTypeId ()) .AddConstructor<MyObject> () .AddTraceSource ("MyInteger",
"An integer value to trace.", MakeTraceSourceAccessor (&MyObject::m_myInt)) ; return tid; } MyObject () {} TracedValue<int32_t> m_myInt;};
Provides the “hooks” used for connecting the trace source to the outside the config system
Provides the infrastructure that overloads the operators and drives callback process
Simple Low-level Tracing Example (2/2)
voidIntTrace (int32_t oldValue, int32_t newValue){std::cout << "Traced " << oldValue << " to " << newValue << std::endl;}
intmain (int argc, char *argv[]){ Ptr<MyObject> myObject = CreateObject<MyObject> (); myObject->TraceConnectWithoutContext ("MyInteger", MakeCallback(&IntTrace)); myObject->m_myInt = 1234;}
Trace sink; callback function: this function will be called whenever the overloaded operators of the TracedValue is excuted
Connect between trace source and trace sink
Operator”=” invoke the Callback
TypeId in Simple Low-level Tracing Example
.AddTraceSource ("MyInteger", "An integer value to trace.",
MakeTraceSourceAccessor (&MyObject::m_myInt))
Config Subsystem Tracing
Config path (the context) Path of predefined trace source Represents a chain of Object pointers Ex) /NodeList/7/$ns3::MobilityModel/CourseChange
Config subsystem is used to allow selecting a trace source in the config path
void ns3::Config::Connect(std::string path,const CallbackBase & cb )
Config Subsystem Tracing ExamplevoidCourseChange (std::string context, Ptr<const MobilityModel> model){ Vector position = model->GetPosition (); NS_LOG_UNCOND (context << " x = " << position.x << ", y = " << position.y);}
//Trace Sink
std::ostringstream oss;oss << "/NodeList/" << wifiStaNodes.Get (nWifi - 1)->GetId () << "/$ns3::MobilityModel/CourseChange";
//Config Path
Config::Connect (oss.str (), MakeCallback (&CourseChange));
//Connection between Trace Source and Sink
Output Result:/NodeList/7/$ns3::MobilityModel/CourseChange x = 7.27897, y = 2.22677…
How to Find and Connect The Trace Source
I. How to find out what trace sources are available.
II. How to figure out the config path to use to connect to the trace source.
III. How to figure out what the return type and formal arguments of the callback function
1. What Trace Sources are Available?
NS-3 Doxygen (http://www.nsnam.org/doxygen-release/index.html)
2. Figure out the Config Path to use to connect to the trace source
Find existing implementation within example codes
Using find & grep command We want to find the examples which contain “CourseChange” and
“Connect”
find . –name ‘*.cc’ | xargs grep CourseChange | grep Connect
3. What are the return type and formal arguments of the callback function?
The return value of callback: void
The return value of callback: void
Config::ConnectWithoutContext void ns3::Config::ConnectWithoutContext (std::string path, const CallbackBase & cb)
path a path to match trace sources cb the callback to connect to the matching trace sources
To find all trace sources which match the input path and will connect the input callback to them
Config::Connect void ns3::Config::Connect (std::string path, const CallbackBase & cb)
path a path to match trace sources cb the callback to connect to the matching trace sources
To find all trace sources which match the input path and will connect the input callback to them in such a way that the callback will receive an extra context string upon trace event notification
3. What are the return type and formal arguments of the callback function?
What about TracedValue? TracedValue is templated src/core/model/traced-value.h
The set code will fire the m_cb callback with two parameters
The callback, m_cb is declared as a TraceCallback<T, T>
3. What are the return type and formal arguments of the callback function?
To customized how information is extracted and saved
To control the amount output, save data to a file and refer back to it later
Use the mid-level trace helpers to do that
Using Mid-level Helpers
High-level of tracing
Control the collection of pre-defined outputs to a fine granularity
All helpers provide ascii and pcap trace sinks Ascii Tracing Device Helpers Pcap Tracing Device Helpers
src/network/helper/trace-helper.h
TCP Congestion Window Tracing Example
Topology
CongestionWindow Trace Source Which class contains CongestionWindow as a trace source?
CongestionWindow Trace Source src/internet/model/tcp-tahoe.cc src/internet/model/tcp-tahoe.h
What Script to Use? Find the proper example
find . –name ‘*.cc’ | xargs grep CongestionWindow
Find the proper example find . –name ‘*.cc’ | xargs grep m_cWnd
Example Code (1/3)#include <fstream>#include "ns3/core-module.h“#include "ns3/network-module.h“#include "ns3/internet-module.h“#include "ns3/point-to-point-module.h“#include "ns3/applications-module.h“
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("FifthScriptExample");
class MyApp : public Application {public:
MyApp (); virtual ~MyApp();
void Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate);
private: virtual void StartApplication (void); virtual void StopApplication (void);
void ScheduleTx (void); void SendPacket (void);
Ptr<Socket> m_socket; Address m_peer; uint32_t m_packetSize; uint32_t m_nPackets; DataRate m_dataRate; EventId m_sendEvent; bool m_running; uint32_t m_packetsSent;};
MyApp::MyApp () : m_socket (0), m_peer (), m_packetSize (0), m_nPackets (0), m_dataRate (0), m_sendEvent (), m_running (false), m_packetsSent (0){}
MyApp::~MyApp(){ m_socket = 0;}
voidMyApp::Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, uint32_t nPackets, DataRate dataRate){ m_socket = socket; m_peer = address; m_packetSize = packetSize; m_nPackets = nPackets; m_dataRate = dataRate;}
voidMyApp::StartApplication (void){ m_running = true; m_packetsSent = 0; m_socket->Bind (); m_socket->Connect (m_peer); SendPacket ();}
Create a simple application
ns-allinone-3.12.1/ns-3.12.1/examples/tutorial/fifth.cc
Example Code (2/3)void MyApp::StopApplication (void){ m_running = false;
if (m_sendEvent.IsRunning ()) { Simulator::Cancel (m_sendEvent); }
if (m_socket) { m_socket->Close (); }}
void MyApp::SendPacket (void){ Ptr<Packet> packet = Create<Packet> (m_packetSize); m_socket->Send (packet);
if (++m_packetsSent < m_nPackets) { ScheduleTx (); }}
void MyApp::ScheduleTx (void){ if (m_running) { Time tNext (Seconds (m_packetSize * 8 /
static_cast<double> (m_dataRate.GetBitRate ()))); m_sendEvent = Simulator::Schedule (tNext,
&MyApp::SendPacket, this); }}
static voidCwndChange (uint32_t oldCwnd, uint32_t newCwnd){ NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\t" << newCwnd);}
static voidRxDrop (Ptr<const Packet> p){ NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ());}
int main (int argc, char *argv[]){ NodeContainer nodes; nodes.Create (2);
PointToPointHelper pointToPoint; pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer devices; devices = pointToPoint.Install (nodes);
Ptr<RateErrorModel> em = CreateObjectWithAttributes<RateErrorModel> ( "RanVar", RandomVariableValue (UniformVariable (0., 1.)), "ErrorRate", DoubleValue (0.00001)); devices.Get (1)->SetAttribute ("ReceiveErrorModel", PointerValue (em));
InternetStackHelper stack; stack.Install (nodes);
Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.252"); Ipv4InterfaceContainer interfaces = address.Assign (devices);
Trace sink
Create network topology and error model
Example Code (3/3) uint16_t sinkPort = 8080; Address sinkAddress
(InetSocketAddress(interfaces.GetAddress (1), sinkPort));
PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), sinkPort));
ApplicationContainer sinkApps = packetSinkHelper.Install (nodes.Get (1));
sinkApps.Start (Seconds (0.)); sinkApps.Stop (Seconds (20.));
Ptr<Socket> ns3TcpSocket =Socket::CreateSocket (nodes.Get (0),
TcpSocketFactory::GetTypeId ()); ns3TcpSocket->TraceConnectWithoutContext
("CongestionWindow", MakeCallback (&CwndChange));
Ptr<MyApp> app = CreateObject<MyApp> (); app->Setup (ns3TcpSocket, sinkAddress, 1040, 1000,
DataRate ("1Mbps")); nodes.Get (0)->AddApplication (app); app->SetStartTime (Seconds (1.)); app->SetStopTime (Seconds (20.));
devices.Get (1)->TraceConnectWithoutContext("PhyRxDrop", MakeCallback (&RxDrop));
Simulator::Stop (Seconds(20)); Simulator::Run (); Simulator::Destroy ();
return 0;}
TCP sink application
TCP application
Connect Cwnd trace source and sink
Connect RxDrop trace source and sink
Example Code
Callback Function
Static voidCwndChange (uint32_t oldCwnd, uint32_t newCwnd){
NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << “\t” << newCwnd);}
Static voidRxDrop (Ptr<const Packet> p){
NS_LOG_UNCON (“RxDrop at” << Simulator::Now ().GetSeconds ();}
Connect a trace source and trace sink
ns3TcpSocket->TraceConnectWithoutContext (“CongestionWindow”, MakeCallback (&CwndChange));
devices.Get(1)->TraceConnectWithoutContext (“PhyRxDrop”, MakeCallback (&RxDrop));
Output Result In ns-allinone-3.12.1/ns-3.12.1/examples/tutorial
tutorial$ cp fifth.cc ~/ns-allinone-3.12.1/ns-3.12.1/scratch/filename.cc ns-3.12.1$ ./waf --run filename
Output Result
Using Mid-level helperstatic voidCwndChange (Ptr<OutputStreamWrapper> stream, uint32_t oldCwnd, uint32_t newCwnd){NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\t" << newCwnd);*stream->GetStream () << Simulator::Now ().GetSeconds () << "\t" << oldCwnd << "\t" <<
newCwnd << std::endl; }
static voidRxDrop (Ptr<PcapFileWrapper> file, Ptr<const Packet> p){NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ());file->Write(Simulator::Now(), p);}…AsciiTraceHelper asciiTraceHelper;Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream ("sixth.cwnd");ns3TcpSocket->TraceConnectWithoutContext ("CongestionWindow", MakeBoundCallback
(&CwndChange, stream));
PcapHelper pcapHelper;Ptr<PcapFileWrapper> file = pcapHelper.CreateFile ("sixth.pcap", std::ios::out,
PcapHelper::devices.Get (1)->TraceConnectWithoutContext("PhyRxDrop", MakeBoundCallback (&RxDrop, file));
References Network Simulator
http://www.nsnam.org
NS-3 tutorial http://www.nsnam.org/docs/release/3.12/tutorial/singleht
ml/index.html
NS-3 manual http://www.nsnam.org/docs/release/3.12/manual/singleht
ml/index.html