1. 程式人生 > >兩種寫程式碼的風格(從簡而一)

兩種寫程式碼的風格(從簡而一)

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

#include "ns3/core-module.h"///直接一個個建立,先建立好節點
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("Project1"
); NodeContainer coreNode, aggNodes, torNodes, serverNodes; NodeContainer l1Nodes[2], l2Nodes[2], l3Nodes[4]; NetDeviceContainer l1Devices[2], l2Devices[2], l3Devices[4]; Ipv4InterfaceContainer l1Interfaces[2], l2Interfaces[2], l3Interfaces[4]; PointToPointHelper pointToPoint; CsmaHelper csma; void addNodes(NodeContainer *targetContainer, NodeContainer *sourceContainer, int startIndex, int count) { for(int i = 0
; i < count ; i++) targetContainer->Add(sourceContainer->Get(startIndex + i)); } void createTopogy() { coreNode.Create(1); aggNodes.Create(2); torNodes.Create(4); serverNodes.Create(8); pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("1.5Mbps")); pointToPoint.SetChannelAttribute
("Delay", TimeValue(NanoSeconds(500))); for(int i = 0; i < 2; i++) { addNodes(&l1Nodes[i], &coreNode, 0, 1); addNodes(&l1Nodes[i], &aggNodes, i, 1); l1Devices[i] = pointToPoint.Install(l1Nodes[i]); } csma.SetChannelAttribute ("DataRate", StringValue ("1Mbps")); csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (500))); for(int i = 0; i < 2; i++) { addNodes(&l2Nodes[i], &aggNodes, i, 1); addNodes(&l2Nodes[i], &torNodes, i*2, 2); l2Devices[i] = csma.Install(l2Nodes[i]); } for(int i = 0; i < 4; i++) { addNodes(&l3Nodes[i], &torNodes, i, 1); addNodes(&l3Nodes[i], &serverNodes, i*2, 2); l3Devices[i] = csma.Install(l3Nodes[i]); } } void internetStackInstall() { InternetStackHelper stack; stack.Install(coreNode); stack.Install(aggNodes); stack.Install(torNodes); stack.Install(serverNodes); } void setIP() { for(int i = 0; i < 2; i++) { Ipv4AddressHelper address; char ip[16] = "192.168.i.0"; ip[8] = i + 1 + '0'; address.SetBase (ip, "255.255.255.0"); l1Interfaces[i] = address.Assign (l1Devices[i]); } for(int i = 0; i < 2; i++) { Ipv4AddressHelper address; char ip[16] = "10.i.0.0"; ip[3] = i + 1 + '0'; address.SetBase (ip, "255.255.255.0"); l2Interfaces[i] = address.Assign (l2Devices[i]); } for(int i = 0; i < 4; i++) { Ipv4AddressHelper address; char ip[16] = "10.0.i.0"; ip[5] = i + 1 + '0'; address.SetBase (ip, "255.255.255.0"); l3Interfaces[i] = address.Assign (l3Devices[i]); } } int main(int argc, char *argv[]) { bool verbose = true; int pattern = 1; CommandLine cmd; cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose); cmd.AddValue ("pattern", "Choose a pattern for simulation", pattern); cmd.Parse (argc,argv); LogComponentEnable("Project1", LOG_LEVEL_INFO); if (verbose) { LogComponentEnable ("PacketSink", LOG_LEVEL_INFO); LogComponentEnable ("OnOffApplication", LOG_LEVEL_INFO); } createTopogy(); internetStackInstall(); setIP(); if(pattern == 1) { int16_t sinkPort = 8080; PacketSinkHelper packetSinkHelper("ns3::TcpSocketFactory",InetSocketAddress(Ipv4Address::GetAny(),sinkPort)); ApplicationContainer sinkApps[4]; ApplicationContainer clientApps[4]; for(int i = 0; i < 4; i++) { sinkApps[i] = packetSinkHelper.Install(serverNodes.Get(i)); sinkApps[i].Start(Seconds(0)); sinkApps[i].Stop(Seconds(50)); OnOffHelper client("ns3::TcpSocketFactory", InetSocketAddress(l3Interfaces[i/2].GetAddress (i%2 + 1), sinkPort)); client.SetAttribute ("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=50]")); client.SetAttribute ("OffTime", StringValue("ns3::ConstantRandomVariable[Constant=0]")); client.SetAttribute ("DataRate", DataRateValue (DataRate ("1.5Mbps"))); client.SetAttribute ("PacketSize", UintegerValue (2000)); clientApps[i] = client.Install (serverNodes.Get (i+4)); clientApps[i].Start(Seconds (1.0 )); clientApps[i].Stop (Seconds (51.0)); } pointToPoint.EnablePcapAll ("p1p2p"); csma.EnablePcapAll("p1csma"); Simulator::Stop (Seconds(50)); } else if(pattern == 2) { int16_t sinkPort = 8080; PacketSinkHelper packetSinkHelper("ns3::TcpSocketFactory",InetSocketAddress(Ipv4Address::GetAny(),sinkPort)); ApplicationContainer sinkApps; sinkApps = packetSinkHelper.Install(serverNodes.Get(0)); sinkApps.Start(Seconds(0)); sinkApps.Stop(Seconds(50)); ApplicationContainer clientApps[7]; for(int i = 0; i < 7; i++) { OnOffHelper client("ns3::TcpSocketFactory", InetSocketAddress(l3Interfaces[0].GetAddress(1), sinkPort)); client.SetAttribute ("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=50]")); client.SetAttribute ("OffTime", StringValue("ns3::ConstantRandomVariable[Constant=0]")); client.SetAttribute ("DataRate", DataRateValue (DataRate ("1.5Mbps"))); client.SetAttribute ("PacketSize", UintegerValue (2000)); clientApps[i] = client.Install (serverNodes.Get (i + 1)); clientApps[i].Start(Seconds (1.0 )); clientApps[i].Stop (Seconds (51.0)); } pointToPoint.EnablePcapAll ("p2p2p"); csma.EnablePcapAll("p2csma"); Simulator::Stop (Seconds(50)); } else NS_LOG_INFO("This project only contains pattern 1 and pattern 2!!!"); Ipv4GlobalRoutingHelper::PopulateRoutingTables (); Simulator::Run (); Simulator::Destroy (); return 0; }
/* -*- 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"//先從建立一個子樹開始逐漸建立整個拓撲
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include <string>
#include <sstream>
#include <iostream>

using namespace ns3;
using namespace std;


NS_LOG_COMPONENT_DEFINE ("ProjectScript");// This registers ProjectScript as a log component.

int 
main (int argc, char *argv[])
{
  bool verbose = true;
  uint32_t nCsma = 2;

  CommandLine cmd;
  cmd.AddValue ("nCsma", "Number of \"extra\" CSMA nodes/devices", nCsma);
  cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose);

  cmd.Parse (argc,argv);

  if (verbose)
    {
      //LogComponentEnable ("OnOffApplication", LOG_LEVEL_INFO);
     // LogComponentEnable ("PacketSink", LOG_LEVEL_INFO);
    }
      // if (verbose)
         //  {
         //     LogComponentEnable ("ProjectScript", LOG_LEVEL_INFO);
         //  }


  nCsma = nCsma == 0 ? 1 : nCsma;


  NodeContainer rootNode;
  rootNode.Create (1);

  NodeContainer leafNodes; 
  Ipv4InterfaceContainer  leafNodeIpv4Container;

  PointToPointHelper * ptrP2P[2];

  for (int iAggNode=0;iAggNode<2;iAggNode++)
        {
              NodeContainer aggregationNode;//Will have  one aggregationNode and one root node
              aggregationNode.Create (1);

              NodeContainer toRNodesContainer;//Will have one aggregationNode and two ToR Nodes
              toRNodesContainer.Add(aggregationNode.Get(0));

              aggregationNode.Add(rootNode.Get(0));          


              //need for two toRNodes per aggregationNode         

              for (int iToR=0;iToR<2;iToR++)
                {
                  NodeContainer toRNode;
                  toRNode.Create (1);
                  toRNodesContainer.Add (toRNode.Get (0));

                  NodeContainer csmaNodesLeafToR;//Will have two leafNodes and one ToR node
                  csmaNodesLeafToR.Create (nCsma);
                  csmaNodesLeafToR.Add (toRNode.Get (0));

                  leafNodes.Add(csmaNodesLeafToR.Get(0));//Will have all leafNodes
                  leafNodes.Add(csmaNodesLeafToR.Get(1));


                  CsmaHelper csma;
                  csma.SetChannelAttribute ("DataRate", StringValue ("1Mbps"));
                  csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (500)));
                  NetDeviceContainer csmaDevicesLeafToR;
                  csmaDevicesLeafToR = csma.Install (csmaNodesLeafToR);//install csma


                  InternetStackHelper stack;     
                  stack.Install (csmaNodesLeafToR);//Every node can only be installed once(two two leafNodes and one ToR node)


                  int count=-1;
                  if(0==iAggNode)
                  {
                    count=1;
                  }
                  if(1==iAggNode)
                  {
                    count=2;
                  }

                  string ipv4BaseString="10.0.";      
                  stringstream stream;
                  string strNum="";
                  stream<<(iToR+iAggNode+count);
                  stream>>strNum;
                  stream.clear();
                  ipv4BaseString=ipv4BaseString+strNum+".0";
                  char const * cIpv4Base=ipv4BaseString.c_str();
                  cout<<"iAggNode: "<<iAggNode<<" iToR: "<<iToR<<" cIpv4StringBase:"<<cIpv4Base<<endl;             

                  Ipv4AddressHelper addressLeafToR;
                  addressLeafToR.SetBase (cIpv4Base, "255.255.255.0");//assign one ToR and two nodes ip
                  Ipv4InterfaceContainer leafToRInterfaces;
                  leafToRInterfaces = addressLeafToR.Assign (csmaDevicesLeafToR);

                  leafNodeIpv4Container.Add(leafToRInterfaces.Get(0));
                  leafNodeIpv4Container.Add(leafToRInterfaces.Get(1));

                }


              //********************************************************************//two ToRs and one aggregationNode assign ip
              CsmaHelper csmaAT;
              csmaAT.SetChannelAttribute ("DataRate", StringValue ("1Mbps"));
              csmaAT.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (500)));
              NetDeviceContainer csmaDevicesAT;
              csmaDevicesAT = csmaAT.Install (toRNodesContainer);              

              InternetStackHelper stack;     
              stack.Install (aggregationNode.Get(0));

              string aggBaseIpStr="10.";
              stringstream stream;
              string strNum="";             
              stream<<(iAggNode+1);
              stream>>strNum;
              //cout<<"strNum1"<<strNum<<endl;
              stream.clear();
              aggBaseIpStr=aggBaseIpStr+strNum+".1.0";
              char const * cAggIpv4Base=aggBaseIpStr.c_str();
              cout<<"iAggNode: "<<iAggNode<<" aggBaseIpStr:"<<aggBaseIpStr<<endl;         
              Ipv4AddressHelper address;
              address.SetBase (cAggIpv4Base, "255.255.255.0");//assign one ToR and two nodes ip
              Ipv4InterfaceContainer csmaInterfaces;
              csmaInterfaces = address.Assign (csmaDevicesAT);
              //******************************************************************************************


              //******************************************************//P2P:one aggregationNode and one RootNode
              PointToPointHelper * pointToPoint=new PointToPointHelper() ;
              pointToPoint->SetDeviceAttribute ("DataRate", StringValue ("1.5Mbps"));
              pointToPoint->SetChannelAttribute ("Delay", TimeValue (NanoSeconds (500)));







             NetDeviceContainer devicesP2p;
             devicesP2p = pointToPoint->Install (aggregationNode);//mac
             //cout<<devicesP2p<<endl;    

             if(0==iAggNode)
              {
              InternetStackHelper stackRoot;     
              stackRoot.Install (rootNode.Get(0));
              }       

             string rootBaseIpStr="192.168.";
             rootBaseIpStr=rootBaseIpStr+strNum+".0";
             char const * cRootIpv4Base=rootBaseIpStr.c_str();

             cout<<"iAggNode: "<<iAggNode<<" rootBaseIpStr:"<<rootBaseIpStr<<endl;
             Ipv4AddressHelper addressRoot;
             addressRoot.SetBase (cRootIpv4Base, "255.255.255.0");

             Ipv4InterfaceContainer interfacesP2p = addressRoot.Assign (devicesP2p);
              //*******************************************************************

             // if(iAggNode==1)
             // {
             // cout<<"strNum"<<strNum<<endl;
             // pointToPoint.EnablePcapAll (strNum+"Root");

             // }


             ptrP2P[iAggNode]=pointToPoint;




        }

      //network has been established! now choose connection pattern

      //**************************************Pattern 1*******************************************
      //*Pattern 1: inter-cluster traffic
      //*Each server communicates using TCP with another server that comes from different cluster
      //*For example, 1-5, 6-2, 3-7, 8-4
     //*******************************************************************************************

     //const int pairs=4;
     int i=0;
     //for(int i=0;i<pairs;i++)
        { uint16_t sinkPort = 8080;       
          Address sinkAddress (InetSocketAddress (leafNodeIpv4Container.GetAddress (i+4), sinkPort));
          PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", InetSocketAddress (Ipv4Address::GetAny (), sinkPort));
          ApplicationContainer sinkApps = packetSinkHelper.Install (leafNodes.Get (i+4));
          sinkApps.Start (Seconds (0.));//All Applications need to be provided with a starting simulation time and a stopping simulation time. The ApplicationContainer is a convenient place for allowing all of the contained Applications to be told to shut down and stop doing their thing (Stop) at a common time.
          sinkApps.Stop (Seconds (50.));


          OnOffHelper client("ns3::TcpSocketFactory", InetSocketAddress(leafNodeIpv4Container.GetAddress (i+4), sinkPort));
          client.SetAttribute ("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=50]"));
          client.SetAttribute ("OffTime", StringValue("ns3::ConstantRandomVariable[Constant=0]"));
          client.SetAttribute ("DataRate", DataRateValue (DataRate ("1Mbps")));
          client.SetAttribute ("PacketSize", UintegerValue (2000));
          ApplicationContainer clientApp = client.Install (leafNodes.Get (i));
          clientApp.Start(Seconds (1.0));
          clientApp.Stop (Seconds (51.0));



        }

  //implement here:
  Ipv4GlobalRoutingHelper::PopulateRoutingTables ();

  ptrP2P[0]->EnablePcapAll ("InRoot");
  for(int i=0;i<2;i++)
  {
    delete ptrP2P[i];
  }


  Simulator::Run ();
  Simulator::Destroy ();
  return 0;
}
//********************************
//install
// net driver install
// tcp/ip protocol install
// what proctocol use (tcp? udp?) 






//       //**************************************Pattern 2*******************************************
      //*Pattern 2: inter-cluster traffic
      //*Each server communicates using TCP with another server that comes from different cluster
      //*For example, 1-5, 6-2, 3-7, 8-4
     //*******************************************************************************************



















  // UdpEchoServerHelper echoServer (9);

  // ApplicationContainer serverApps = echoServer.Install (csmaNodes.Get (nCsma));
  // serverApps.Start (Seconds (1.0));
  // serverApps.Stop (Seconds (10.0));

  // UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (nCsma), 9);
  // echoClient.SetAttribute ("MaxPackets", UintegerValue (1));
  // echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0)));
  // echoClient.SetAttribute ("PacketSize", UintegerValue (1024));

  // ApplicationContainer clientApps = echoClient.Install (p2pNodes.Get (0));
  // clientApps.Start (Seconds (2.0));
  // clientApps.Stop (Seconds (10.0));


  //Pattern 1: inter-cluster traffic
//Each server communicates using TCP with another server that comes from different cluster
//For example, 1-5, 6-2, 3-7, 8-4