VANET仿真-ns3(1)

VANET 仿真

ns3示例代码first.cc注释整理,点对点的udp传输仿真


#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"

//namespace 定义之后,所有命令行的参数都需要用ns::的形式来表示
using namespace ns3;

//定义日志的组成部分
NS_LOG_COMPONENT_DEFINE ("FirstScriptExample");

int
main (int argc, char \*argv[])
{
//开启命令行参数,可以设置全局变量、属性等,可以用./waf --run "scratch/myfirst --PrintHelp"查看帮助信息
CommandLine cmd;
cmd.Parse (argc, argv);

Time::SetResolution (Time::NS); //时间被设定成纳秒级别
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);

NodeContainer nodes;
nodes.Create (2);

PointToPointHelper pointToPoint;
//实例化一个点对点模型
//有两种方式可以设置节点参数,一种可以通过下面的方式修改,
//另一种通过命令行./waf --run "scratch/myfirst --ns3::PointToPointNetDevice::DataRate=5Mbps --ns3::PointToPointChannel::Delay=2ms"
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));

NetDeviceContainer devices;
devices = pointToPoint.Install (nodes);

//协议栈,包括TCP,UDP,IP等
InternetStackHelper stack;
stack.Install (nodes);

//设定地址掩码等信息
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");

//通过下面的函数将ipv4地址与设备链接起来
Ipv4InterfaceContainer interfaces = address.Assign (devices);

//设置udp端口号为9
UdpEchoServerHelper echoServer (9);

//install函数就是把节点挂载到server上
ApplicationContainer serverApps = echoServer.Install (nodes.Get (1));
serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (10.0));

//client上五个属性分别为节点地址、端口号、包数量、间隔、包大小
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));
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0));

//开始仿真、结束仿真
Simulator::Run ();
Simulator::Destroy ();
return 0;
}