点对点有线网络:first.cc脚本
该c++模拟脚本船舰了一个有两个节点的有线网络,其链路岑层使用点对点协议传输分组。
1.头文件
#include "ns3/core-moudel.h"
#include "ns3/network-moudel.h"
#include "ns3/internet-moudel.h"
#include "ns3/point-to-point-moudel.h"
#include "ns3/applications-moudel.h"
core和network模块头文件是所有脚本必须包括的,分别定义了ns-3的核心功能和基本网络组件。
2.名字空间
using namespace ns3;
整个源代码收“ns3”名字空间保护。
3.NS_LOG_COMPONENT_DEFINE ("FirstScriptExample");
允许在该脚本中使用log系统中的宏定义打印辅助信息。通过对FirstSxriptExample这个名字的操作,可以关闭或打开控制台日志输出。
4.主函数
CommandLine cmd;
cmd.Parse (argc, argv);//读取命令行参数
Time::SetResolution (Time::NS);//最小时间单元ns
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);//打印日志信息
5.创建网络拓扑-生成网络节点
NodeContainer nodes;//声明一个名为nodes的NodeContainer
nodes.Create (2);//生成n个节点
创建网络节点,调用create方法创建了两个节点。
6.-物理连接计算机
PointToPointHelper pointToPoint;//在栈中初始化一个PointToPointHelper对象pointToPoint
//配置PPP信道属性
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));//传输速率属性
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));//传播延迟属性
//创建对象使用“5Mbps”来作为数据速率,使用“2ms”作为每一个被创建的点到点信道的传输时延。
NetDeviceContainer devices;//创建网络设备
devices = pointToPoint.Install (nodes);//链接节点与信道
//这两行代码完成设备和信道的配置。
7.安装TCP/IP协议族
Ipv4AddressHelper address;//为网络设备分配IP地址
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
8.安装应用层
UdpEchoServerHelper echoServer (9);//监听9号端口
//在节点1中安装服务端程序
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));
//再节点0中安装客户端程序
ApplicationContainer clientApps = echoClient.Install (nodes.Get (0));
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0));
9.启动与结束
Simulator::Run ();
Simulator::Destroy ();
return 0;
Run()函数执行之前步骤中定义的所有操作,完成之后,destroy()函数执行清除操作。在ns3中任何网络行为都是一个事件,run()函数的任务就是按时间顺序执行这些事件,直到所有事件都执行完毕为止。因为c++模拟脚本本质上是一个main()函数,所以程序最后需要返回0来告诉操作系统程序执行成功。
10.执行
./waf --run first命令执行first脚本