first脚本是点对点有线网络,该脚本创造了包含两个结点的有线网络。其链路层采用点对点协议传输分组。一个完整的ns-3脚本可以按照编写顺序分为以下几个部分:
1.头文件,添加头文件仅需知道模块名即可。build/ns3 (编译后)中可以找到这些头文件。
2.名字空间,整个ns3源代码都受到“ns3”名字空间保护。
3.log系统打印信息(不是很懂)
4.main()函数中的准备工作,设置模拟时间单元、开启log组件等
5.创建网络拓扑结构。在一个物理网络中,一个网络拓扑是由若干结点和连接这些结点的信道组成。在ns3中信道和结点被抽象为Node、Channel以及结点中连接信道的网络设备NetDevice类。
NetDevice主要负责实现链路层协议。Channel主要负责实现物理层协议。
网络拓扑的建立经历以下三个步骤
①创建结点
②配置信道属性
③创建信道并建立连接结点
6.安装上层协议栈,即安装TCP/IP协议栈
7.安装应用程序
8.数据生成(first脚本里没有这一步)
9.启动和结束仿真。
#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"
/*head file is locate at build/ns3(after debug)
//core and network are must need
//interner modle defines TCP/IP protocol stack
//application modle defines packet modle of application layer*/
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("FirstScriptExample");
//allow script ues mocro definition of log system to print subsidiary information
int
main (int argc, char *argv[])
{
CommandLine cmd;
cmd.Parse (argc, argv); //read command line parameter
Time::SetResolution (Time::NS); //set min time unit
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO); //print some information
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
//different channel has different NetDevice and Channel
//Node Channel NetDevice
NodeContainer nodes;
nodes.Create (2); //creat nodes
PointToPointHelper pointToPoint; //ppp channel helper class
//configure ppp channel attribute
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); //transmission rate
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms")); //delay
NetDeviceContainer devices; //creat netdevice
devices = pointToPoint.Install (nodes); //link node with device
InternetStackHelper stack; //InternetStackHelper class to install TCP/IP for node
stack.Install (nodes);
Ipv4AddressHelper address; //assign ip address for net devices
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
//udpecho
UdpEchoServerHelper echoServer (9); //monitor 9 port
//install severapp in node 1
ApplicationContainer serverApps = echoServer.Install (nodes.Get (1));
serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (10.0));
//assign client app attribute
UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9);
echoClient.SetAttribute ("MaxPackets", UintegerValue (1));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0)));
echoClient.SetAttribute ("PacketSize", UintegerValue (1024));
//install clientapp in node 0
ApplicationContainer clientApps = echoClient.Install (nodes.Get (0));
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0));
//start and end simulator
Simulator::Run ();
Simulator::Destroy ();
return 0;
}