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.
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 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 Example simulation scripts
Starting NS-3 Simulation
How to Download NS-3 Ns-3 download: ~]# tar xvf ns-allinone-3.15.tar.bz2 ~]# cd ns-allinone-3.15 Ns-3 download using mercurial: ~]# hg clone ~]# cd ns-3-allinone ~]#./download.py -n ns-3.15
How to Install NS-3 Building ~/ns-allinone-3.15]#./build.py Setting environment –d optimized configure ~/ns-allinone-3.15/ns-3.15]#./waf -d debug --enable- examples --enable-tests configure ~/ns-allinone-3.15/ns-3.15]#./waf ~/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 rtualBox_to_run_simulations_on_Windows_machines rtualBox_to_run_simulations_on_Windows_machines How to run simulations using VMware Mware_to_set_up_virtual_networks_(Windows) Mware_to_set_up_virtual_networks_(Windows) Cygwin was supported in the past There might be some problems
Conceptual Overview of NS Key Abstractions 2. 2.Simulation Procedure 3. 3.Simulation Example
Key Abstractions 1.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 Helpers I. 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 Protocolstack Node NetDevice NetDevice Application Application Protocolstack Node NetDevice NetDevice Sockets-like API 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 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 Example PointToPointHelper 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 ) Example 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));
Simulation Procedure - 4. Running simulator- Start Simulator Simulator::Run (); Destroy Simulator Simulator::Destroy ();
Simulation Example
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 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 (" ", " "); 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 Output Sent 1024 bytes to Received 1024 bytes from Received 1024 bytes from
Tweaking 1. 1.Logging Modules 2. 2.Command Line Arguments 3. 3.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 Received 1024 bytes from UdpEchoClientApplication:HandleRead(0x6241e0, 0x624a20) Received 1024 bytes from UdpEchoClientApplication: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 Received 1024 bytes from s UdpEchoClientApplication:HandleRead(0x9aead30, 0x9aeb378) s UdpEchoClientApplication:HandleRead(): Received 1024 bytes from s 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 function CommandLine 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 Example int 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: > ) ns3::UdpHeader (length: > 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: > ) ns3::UdpHeader (length: > 9) Payload (size=1024) …
Tracing System Trace file format /NodeList/0/DeviceList/0/$ns3::PointToPointNetDevice/TxQueue/Enqueue 03 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: > ) 08 ns3::UdpHeader ( 09 length: > 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.pcap reading from file myfirst-0-0.pcap, link-type PPP (PPP) IP > : UDP, length IP > : UDP, length 1024 $ tcpdump -nn -tt -r myfirst-1-0.pcap reading from file myfirst-1-0.pcap, link-type PPP (PPP) IP > : UDP, length IP > : UDP, length 1024
Tracing System Reading output with Wireshark
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)TcpSocket Set with class: ns3::UintegerValuens3::UintegerValue Underlying type: uint32_t / Initial value: uint32_t RcvBufSize: TcpSocket maximum receive buffer size (bytes)TcpSocket Set with class: ns3::UintegerValuens3::UintegerValue Underlying type: uint32_t / Initial value: uint32_t SegmentSize: TCP maximum segment size in bytes (may be adjusted based on MTU discovery) Set with class: ns3::UintegerValuens3::UintegerValue Underlying type: uint32_t / Initial value: 536uint32_t SlowStartThreshold: TCP slow start threshold (bytes) Set with class: ns3::UintegerValuens3::UintegerValue Underlying type: uint32_t / Initial value: 65535uint32_t InitialCwnd: TCP initial congestion window size (segments) Set with class: ns3::UintegerValuens3::UintegerValue Underlying type: uint32_t / Initial value: 1uint32_t
ConnTimeout: TCP retransmission timeout when opening connection (seconds) Set with class: TimeValueTimeValue Underlying type: Time / Initial value: nsTime ConnCount: Number of connection attempts (SYN retransmissions) before returning failure Set with class: ns3::UintegerValuens3::UintegerValue Underlying type: uint32_t / Initial value: 6uint32_t DelAckTimeout: Timeout value for TCP delayed acks, in seconds Set with class: TimeValueTimeValue Underlying type: Time / Initial value: nsTime DelAckCount: Number of packets to wait before sending a TCP ack Set with class: ns3::UintegerValuens3::UintegerValue Underlying type: uint32_t / Initial value: 2uint32_t PersistTimeout: Persist timeout to probe for rx window Set with class: TimeValueTimeValue Underlying type: Time / Initial value: nsTime 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)UdpSocket Set with class: ns3::UintegerValuens3::UintegerValue Underlying type: uint32_t / Initial value: uint32_t IpTtl: socket-specific TTL for unicast IP packets (if non-zero) Set with class: ns3::UintegerValuens3::UintegerValue Underlying type: uint8_t / Initial value: 0uint8_t IpMulticastTtl: socket-specific TTL for multicast IP packets (if non-zero) Set with class: ns3::UintegerValuens3::UintegerValue Underlying type: uint8_t / Initial value: 0uint8_t IpMulticastIf: interface index for outgoing multicast on this socket; -1 indicates to use default interface Set with class: ns3::IntegerValuens3::IntegerValue Underlying type: int32_t / Initial value: -1int32_t IpMulticastLoop: whether outgoing multicast sent also to loopback interface Set with class: BooleanValueBooleanValue Underlying type: bool / Initial value: falsebool MtuDiscover: If enabled, every outgoing ip packet will have the DF flag set. Set with class: BooleanValueBooleanValue Underlying type: bool / Initial value: falsebool
SocketFactory Class Object to create transport layer instances that provide a socket API to applications Public Member Functions virtual Ptr CreateSocket (void)=0 Static Public Member Functions static TypeId GetTypeId (void) This method returns the TypeId associated to ns3::SocketFactory
Tracing System 1. 1.Tracing overview 2. 2.Callback 3. 3.How to Find and Connect The Trace Source 4. 4.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
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 using namespace ns3; class MyObject : public Object { public: static TypeId GetTypeId (void) { static TypeId tid = TypeId ("MyObject").SetParent (Object::GetTypeId ()).AddConstructor ().AddTraceSource ("MyInteger", "An integer value to trace.", MakeTraceSourceAccessor (&MyObject::m_myInt)) ; return tid; } MyObject () {} TracedValue 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) void IntTrace (int32_t oldValue, int32_t newValue) { std::cout << "Traced " << oldValue << " to " << newValue << std::endl; } int main (int argc, char *argv[]) { Ptr myObject = CreateObject (); 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 Example void CourseChange (std::string context, Ptr model) { Vector position = model->GetPosition (); NS_LOG_UNCOND (context << " x = " << position.x << ", y = " << position.y); } //Trace Sink std::ostringstream oss; oss << "/NodeList/" 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 = , y = …
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 (
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
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 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 #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, 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 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; } void MyApp::Setup (Ptr 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; } void MyApp::StartApplication (void) { m_running = true; m_packetsSent = 0; m_socket->Bind (); m_socket->Connect (m_peer); SendPacket (); } Create a simple application ns-allinone /ns /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 = Create (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 (m_dataRate.GetBitRate ()))); m_sendEvent = Simulator::Schedule (tNext, &MyApp::SendPacket, this); } static void CwndChange (uint32_t oldCwnd, uint32_t newCwnd) { NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\t" << newCwnd); } static void RxDrop (Ptr 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 em = CreateObjectWithAttributes ( "RanVar", RandomVariableValue (UniformVariable (0., 1.)), "ErrorRate", DoubleValue ( )); devices.Get (1)->SetAttribute ("ReceiveErrorModel", PointerValue (em)); InternetStackHelper stack; stack.Install (nodes); Ipv4AddressHelper address; address.SetBase (" ", " "); 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 ns3TcpSocket = Socket::CreateSocket (nodes.Get (0), TcpSocketFactory::GetTypeId ()); ns3TcpSocket->TraceConnectWithoutContext ("CongestionWindow", MakeCallback (&CwndChange)); Ptr app = CreateObject (); 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 void CwndChange (uint32_t oldCwnd, uint32_t newCwnd) { NS_LOG_UNCOND (Simulator::Now ().GetSeconds () 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 /ns /examples/tutorial tutorial$ cp fifth.cc ~/ns-allinone /ns /scratch/filename.cc ns $./waf --run filename
Output Result
Using Mid-level helper static void CwndChange (Ptr 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 void RxDrop (Ptr file, Ptr p) { NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ()); file->Write(Simulator::Now(), p); } … AsciiTraceHelper asciiTraceHelper; Ptr stream = asciiTraceHelper.CreateFileStream ("sixth.cwnd"); ns3TcpSocket->TraceConnectWithoutContext ("CongestionWindow", MakeBoundCallback (&CwndChange, stream)); PcapHelper pcapHelper; Ptr file = pcapHelper.CreateFile ("sixth.pcap", std::ios::out, PcapHelper::devices.Get (1)->TraceConnectWithoutContext("PhyRxDrop", MakeBoundCallback (&RxDrop, file));
References Network Simulator NS-3 tutorial tml/index.html tml/index.html NS-3 manual tml/index.html tml/index.html