A Discrete-Event Network Simulator
API
topology-example-sim.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * This program is free software; you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License version 2 as
5  * published by the Free Software Foundation;
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15  *
16  * Author: Tommaso Pecorella <tommaso.pecorella@unifi.it>
17  * Author: Valerio Sartini <valesar@gmail.com>
18  *
19  * This program conducts a simple experiment: It builds up a topology based on
20  * either Inet or Orbis trace files. A random node is then chosen, and all the
21  * other nodes will send a packet to it. The TTL is measured and reported as an histogram.
22  *
23  */
24 
25 #include <ctime>
26 
27 #include <sstream>
28 
29 #include "ns3/core-module.h"
30 #include "ns3/network-module.h"
31 #include "ns3/internet-module.h"
32 #include "ns3/point-to-point-module.h"
33 #include "ns3/applications-module.h"
34 #include "ns3/ipv4-static-routing-helper.h"
35 #include "ns3/ipv4-list-routing-helper.h"
36 #include "ns3/ipv4-nix-vector-helper.h"
37 
38 #include "ns3/topology-read-module.h"
39 #include <list>
40 
41 using namespace ns3;
42 
43 NS_LOG_COMPONENT_DEFINE ("TopologyCreationExperiment");
44 
45 static std::list<unsigned int> data;
46 
47 static void SinkRx (Ptr<const Packet> p, const Address &ad)
48 {
49  Ipv4Header ipv4;
50  p->PeekHeader (ipv4);
51  std::cout << "TTL: " << (unsigned)ipv4.GetTtl () << std::endl;
52 }
53 
54 
55 // ----------------------------------------------------------------------
56 // -- main
57 // ----------------------------------------------
58 int main (int argc, char *argv[])
59 {
60 
61  std::string format ("Inet");
62  std::string input ("src/topology-read/examples/Inet_small_toposample.txt");
63 
64  // Set up command line parameters used to control the experiment.
66  cmd.AddValue ("format", "Format to use for data input [Orbis|Inet|Rocketfuel].",
67  format);
68  cmd.AddValue ("input", "Name of the input file.",
69  input);
70  cmd.Parse (argc, argv);
71 
72 
73  // ------------------------------------------------------------
74  // -- Read topology data.
75  // --------------------------------------------
76 
77  // Pick a topology reader based in the requested format.
78  TopologyReaderHelper topoHelp;
79  topoHelp.SetFileName (input);
80  topoHelp.SetFileType (format);
81  Ptr<TopologyReader> inFile = topoHelp.GetTopologyReader ();
82 
84 
85  if (inFile != 0)
86  {
87  nodes = inFile->Read ();
88  }
89 
90  if (inFile->LinksSize () == 0)
91  {
92  NS_LOG_ERROR ("Problems reading the topology file. Failing.");
93  return -1;
94  }
95 
96  // ------------------------------------------------------------
97  // -- Create nodes and network stacks
98  // --------------------------------------------
99  NS_LOG_INFO ("creating internet stack");
101 
102  // Setup NixVector Routing
103  Ipv4NixVectorHelper nixRouting;
104  Ipv4StaticRoutingHelper staticRouting;
105 
106  Ipv4ListRoutingHelper listRH;
107  listRH.Add (staticRouting, 0);
108  listRH.Add (nixRouting, 10);
109 
110  stack.SetRoutingHelper (listRH); // has effect on the next Install ()
111  stack.Install (nodes);
112 
113  NS_LOG_INFO ("creating ip4 addresses");
115  address.SetBase ("10.0.0.0", "255.255.255.252");
116 
117  int totlinks = inFile->LinksSize ();
118 
119  NS_LOG_INFO ("creating node containers");
120  NodeContainer* nc = new NodeContainer[totlinks];
122  int i = 0;
123  for ( iter = inFile->LinksBegin (); iter != inFile->LinksEnd (); iter++, i++ )
124  {
125  nc[i] = NodeContainer (iter->GetFromNode (), iter->GetToNode ());
126  }
127 
128  NS_LOG_INFO ("creating net device containers");
129  NetDeviceContainer* ndc = new NetDeviceContainer[totlinks];
130  PointToPointHelper p2p;
131  for (int i = 0; i < totlinks; i++)
132  {
133  // p2p.SetChannelAttribute ("Delay", TimeValue(MilliSeconds(weight[i])));
134  p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
135  p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
136  ndc[i] = p2p.Install (nc[i]);
137  }
138 
139  // it crates little subnets, one for each couple of nodes.
140  NS_LOG_INFO ("creating ipv4 interfaces");
141  Ipv4InterfaceContainer* ipic = new Ipv4InterfaceContainer[totlinks];
142  for (int i = 0; i < totlinks; i++)
143  {
144  ipic[i] = address.Assign (ndc[i]);
145  address.NewNetwork ();
146  }
147 
148 
149  uint32_t totalNodes = nodes.GetN ();
150  Ptr<UniformRandomVariable> unifRandom = CreateObject<UniformRandomVariable> ();
151  unifRandom->SetAttribute ("Min", DoubleValue (0));
152  unifRandom->SetAttribute ("Max", DoubleValue (totalNodes - 1));
153 
154  unsigned int randomServerNumber = unifRandom->GetInteger (0, totalNodes - 1);
155 
156  Ptr<Node> randomServerNode = nodes.Get (randomServerNumber);
157  Ptr<Ipv4> ipv4Server = randomServerNode->GetObject<Ipv4> ();
158  Ipv4InterfaceAddress iaddrServer = ipv4Server->GetAddress (1,0);
159  Ipv4Address ipv4AddrServer = iaddrServer.GetLocal ();
160 
161  // ------------------------------------------------------------
162  // -- Send around packets to check the ttl
163  // --------------------------------------------
164  Config::SetDefault ("ns3::Ipv4RawSocketImpl::Protocol", StringValue ("2"));
165  InetSocketAddress dst = InetSocketAddress ( ipv4AddrServer );
166 
167  OnOffHelper onoff = OnOffHelper ("ns3::Ipv4RawSocketFactory", dst);
168  onoff.SetConstantRate (DataRate (15000));
169  onoff.SetAttribute ("PacketSize", UintegerValue (1200));
170 
171  NodeContainer clientNodes;
172  for ( unsigned int i = 0; i < nodes.GetN (); i++ )
173  {
174  if (i != randomServerNumber )
175  {
176  Ptr<Node> clientNode = nodes.Get (i);
177  clientNodes.Add (clientNode);
178  }
179  }
180 
181  ApplicationContainer apps = onoff.Install (clientNodes);
182  apps.Start (Seconds (1.0));
183  apps.Stop (Seconds (2.0));
184 
185  PacketSinkHelper sink = PacketSinkHelper ("ns3::Ipv4RawSocketFactory", dst);
186  apps = sink.Install (randomServerNode);
187  apps.Start (Seconds (0.0));
188  apps.Stop (Seconds (3.0));
189 
190  // we trap the packet sink receiver to extract the TTL.
191  Config::ConnectWithoutContext ("/NodeList/*/ApplicationList/*/$ns3::PacketSink/Rx",
192  MakeCallback (&SinkRx));
193 
194  // ------------------------------------------------------------
195  // -- Run the simulation
196  // --------------------------------------------
197  NS_LOG_INFO ("Run Simulation.");
198  Simulator::Run ();
200 
201  delete[] ipic;
202  delete[] ndc;
203  delete[] nc;
204 
205  NS_LOG_INFO ("Done.");
206 
207  return 0;
208 
209  // end main
210 }
holds a vector of ns3::Application pointers.
an Inet address class
holds a vector of std::pair of Ptr and interface index.
Ptr< T > GetObject(void) const
Get a pointer to the requested aggregated Object.
Definition: object.h:455
Hold variables of type string.
Definition: string.h:41
NetDeviceContainer Install(NodeContainer c)
ConstLinksIterator LinksBegin(void) const
Returns an iterator to the the first link in this block.
static void Run(void)
Run the simulation.
Definition: simulator.cc:200
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:201
Helper class that adds Nix-vector routing to nodes.
aggregate IP/TCP/UDP functionality to existing Nodes.
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:244
A helper to make it easier to instantiate an ns3::PacketSinkApplication on a set of nodes...
Build a set of PointToPointNetDevice objects.
void SetFileName(const std::string fileName)
Sets the input file name.
void SetDeviceAttribute(std::string name, const AttributeValue &value)
Set an attribute value to be propagated to each NetDevice created by the helper.
A helper to make it easier to instantiate an ns3::OnOffApplication on a set of nodes.
Definition: on-off-helper.h:42
tuple cmd
Definition: second.py:35
a polymophic address class
Definition: address.h:90
Ptr< TopologyReader > GetTopologyReader()
Gets a Ptr to the actual TopologyReader.
uint32_t GetN(void) const
Get the number of Ptr stored in this container.
tuple nodes
Definition: first.py:25
Class for representing data rates.
Definition: data-rate.h:88
Packet header for IPv4.
Definition: ipv4-header.h:31
virtual uint32_t GetInteger(void)=0
Get the next random value as an integer drawn from the distribution.
int LinksSize(void) const
Returns the number of links in this block.
static void SinkRx(Ptr< const Packet > p, const Address &ad)
Hold an unsigned integer type.
Definition: uinteger.h:44
holds a vector of ns3::NetDevice pointers
Callback< R > MakeCallback(R(T::*memPtr)(void), OBJ objPtr)
Definition: callback.h:1480
void ConnectWithoutContext(std::string path, const CallbackBase &cb)
Definition: config.cc:824
void SetFileType(const std::string fileType)
Sets the input file type.
void Start(Time start)
Arrange for all of the Applications in this container to Start() at the Time given as a parameter...
Parse command-line arguments.
Definition: command-line.h:201
static void Destroy(void)
Execute the events scheduled with ScheduleDestroy().
Definition: simulator.cc:164
Access to the Ipv4 forwarding table, interfaces, and configuration.
Definition: ipv4.h:76
std::list< Link >::const_iterator ConstLinksIterator
Constant iterator to the list of the links.
uint32_t PeekHeader(Header &header) const
Deserialize but does not remove the header from the internal buffer.
Definition: packet.cc:276
Every class exported by the ns3 library is enclosed in the ns3 namespace.
void SetConstantRate(DataRate dataRate, uint32_t packetSize=512)
Helper function to set a constant rate source.
keep track of a set of node pointers.
static std::list< unsigned int > data
void Install(std::string nodeName) const
Aggregate implementations of the ns3::Ipv4, ns3::Ipv6, ns3::Udp, and ns3::Tcp classes onto the provid...
void Add(const Ipv4RoutingHelper &routing, int16_t priority)
tuple stack
Definition: first.py:34
void SetChannelAttribute(std::string name, const AttributeValue &value)
Set an attribute value to be propagated to each Channel created by the helper.
Helper class which makes it easier to configure and use a generic TopologyReader. ...
Ipv4 addresses are stored in host order in this class.
Definition: ipv4-address.h:40
void Stop(Time stop)
Arrange for all of the Applications in this container to Stop() at the Time given as a parameter...
Ipv4InterfaceContainer Assign(const NetDeviceContainer &c)
Assign IP addresses to the net devices specified in the container based on the current network prefix...
void Add(NodeContainer other)
Append the contents of another NodeContainer to the end of this container.
a class to store IPv4 address information on an interface
Helper class that adds ns3::Ipv4StaticRouting objects.
void AddValue(const std::string &name, const std::string &help, T &value)
Add a program argument, assigning to POD.
Definition: command-line.h:491
virtual Ipv4InterfaceAddress GetAddress(uint32_t interface, uint32_t addressIndex) const =0
Because addresses can be removed, the addressIndex is not guaranteed to be static across calls to thi...
Ptr< Node > Get(uint32_t i) const
Get the Ptr stored in this container at a given index.
virtual NodeContainer Read(void)=0
Main topology reading function.
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:895
void SetDefault(std::string name, const AttributeValue &value)
Definition: config.cc:774
Ipv4Address NewNetwork(void)
Increment the network number and reset the IP address counter to the base value provided in the SetBa...
Helper class that adds ns3::Ipv4ListRouting objects.
ApplicationContainer Install(NodeContainer c) const
Install an ns3::PacketSinkApplication on each node of the input container configured with all the att...
void Parse(int argc, char *argv[])
Parse the program arguments.
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
#define NS_LOG_ERROR(msg)
Use NS_LOG to output a message of level LOG_ERROR.
Definition: log.h:220
uint8_t GetTtl(void) const
Definition: ipv4-header.cc:265
tuple address
Definition: first.py:37
This class can be used to hold variables of floating point type such as 'double' or 'float'...
Definition: double.h:41
void SetAttribute(std::string name, const AttributeValue &value)
Set a single attribute, raising fatal errors if unsuccessful.
Definition: object-base.cc:191
ApplicationContainer Install(NodeContainer c) const
Install an ns3::OnOffApplication on each node of the input container configured with all the attribut...
void SetRoutingHelper(const Ipv4RoutingHelper &routing)
void SetAttribute(std::string name, const AttributeValue &value)
Helper function used to set the underlying application attributes.
ConstLinksIterator LinksEnd(void) const
Returns an iterator to the the last link in this block.
void SetBase(Ipv4Address network, Ipv4Mask mask, Ipv4Address base="0.0.0.1")
Set the base network number, network mask and base address.