示例脚本:【examples/tutorial/first.cc】
模拟了一个有线网络,包含两个结点
链路层使用PPP传输分组
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ns3/core-module.h" // 定义了ns-3的核心功能(如模拟事件、事件调度),必须包括
#include "ns3/network-module.h" // 定义了ns-3的基本网络组件(如网络结点、分组和地址等),必须包括
#include "ns3/internet-module.h" // 定义了TCP/IP协议栈
#include "ns3/point-to-point-module.h" //
#include "ns3/applications-module.h" // 定义了应用层的分组收发模型(如贪婪模型、ON/OFF模型等)
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("FirstScriptExample");
int
main (int argc, char *argv[])
{
CommandLine cmd;
cmd.Parse (argc, argv); // 读取命令行参数
Time::SetResolution (Time::NS); // 设置最小模拟时间单元:ns
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO); // 开启Log组件,打印指定Log组件信息
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
NodeContainer nodes;
nodes.Create (2); // 创建网络结点
PointToPointHelper pointToPoint; // PPP信道助手类
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); // 配置PPP信道传输速率属性
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms")); // 配置PPP信道传播延迟属性
NetDeviceContainer devices; // 创建网络设备
devices = pointToPoint.Install (nodes); // 连接结点与信道
InternetStackHelper stack;
stack.Install (nodes); // 为nodes容器中的结点安装TCP/IP协议栈
Ipv4AddressHelper address; // 为网络设备分配IP地址
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
UdpEchoServerHelper echoServer (9); // 监听9号端口
ApplicationContainer serverApps = echoServer.Install (nodes.Get (1)); // 在结点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)); // 在结点0中安装客户端程序
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}