ns-3入门非常简单,一定做到吃透example/tutorial/目录下的first.cc示例程序
一,ns-3基础资料
1,ns3简介
ns3的开发旨在为网络研究和教育提供开放,可扩展的网络仿真平台。简而言之,ns3提供了分组数据网络如何工作和执行的模型,并为用户提供了进行模拟实验的模拟引擎。使用ns-3的一些原因包括进行更难或不可能用真实系统执行的研究,在高度可控的,可重现的环境中研究系统行为,以及了解网络如何工作。用户将注意到ns3中的可用模型集侧重于建模Internet协议和网络的工作方式,但ns3不仅限于Internet系统;一些用户正在使用ns-3来建模非基于互联网的系统。
源代码管理工具:‘Git’
源代码系统构建工具:‘waf’;(简单版的make)
2,参考资料
- Official Website: https://www.nsnam.org
- Official Documents Webpage: http://www.nsnam.org/documentation
主要的三个文档:tutorial:入门文档;manual:功能文档;model-library:模型库介绍;
- Official Wiki: https://www.nsnam.org/wiki
- Source Code: https://gitlab.com/nsnam
入门文档tutorial是快速了解ns-3最好也是最准确的文档,建立结合example/tutorial/目录下的各个示例程序学习。
二,示例程序first.cc
1,first.cc逐句注释
example/first.cc,怎么通过Helper类构建网络拓扑。理解透彻first.cc后,即可入门ns-3网络仿真开发。
//头文件均在/build/目录下,单个.h集成了多个.h文件
#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"
//n0------n1,point to point
using namespace ns3;//声明在ns3命名空间下,可以省略“ns3:”
NS_LOG_COMPONENT_DEFINE ("FirstScriptExample");
int
main (int argc, char *argv[])//命令行传入
{
CommandLine cmd;//命令行参数解析
cmd.Parse (argc, argv);
Time::SetResolution (Time::NS);//时间解析度:默认ns
//激活两个应用的日志组件,日志等级:info,普通信息
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
NodeContainer nodes;//构建容器,起名为nodes
nodes.Create (2);//创建两个空节点
PointToPointHelper pointToPoint;//创建点对点Helper,命名为p..,命名规则首字母小写
//设置属性:数字率、延迟
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer devices;//设备容器
//通过Helper把设备连接到通信子网,并安装到nodes,且返回给devices一一对应
devices = pointToPoint.Install (nodes);
InternetStackHelper stack;//安装Internet协议
stack.Install (nodes);
Ipv4AddressHelper address;//指定IPv4地址范围,从哪开始,子网掩码
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);//分配地址
//底层结束,后续为上层
UdpEchoServerHelper echoServer (9);//指定端口号为9
//获取节点1,把echohelper应用安装到node1;应用容器记录了节点上所有应用
ApplicationContainer serverApps = echoServer.Install (nodes.Get (1));
serverApps.Start (Seconds (1.0));//应用启动时间和停止时间
serverApps.Stop (Seconds (10.0));
//获取服务器ip地址,指定端口号
UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9);
//设置访问服务端时的属性:多少个包、间隔、包的大小1024字节
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;
}
2,first.cc运行
将first.cc复制到scratch/目录下,即可使用waf工具运行
注:vscode快捷键ctrl+shift+` 快速打开终端
./waf --run first.cc
运行结果显示了基本的收发包过程