3 - 한국기술교육대학교

Download Report

Transcript 3 - 한국기술교육대학교

NS-3 Tutorial 및 프로토콜 구현 방법
한국기술교육대학교 컴퓨터공학부 - 한연희 교수
[email protected]
고려대학교 융합소프트웨어 전문대학원 - 최현영 연구교수
[email protected]
2011년도 한국통신학회 단기강좌
NS-3 Introduction
2
NS-3
What is NS-3?
NS-3 is a discrete-event network simulator for Internet
systems



http://www.nsnam.org
targeted primarily for research and educational use.
intended to eventually replace the ns-2 simulator
 not backwards-compatible with ns-2



a free, open source software project organized
around research community development and maintenance
NS-3 is a GNU GPLv2-licensed project
Open mailing lists
 http://www.nsnam.org/developers/tools/mailing-lists

3
~30 maintainers worldwide
NS-3
What is NS-3?
Main Groups


University of Washington (Tom Henderson), Georgia Tech (George
Riley), Bucknell (Felipe Perrone)
Financial Support
 U.S. National Science Foundation (NSF) & INRIA
 Project timeline: 2010-14
All code for merge to ns-3 is openly reviewed by
maintainers



Syntactic (style) reviews
Design reviews
Documentation and tests
Papers using NS-3 starting to appear

4
http://www.nsnam.org/overview/publications
NS-3
Language: NS-2 vs. NS-3
Language aspect

ns-2
 simulator core: c++ and Otcl
 script: Otcl

ns-3
 simulator core: NS-3 core is written entirely in C++
 script: user code - protocols and scenarios - also in C++
 Python wrappers for user code also exist, but can run ns-3
without any knowledge of Python
5
NS-3
NS-3 Progress Report
Current Release

ns-3.12.1 (Aug 31, 2011)
Progress Report (1/3)

6
ns-3.1 : June 2008
NS-3
NS-3 Progress Report
Progress Report (2/3)

ns-3-3.9 (August 20, 2010)
 Spectrum Modeling
 OFDM
 Underwater Acoustic Network
 WiFi patches for bugs, etc.
 See the page: http://www.nsnam.org/wiki/index.php/Ns-3.9

ns-3-3.10 (Jan., 2011)
 DSDV (Destination Sequenced Distance Vector) routing
 Initial support for the 802.11g PHY
 Consolidate Wi-Fi MAC high functionality
 Energy model WiFi additions
 New TCP
 3GPP LTE support, etc.
 See the page: http://www.nsnam.org/wiki/index.php/Ns-3.10
7
NS-3
NS-3 Progress Report
Progress Report (3/3)

ns-3-3.11 (May, 2011)
 The build system has been modularized, and the source code
reorganized

Python bindings have also been modularized
 An interface to an OpenFlow software implementation distribution has
been added
 Click Modular Routing

ns-3-3.12.1 (Aug 31, 2011)
 SpectrumChannel models now support the usage of single-frequency
propagation loss models based on the PropagationLossModel class
 Support for IPv4 fragmentation has been added
8
NS-3
Available modules (NS-3.11 May 2011)
devices
bridge
csma
emu
spectrum
tap-bridge
protocols
applications
internet
energy
uan
utilities
aodv
configstore
dsdv
flowmonitor
olsr
netanim
click
stats
mpi
point-topoint
virtualnet-device
mobility
lte
wifi
nix-vectorrouting
network
topologyread
propagation
mesh
9
wimax
core
visualizer
NS-3
NS-3 Features
Features (1/3)


Clean slate design from ns2, aiming to be easier to use and more
ready for extension
Alignment with real systems
 BSD-lookalike - sockets, device driver interfaces

Standard input/output formats so that other tools can be reused.
 e.g., PCAP (tcpdump/wireshark) trace output

ns-3 is adding “running implementation code”
 e.g., Linux TCP code
10
NS-3
NS-3 Features
Features (2/3)

Looks just like IP architecture stack
Application
Application
Application
Application
Sockets-like
API
Protocol
stack
Protocol
stack
Packet(s)
Node
NetDevice
NetDevice
Node
Channel
NetDevice
NetDevice
Channel
11
NS-3 basic simulation model
NS-3
NS-3 Features
Features (3/3)

Nodes have “network devices,” e.g. WiFi, CSMA
 NetDevices transfer packets over Channels
 Incorporating Layer 1 (Physical) & Layer 2 (Link)
 A node can be equipped with multiple network interfaces.
 Wireless Support




WiFi, WiMAX, UMTS (PPP)
Devices interface with Layer 3 (Network: IP, ARP)
Layer 3 supports Layer 4 (Transport: UDP, TCP)
Layer 4 is used by Layer 5 (Application) objects
 Can run real implementation of applications.

Various Network Access Types
 P2P link, shared link with CSMA.

12
Support (nearly) complete IPv6
NS-3
NS-3 Features
Extensively documented API (doxygen):

13
http://www.nsnam.org/documentation
NS-3
Key Abstractions
Node



basic computing device abstraction
Node class provides methods for managing computing devices
An ns-3 Node is a husk of a computer to which applications,
stacks, and NICs are added
Application
Application
Application
14
NS-3
Network Emulation
Network Emulation
real machine
virtual
machine
ns-3
virtual
machine
ns-3
ns-3
real
machine
real
machine
Testbed
1) ns-3 interconnects virtual
machines
Added in ns-3.5
15
2) testbeds interconnect ns-3
stacks
Added in ns-3.3
NS-3
NS-3 attribute system
Researchers want to know all of the values in effect in
their simulations

and configure them easily
In NS-3

Each ns-3 object has a set of attributes:
 A name, help text
 A type
 An initial value
 Object attributes are organized and
documented in the Doxygen




16
Control all simulation parameters for static objects
Dump and read them all in configuration files
Visualize them in a GUI
Makes it easy to verify the parameters of a simulation
NS-3
Key Abstractions
Application


user’s program to be simulated
Application class provides methods for managing user-level
applications
Channel



medium connected by nodes
Channel class provides methods for managing communication
media and connecting nodes to them.
Specialized Channel
 CsmaChannel: Ethernet
 PointToPointChannel
 WifiChannel
17
NS-3
Key Abstractions
Net device


like Network Interface Cards (NICs)
NICs are controlled using network device drivers collectively
known as “net devices”
 In Linux, you refer to these “net devices” by names such as eth0
 In NS-3, “net device” abstraction covers both the software driver and
the simulated hardware


It enables a node to communicate with other nodes in simulation
via channels
NetDevice class provides methods for managing connections to
Node and Channel objects
 a Node may be connected to more than one Channel via multiple
NetDevices.

Specialized Channel
 CsmaNetDevice
 PointToPointNetDevice
 WifiNetDevice
18
NS-3
Key Abstractions
Topology helpers


19
In a large simulated network you will need to arrange many
connections between Nodes, NetDevices and Channels.
By using “Topology helper” object, we can connect NetDevices to
Nodes, NetDevices to Channels, and assign IP addresses to
NetDevices
NS-3
Additional third-party project releases
PhySim: high-fidelity physical layer model for 5 GHz OFDM
 http://dsn.tm.uni-karlsruhe.de/english/ns3-physim.php
SliceTime: time synchronization between Xen PVMs and ns-3
 http://www.comsys.rwth-aachen.de/research/projects/slicetime
Multipath TCP: IETF TCP extensions
 http://code.google.com/p/mptcp-ns3
LENA project: LTE/EPC network simulator
 http://www.ubiquisys.com/femtocell-media-press-releases-id-203.htm
ns-3 DCE: Direct Code Execution environment
 http://www-sop.inria.fr/members/Mathieu.Lacage/dce.html
LTE: Univ. of Padua, HARQ and MOBILITY modules
 https://sourceforge.net/projects/ns3-lte
Content Addressable Networks DHT
 http://mailman.isi.edu/pipermail/ns-developers/201020
November/008460.html
NS-3
Course usage
Georgia Tech (George Riley)
 ECE 6110; http://users.ece.gatech.edu/~riley/ece6110
University of Kansas (James Sterbenz)
 EECS 882; http://www.ittc.ku.edu/~jpgs/courses/mwnets
University of Pennsylvania (Boon Thau Loo)
 CIS553; http://netdb.cis.upenn.edu/cis553projects
21
NS-3
Challenges for ns-3
NS-3 lacks an integrated development/visualization
environment (IDE)
NS-3 needs participation from the research community



22
1) improving simulation credibility
2) contributed and supported models
3) maintainers
NS-3
NS-3 Installation and Programming
23
NS-3
NS-3 Installation
Environment Recommendation  Ubuntu in VirtualBox
Download ns-3.11 (all-in-one package recommended)

Download directly from http://www.nsnam.org
home~$ wget http://www.nsnam.org/releases/ns-allinone-3.11.tar.bz2
home~$ tar xvfj ns-allinone-3.11.tar.bz2
Or using mercurial tool (Ubuntu)
home~$ sudo apt-get install mercurial
home~$ mkdir repos
home~$ cd repos
home~$ hg clone http://code.nsnam.org/ns-3-allinone
home~$ ls
ns-3-allinone
home~$ cd ns-3-allinone
home~$ ls
build.py* constants.py dist.py* download.py* README util.py
home~$ ./download.py -n ns-3.11

24
NS-3
NS-3 Installation
Build NS-3.11 (all-in-one) version
ns-allinone-3.11$ ./build.py --enable-examples --enable-tests
Setting environment
ns-allinone-3.11$ cd ns-3.11
ns-3.11$ ./waf -d optimized configure
ns-3.11$ ./waf -d debug configure
ns-3.11$ ./waf
ns-3.11$ ./test.py -c core
Hello Simulator example
ns-3.11$ ./waf --run hello-simulator
Waf: Entering Directory ‘/home/ns-allinone-3.11/ns-3.11/build’
Waf: Leaving Directory ‘/home/ns-allinone-3.11/ns-3.11/build’
‘build’ finished successfully (0.677s)
Hello Simulator
25
NS-3
waf
Python-based framework, meta-build system

waf [command] [options]
waf commands





build (default)
configure
clean
distclean
install
waf options



- -run=program
- -pyrun=python-program
- -command-template=“template”
 e.g.: - -command-template=“gdb - -args %s”
26
NS-3
How to Browse Codes (NS-3.11)
ns-allinone-3.11
ns-3.11
nsc-0.5.2
pybindgen0.15.0.785
...
...
src
build
examples
core
bindings
animation
network
model
csma
helper
...
internet
...
27
bindings
test
NS-3
Tutorial #1 – UDP Echo System
examples/tutorial/first.cc (1/6)
int main (int argc, char *argv[])
{
LogComponentEnable (“UdpEchoClientApplication”, LOG_LEVEL_INFO);
LogComponentEnable (“UdpEchoServerApplication”, LOG_LEVEL_INFO);
CommandLine cmd;
cmd.Parse (argc, argv);
NodeContainer nodes;
nodes.Create (2);
nodes: NodeContainer
Node 0
28
Node 1
NS-3
Tutorial #1 – UDP Echo System
examples/tutorial/first.cc (2/6)
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer devices;
devices = pointToPoint.Install (nodes);
devices: NetDeviceContainer
Node 0
5Mbit/s, 2ms
Node 1
PointToPointNetDevice
29
NS-3
Tutorial #1 – UDP Echo System
examples/tutorial/first.cc (3/6)
InternetStackHelper stack;
stack.Install (nodes);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
interfaces: Ipv4InterfaceContainer
10.1.1.1
Ipv4Interface
Node 0
10.1.1.1
Node 1
PointToPointNetDevice
30
NS-3
Tutorial #1 – UDP Echo System
examples/tutorial/first.cc (4/6)
UdpEchoServerHelper echoServer (9);
ApplicationContainer serverApps = echoServer.Install (nodes.Get (1));
serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (10.0));
serverApps: ApplicationContainer
UdpEchoServer
Node 0
31
Node 1
NS-3
Tutorial #1 – UDP Echo System
examples/tutorial/first.cc (5/6)
UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9);
echoClient.SetAttribute (“MaxPackets”, UintegerValue (1));
echoClient.SetAttribute (“Interval”, TimeValue (Seconds (1.)));
echoClient.SetAttribute (“PacketSize”, UintegerValue (1024));
ApplicationContainer clientApps = echoClient.Install (nodes.Get (0));
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0));
clientApps: ApplicationContainer
UdpEchoClient
Node 0
32
Dest: 10.1.1.2, port 9
1 packet, 1024 bytes
UdpEchoServer
Node 1
NS-3
Tutorial #1 – UDP Echo System
examples/tutorial/first.cc (6/6)
[...]
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
UdpEchoClient
UdpEchoServer
Node 0
(10.1.1.1)
Node 1
(10.1.1.2)
1
UDP Packet
2
3
UDP Packet
$ ./waf --run first
[...]
Sent 1024 bytes to 10.1.1.2 1
Received 1024 bytes from 10.1.1.1 2
Received 1024 bytes from 10.1.1.2 3
33
NS-3
Internal API Overview
Simulator Core
Random Variables
Memory Management
Object Aggregation
NS-3 Type System
Debugging support
Tracing
Callback Objects
Nodes
Packets
Packet: Headers and Trailers
NS-3 Sockets
34
NS-3
Simulator Core
Time is not manipulated directly: the Time class

Time class supports high precision 128 bit time values
(nanosecond precision)
Time t1 = Seconds (10);
Time t2 = t1 + MilliSeconds (100);
std::cout << t2.GetSeconds () << std::endl; //t2 = 10.1
Get current time:

Time now = Simulator::Now ();
Schedule an event to happen in 3 seconds:


35
void MyCallback (T1 param1, T2 param2) {…}
….
Simulator::Schedule (Seconds (3), MyCallback, param1, param2);
Also works with instance methods:
Simulator::Schedule (Seconds (3), &MyClass::Method, instancePtr,
param1, param2);
NS-3
Random Variables
Currently implemented distributions








Uniform: values uniformly distributed in an interval
Constant: values is always the same (not really random)
Sequential: return a sequential list of predefined values
Exponential: exponential distribution (poisson process)
Normal (gaussian)
Log-normal
pareto, weibull, triangular,
…
import pylab
import NS-3
rng = NS-3.NormalVariable(10.0, 5.0)
x = [rng.GetValue() for t in range(100000)]
pylab.hist(x, 100)
pylab.show()
36
NS-3
Memory Management
Many NS-3 objects use automatic garbage collection
Reference counting

Packet *p = new Packet; // refcount initialized to 1
p->Ref (); // refcount becomes 2
p->Unref (); // refcount becomes 1
p->Unref (); // refcount becomes 0, packet is freed
Smart Pointers

Manual reference counting is error prone
 Can easily lead to memory errors

Smart Pointers
 Take care of all the reference counting work
 Otherwise they behave like normal pointers

37
Example:
void MyFunction ()
{
Ptr<Packet> p = Create<Packet> (10);
std::cerr << “Packet size: “ << p->GetSize () << std::endl;
} //Packet is released (smart pointer goes out of scope)
NS-3
Object Aggregation
A circular singly linked-list
AggregateObject() is a constant-time operation
GetObject() is a O(n) operation
Node
Aggregate contains only one
object of each type
MobilityModel
Node
Ptr<Node> node=CreateObject<Node>();
Ptr<MobilityModel> mm=CreateObject<MobilityModel>();
node->AggregateObject (mm);
MobilityModel
Ipv4
Ptr<Ipv4> ipv4 = CreateObject<Ipv4>();
node->AggregateObject(ipv4);
//Query
Ptr<Ipv4> ipv4=node->GetObject<Ipv4>();
38
Node
MobilityModel
Ipv4
NS-3
NS-3 Type System
The aggregation mechanism needs information about the
type of objects at runtime
The attribute mechanism needs information about the
attributes supported by a specific object
The tracing mechanism needs information about the trace
sources supported by a specific object
All this information is stored in NS-3::TypeId;




39
The parent type
The name of the type
The list of attributes (their name, their type, etc.)
The list of trace sources (their name, their type, etc.)
NS-3
NS-3 Type System (cont.)
Derive from the NS-3::Object base class
Define a GetTypeId static method:
class MyClass : public Object {
public:
static TypeId GetTypeId();
};
Define the features of the object:
TypeId MyClass::GetTypeId() {
static TypeId tid = TypeId(“NS-3::MyClass”)
.SetParent<Object>()
.SetAttribute(“Name”, “Help”, ...)
.AddTraceSource (“Name”, “Help”, ...);
return tid;
}
call NS_OBJECT_ENSURE_REGISTERED macro in source code
NS_OBJECT_ENSURE_REGISTERED (MyClass);
40
NS-3
Debugging Support
Assertions: NS_ASSERT (expression);


Aborts the program if expression evaluates to false
Includes source file name and line number
Unconditional Breakpoints: NS_BREAKPOINT ();

Forces an unconditional breakpoint, compiled in
Debug Logging (not to be confused with tracing!)

Purpose
 Used to trace code execution logic
 For debugging, not to extract results!

properties
 NS_LOG* macros work with C++ IO streams
 e.g.: NS_LOG_LOGIC (“I have received ” << p->GetSize() << “bytes”);
 NS_LOG* macros evaluate to nothing in optimized builds
 When debugging is done, logging does not get in the way of execution
performance
41
NS-3
Debugging Support (cont.)

Logging levels:
 NS_LOG_ERROR (…): serious error messages only
 NS_LOG_WARN (…): warning messages
 NS_LOG_DEBUG (…): rare ad-hoc debug messages
 NS_LOG_INFO (…): informational messages (e.g. banners)
 NS_LOG_FUNCTION (…): function tracing
 NS_LOG_PARAM (…): parameters to functions
 NS_LOG_LOGIC (…): control flow tracing within functions

Logging “components”
 Logging messages organized by components
 Usually one component is one .cc source file
 NS_LOG_COMPONENT_DEFINE (“OslrAgent”);

Displaying log messages. Two ways:
 Programatically:

LogComponentEnable (“OslrAgent”, LOG_LEVEL_ALL);
 From the environment:
42

NS_LOG=“OslrAgent” ./my-program
NS-3
Tracing (by example)
uint64_t g_packetDrops = 0;
uint64_t g_packetDropBytes = 0;
void TraceDevQueueDrop (std::string context,
Ptr<const Packet> droppedPacket)
{
g_packetDrops += 1;
g_packetDropBytes += droppedPacket->GetSize ();
}
NodeList
0..*
Node
0..*
int main (int argc, char *argv[])
{
[…]
Config::Connect (“/NodeList/*/DeviceList/*/TxQueue/Drop”,
MakeCallback (&TraceDevQueueDrop));
[…]
}
43
NodeList
DeviceList
CsmaNetDevice
1
TxQueue
Queue
NS-3
Callback Objects
NS-3 Callback class implements function objects

Type safe callbacks, manipulated by value
 used for example in sockets and tracing
Example
double MyFunc (int x, float y) {
return double (x+y)/2;
}
Callback<double, int, float> cb1;
cb1 = MakeCallback (MyFunc);
double result = cb1 (2, 3); //result receives 2.5
------------------------------------------------------------------------------------------------class MyClass {
public: double MyMethod (int x, float y) {
return double (x+y)/2;
}};
Callback<double, int, float> cb1;
MyClass myobj;
cb1 = MakeCallback (&MyClass::MyMethod, &myObj);
double result = cb1 (2, 3); //result receives 2.5
44
NS-3
Nodes
Node class


Represents a network element
May have an IPv4 stack object
Application
May have a mobility model
 But it is optional


Contains a list of NetDevices
Contains a list of Applications
1
0..*
 But it is completely optional!

NodeList
Aggregates
IPv4
0..*
1
Node
MobilityModel
1
0..*
NodeList class (singleton)


45
NetDevice
Tracks all nodes ever created
Node index  Ptr conversions
NS-3
Packets
Packet objects used vertically in NS-3 to represent:



Units of information sent and received by applications
Information chunks of what will becomes a real packet (similar
sk_buff in Linux kernel)
Simulated packets and L2/L1 frames being transmitted
Basic Usage

Create empty packet
 Ptr<Packet> packet = Create<Packet> ();

Create packet with 10 “dummy” bytes
 Ptr<Packet> packet = Create<Packet> (10);

Create packet with user data
 Ptr<Packet> packet = Create<Packet> (“hello”, 5);

Copy a packet
 Ptr<Packet> packet2 = packet1->Copy ();
 Note: packet copy is usually cheap (copy-on-write)
46
NS-3
Packet: Headers and Trailers
Packets support headers and trailers

Headers and trailers are implemented as classes that
 Implement a Serialize method:

Writes the header information as a byte stream;
 Implement a Deserialize method:



Reads the header information from a byte stream;
Headers and trailers used to implement protocols
Packets contain exact byte contents
 They are not just structure as in NS-2
 Allows writing pcap trace files, readable from wireshark
47
NS-3
Packet: Headers and Trailers (cont.)
LLC/SNAP header example
uint32_t LlcSnapHeader::GetSerializedSize (void) const
{
return 8;
}
void LlcSnapHeader::Serialize (Buffer::Iterator start) const
{
Buffer::Iterator i = start;
uint8_t buf[] = { 0xaa, 0xaa, 0x03, 0, 0, 0};
i.Write (buf, 6);
i.WriteHtonU16 (m_etherType);
}
uint32_t LlcSnapHeader::Deserialize (Buffer::Iterator start)
{
Buffer::Iterator i = start;
i.Next (5+1);
m_etherType = i.ReadNtohU16 ();
return GetSerializedSize ();
}
Adding a header
LlcSnapHeader llcsnap;
llcsnap.SetType (0x0800); //IPv4
packet->AddHeader (llcsnap);
DSAP SSAP Ctrl. 00
LLC(3bytes)
00
00 Ethertype
SNAP(5bytes)
Removing a header
LlcSnapHeader llcsnap;
packet->RemoveHeader (llcsnap);
48
NS-3
NS-3 Sockets
Plain C sockets
int sk;
sk = socket (PF_INET, SOCK_DGRAM, 0);
struct sockaddr_in src;
inet_pton(AF_INET, “0.0.0.0”, &src.sin_addr);
src.sin_port = htons(80);
bind(sk, (struct sockaddr *)&src, sizeof(src));
NS-3 sockets
Ptr<SocketFactory> udpFactory=node->
GetObject<UdpSocketFactory> ();
Ptr<Socket> sk = udpFactory->CreateSocket ();
InetSocketAddress src = InetSocketAddress
(Ipv4Address::GetAny(), 80);
sk->Bind (src);
struct sockaddr_in dest;
inet_pton(AF_INET, “10.0.0.1”, &dest.sin_addr);
dest.sin_port = htons(80);
sendto(sk, “hello”, 6, 0, (struct sockaddr *)&dest,
sizeof(dest));
InetSocketAddress dest = InetSocketAddress
(Ipv4Address(“10.0.0.1”), 80);
sk->SendTo (dest, Create<Packet> (“hello”, 6));
char buf[6];
recv(sk, buf, 6, 0);
sk->SetReceiveCallback (MakeCallback
(MySocketReceive));
49
void MySocketReceive (Ptr<Socket> sk) {
char buf[6];
sk->Recv (buf, 6, 0);
}
NS-3
Tutorial #2
Making a new agent called “MyAgent”


It communicates each other using IPv4 with protocol number
(250)
New packet header “MyHeader” is used for information exchange
 source IP, destnation IP, and sequence
0
32
source IP
destination IP
sequence
MyAgent
Node1
50
MyHeader
IPv4
PPP
MyAgent
Node2
NS-3
Tutorial #2 - Where to put source codes
Create new folder “myagent” and sub-folders
ns-3.11
scratch
myagent-test.cc
src
myagent
wscript
bindings
51
helper
myagent-helper.h, myagent-helper.cc
model
myagent.h, myagent.cc, myheader.h,
myheader.cc
test
NS-3
Tutorial #2 - Module dependency
Add “myagent” module to ns-3.11

ns-3.11/src/wscript file
all_modules = {
……
‘template’,
‘myagent’,
};
Create “wscript” file in ns-3.11/src/myagent folder
52
def build(bld):
myagent = bld.create_NS-3_module(‘myagent’, [‘network’, ‘internet’])
myagent.source = [
‘model/myagent.cc’,
‘model/myheader.cc’,
‘helper/myagent-helper.cc’,
]
headers = bld.new_task_gen(‘NS-3header’)
headers.module = ‘myagent’
headers.source = [
‘model/myagent.h’,
‘model/myheader.h’,
‘helper/myagent-helper.h’,
]
NS-3
Tutorial #2 - MyHeader class
MyHeader class definition
class MyHeader : public Header
{
public:
MyHeader ();
[……]
virtual
virtual
virtual
virtual
void Print (std::ostream &os) const;
uint32_t GetSerializedSize (void) const;
void Serialize (Buffer::Iterator start) const;
uint32_t Deserialize (Buffer::Iterator start);
private:
Ipv4Address m_source;
Ipv4Address m_destination;
uint32_t m_sequence;
}
53
NS-3
Tutorial #2 - MyHeader class(cont.)
MyHeader codes
uint32_t
MyHeader::GetSerializedSize (void) const
{
return 12;
}
void
MyHeader::Serialize (Buffer::Iterator start) const
{
Buffer::Iterator i = start;
uint8_t buf[4];
uint32_t
MyHeader::Deserialize (Buffer::Iterator start)
{
Buffer::Iterator i = start;
uint8_t buf[4];
i.Read (buf, 4);
m_source = Ipv4Address::Deserialize (buf);
i.Read (buf, 4);
m_destination = Ipv4Address::Deserialize (buf);
m_source.Serialize (buf);
i.Write (buf, 4);
m_destination.Serialize (buf);
i.Write (buf, 4);
}
54
m_sequence = i.ReadNtohU32 ();
}
return GetSerializedSize ();
i.WriteHtonU32 (m_sequence);
NS-3
Tutorial #2 - MyAgent class
MyAgent class definition
class MyAgent : public Ipv4L4Protocol
{
public:
static TypeId GetTypeId (void);
static uint16_t PROT_NUMBER;
[……]
virtual int GetProtocolNumber (void) const;
virtual enum Ipv4L4Protocol::RxStatus Receive (Ptr<Packet> p, Ipv4Header const &header,
Ptr<Ipv4Interface> incomingInterface);
[……]
void SendMyInfo ();
protected:
virtual void NotifyNewAggregate ();
private:
Ptr<Node> m_node;
uint32_t m_sequence;
Ipv4Address m_localAddress;
Ipv4Address m_peerAddress;
};
55
NS-3
Tutorial #2 - MyAgent class (cont.)
MyAgent class codes

NotifyNewAggregate() : called whenever an object is aggregated
void MyAgent::NotifyNewAggregate ()
{
if (m_node == 0)
{
Ptr<Node>node = this->GetObject<Node> ();
if (node != 0)
{
this->SetNode (node);
Ptr<Ipv4> ipv4 = node->GetObject<Ipv4> ();
ipv4->Insert (this);
}
}
Object::NotifyNewAggregate ();
}
56
MyAgent
1) Insert()
2)
List
Ipv4L3Protocol
NS-3
Tutorial #2 - MyAgent class
MyAgent class codes
Sending Information

void MyAgent::SendMyInfo ()
{
NS_LOG_FUNCTION_NOARGS ();
MyAgent
Ptr<Packet> packet = Create<Packet>();
MyHeader myh;
myh.SetDestination (m_peerAddress);
myh.SetSource (m_localAddress);
myh.SetSequence (m_sequence++);
packet->AddHeader (myh);
Send()
Ipv4L3Protocol
NS_LOG_INFO ("Sending information : " << myh);
Ptr<Ipv4> ipv4 = m_node->GetObject<Ipv4> ();
}
57
ipv4->Send (packet, m_localAddress, m_peerAddress,
PROT_NUMBER, 0);
NS-3
Tutorial #2 - MyAgent class (cont.)
MyAgent class codes
Receiving Information

enum Ipv4L4Protocol::RxStatus MyAgent::Receive (Ptr<Packet> p,
Ipv4Header const &header,
Ptr<Ipv4Interface> incomingInterface)
{
NS_LOG_FUNCTION (this << p << header);
MyHeader myh;
p->RemoveHeader (myh);
MyAgent
NS_LOG_INFO ("Received information : " << myh);
}
return Ipv4L4Protocol::RX_OK;
uint16_t MyAgent::PROT_NUMBER = 250;
58
int MyAgent::GetProtocolNumber (void) const
{
NS_LOG_FUNCTION_NOARGS ();
return PROT_NUMBER;
}
2) Receive()
1)GetProtocolNumber()
Ipv4L3Protocol
NS-3
Tutorial #2 - MyAgentHelper class
MyAgentHelper class definition & code
class MyAgentHelper
{
public:
MyAgentHelper (void);
virtual ~MyAgentHelper (void);
void Install (Ptr<Node> node, Ipv4Address local, Ipv4Address peer) const;
private:
};
void MyAgentHelper::Install (Ptr<Node> node, Ipv4Address local, Ipv4Address peer) const
{
NS_LOG_FUNCTION (this << node << local << peer);
Ptr<MyAgent> myagent = CreateObject<MyAgent> ();
myagent->SetLocalAddress (local);
myagent->SetPeerAddress (peer);
}
59
node->AggregateObject (myagent);
NS-3
Tutorial #2 - Simulation Script
The same script from Tutorial #1 except MyAgent related
codes
void SendInfo (Ptr<Node> node)
{
Ptr<MyAgent> myagent = node->GetObject<MyAgent> ();
myagent->SendMyInfo ();
}
int main (int argc, char *argv[])
{
[……]
MyAgentHelper myHelper;
myHelper.Install (nodes.Get (0), Ipv4Address ("10.1.1.1"), Ipv4Address ("10.1.1.2"));
myHelper.Install (nodes.Get (1), Ipv4Address ("10.1.1.2"), Ipv4Address ("10.1.1.1"));
}
60
Simulator::Schedule (Seconds (1.0), SendInfo, nodes.Get (0));
NS-3
Tutorial #2 - Simulation Results
Results
ns-3.11$ ./waf --run myagent-test
Sending information : ( SourceIP: 10.1.1.1, DestinationIP: 10.1.1.2, Sequence: 0)
Received information : ( SourceIP: 10.1.1.1, DestinationIP: 10.1.1.2, Sequence: 0)
61
NS-3
Tutorial #2 - Simulation Results
0xfa=250
source IP:10.1.1.1
dest. IP:10.1.1.2
62
NS-3
Thank you
Q&A
63
NS-3