NS3 1个发送节点向2个接收节点广播1个数据包

  • 基于NS3 Wave模块提供的实例,实现1个发送节点向2个接收节点广播1个数据包
/*
 * Copyright (c) 2005,2006,2007 INRIA
 * Copyright (c) 2013 Dalian University of Technology
 *
 * 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
 *
 * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
 * Author: Junling Bu <linlinjavaer@gmail.com>
 *
 */
/**
 * This example shows basic construction of an 802.11p node.  Two nodes
 * are constructed with 802.11p devices, and by default, one node sends a single
 * packet to another node (the number of packets and interval between
 * them can be configured by command-line arguments).  The example shows
 * typical usage of the helper classes for this mode of WiFi (where "OCB" refers
 * to "Outside the Context of a BSS")."
 */

#include "ns3/command-line.h"
#include "ns3/config.h"
#include "ns3/double.h"
#include "ns3/internet-stack-helper.h"
#include "ns3/ipv4-address-helper.h"
#include "ns3/ipv4-interface-container.h"
#include "ns3/log.h"
#include "ns3/mobility-helper.h"
#include "ns3/mobility-model.h"
#include "ns3/ocb-wifi-mac.h"
#include "ns3/position-allocator.h"
#include "ns3/socket.h"
#include "ns3/string.h"
#include "ns3/vector.h"
#include "ns3/wave-mac-helper.h"
#include "ns3/wifi-80211p-helper.h"
#include "ns3/yans-wifi-helper.h"

#include <iostream>

using namespace ns3;

NS_LOG_COMPONENT_DEFINE("WifiSimpleOcb");

/*
 * In WAVE module, there is no net device class named like "Wifi80211pNetDevice",
 * instead, we need to use Wifi80211pHelper to create an object of
 * WifiNetDevice class.
 *
 * usage:
 *  NodeContainer nodes;
 *  NetDeviceContainer devices;
 *  nodes.Create (2);
 *  YansWifiPhyHelper wifiPhy;
 *  YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
 *  wifiPhy.SetChannel (wifiChannel.Create ());
 *  NqosWaveMacHelper wifi80211pMac = NqosWave80211pMacHelper::Default();
 *  Wifi80211pHelper wifi80211p = Wifi80211pHelper::Default ();
 *  devices = wifi80211p.Install (wifiPhy, wifi80211pMac, nodes);
 *
 * The reason of not providing a 802.11p class is that most of modeling
 * 802.11p standard has been done in wifi module, so we only need a high
 * MAC class that enables OCB mode.
 */

/**
 * Receive a packet
 * \param socket Rx socket
 */
void
ReceivePacket(Ptr<Socket> socket)
{
    while (socket->Recv())
    {
        NS_LOG_UNCOND("Received one packet!");
    }
}

/**
 * Geerate traffic
 * \param socket Tx socket
 * \param pktSize packet size
 * \param pktCount number of packets
 * \param pktInterval interval between packet generation
 */
static void
GenerateTraffic(Ptr<Socket> socket, uint32_t pktSize, uint32_t pktCount, Time pktInterval)
{
    if (pktCount > 0)
    {
        socket->Send(Create<Packet>(pktSize));
        Simulator::Schedule(pktInterval,
                            &GenerateTraffic,
                            socket,
                            pktSize,
                            pktCount - 1,
                            pktInterval);
    }
    else
    {
        socket->Close();
    }
}

int
main(int argc, char* argv[])
{
    std::string phyMode("OfdmRate6MbpsBW10MHz");
    uint32_t packetSize = 1000; // bytes
    uint32_t numPackets = 1;
    double interval = 1.0; // seconds
    bool verbose = false;

    CommandLine cmd(__FILE__);

    cmd.AddValue("phyMode", "Wifi Phy mode", phyMode);
    cmd.AddValue("packetSize", "size of application packet sent", packetSize);
    cmd.AddValue("numPackets", "number of packets generated", numPackets);
    cmd.AddValue("interval", "interval (seconds) between packets", interval);
    cmd.AddValue("verbose", "turn on all WifiNetDevice log components", verbose);
    cmd.Parse(argc, argv);
    // Convert to time object
    Time interPacketInterval = Seconds(interval);

    NodeContainer c;
    c.Create(3);

    // The below set of helpers will help us to put together the wifi NICs we want
    YansWifiPhyHelper wifiPhy;
    YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default();
    Ptr<YansWifiChannel> channel = wifiChannel.Create();
    wifiPhy.SetChannel(channel);
    // ns-3 supports generate a pcap trace
    wifiPhy.SetPcapDataLinkType(WifiPhyHelper::DLT_IEEE802_11);
    NqosWaveMacHelper wifi80211pMac = NqosWaveMacHelper::Default();
    Wifi80211pHelper wifi80211p = Wifi80211pHelper::Default();
    if (verbose)
    {
        wifi80211p.EnableLogComponents(); // Turn on all Wifi 802.11p logging
    }

    wifi80211p.SetRemoteStationManager("ns3::ConstantRateWifiManager",
                                       "DataMode",
                                       StringValue(phyMode),
                                       "ControlMode",
                                       StringValue(phyMode));
    NetDeviceContainer devices = wifi80211p.Install(wifiPhy, wifi80211pMac, c);

    // Tracing
    wifiPhy.EnablePcap("wave-simple-80211p", devices);

    MobilityHelper mobility;
    Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator>();
    positionAlloc->Add(Vector(0.0, 0.0, 0.0));
    positionAlloc->Add(Vector(5.0, 0.0, 0.0));
    positionAlloc->Add(Vector(10.0, 0.0, 0.0));
    mobility.SetPositionAllocator(positionAlloc);
    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
    mobility.Install(c);

    InternetStackHelper internet;
    internet.Install(c);

    Ipv4AddressHelper ipv4;
    NS_LOG_INFO("Assign IP Addresses.");
    ipv4.SetBase("10.1.1.0", "255.255.255.0");
    Ipv4InterfaceContainer i = ipv4.Assign(devices);

    TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory");
    Ptr<Socket> recvSink = Socket::CreateSocket(c.Get(0), tid);
    InetSocketAddress local = InetSocketAddress(Ipv4Address::GetAny(), 80);
    recvSink->Bind(local);
    recvSink->SetRecvCallback(MakeCallback(&ReceivePacket));

    TypeId tid2 = TypeId::LookupByName("ns3::UdpSocketFactory");
    Ptr<Socket> recvSink2 = Socket::CreateSocket(c.Get(2), tid2);
    InetSocketAddress local2 = InetSocketAddress(Ipv4Address::GetAny(), 80);
    recvSink2->Bind(local2);
    recvSink2->SetRecvCallback(MakeCallback(&ReceivePacket));

    Ptr<Socket> source = Socket::CreateSocket(c.Get(1), tid);
    InetSocketAddress remote = InetSocketAddress(Ipv4Address("255.255.255.255"), 80);
    source->SetAllowBroadcast(true);
    source->Connect(remote);//source 表示广播发送节点
     

    Simulator::ScheduleWithContext(source->GetNode()->GetId(),
                                   Seconds(1.0),
                                   &GenerateTraffic,
                                   source,
                                   packetSize,
                                   numPackets,
                                   interPacketInterval);

    Simulator::Run();
    Simulator::Destroy();

    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,您需要下载和安装NS-3模拟器。然后,您可以使用以下代码创建所需的拓扑图: ```cpp #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/internet-module.h" #include "ns3/applications-module.h" using namespace ns3; NS_LOG_COMPONENT_DEFINE ("MyTopology"); int main (int argc, char *argv[]) { // 创建一个节点容器,包含5个中断节点,4个接收节点和5个发送节点 NodeContainer interruptNodes; interruptNodes.Create (5); NodeContainer receiverNodes; receiverNodes.Create (4); NodeContainer senderNodes; senderNodes.Create (5); // 创建两个网络容器,一个用于中断节点接收节点,另一个用于发送节点 NodeContainer interruptReceiverNodes = NodeContainer (interruptNodes, receiverNodes); NodeContainer allNodes = NodeContainer (interruptNodes, receiverNodes, senderNodes); // 创建一个点到点通信信道并将其连接到所有节点 PointToPointHelper p2p; p2p.SetDeviceAttribute ("DataRate", StringValue ("10Mbps")); p2p.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560))); NetDeviceContainer devices = p2p.Install (allNodes); // 创建一个Internet协议栈并为所有设备分配IP地址 InternetStackHelper stack; stack.Install (allNodes); Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer interfaces = address.Assign (devices); // 在接收节点上创建一个UDP应用程序,以便接收来自发送节点数据包 uint16_t port = 9; OnOffHelper onoff ("ns3::UdpSocketFactory", InetSocketAddress (interfaces.GetAddress (3), port)); onoff.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]")); onoff.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]")); onoff.SetAttribute ("DataRate", DataRateValue (DataRate ("10Mb/s"))); onoff.SetAttribute ("PacketSize", UintegerValue (1024)); ApplicationContainer recvApps = onoff.Install (receiverNodes); recvApps.Start (Seconds (1.0)); recvApps.Stop (Seconds (10.0)); // 在发送节点上创建一个UDP应用程序,以便向接收节点发送数据包 onoff.SetAttribute ("Remote", AddressValue (InetSocketAddress (interfaces.GetAddress (3), port))); ApplicationContainer sendApps = onoff.Install (senderNodes.Get (0)); sendApps.Start (Seconds (2.0)); sendApps.Stop (Seconds (9.0)); // 运行仿真器 Simulator::Run (); Simulator::Destroy (); return 0; } ``` 在上面的代码中,我们首先创建了三个节点容器,分别表示中断节点接收节点发送节点。然后,我们创建了两个网络容器,一个包含中断节点接收节点,另一个包含所有节点。接下来,我们使用PointToPointHelper创建了一个点到点通信信道,并将其连接到所有节点。然后,我们使用InternetStackHelper创建了一个Internet协议栈,并为所有设备分配了IP地址。在接收节点上,我们创建了一个UDP应用程序,以便接收来自发送节点数据包。在发送节点上,我们创建了一个UDP应用程序,以便向接收节点发送数据包。最后,我们运行仿真器并销毁它。 请注意,上述代码仅仅是一个示例,您需要根据您的具体需求进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值