Skip to content

Instantly share code, notes, and snippets.

@hyhilman
Last active December 15, 2017 22:22
Show Gist options
  • Save hyhilman/14dcd29a7259f32b031140b1271e9335 to your computer and use it in GitHub Desktop.
Save hyhilman/14dcd29a7259f32b031140b1271e9335 to your computer and use it in GitHub Desktop.
Aodv routing with randomwalk mobility, CBR data sending, netflowmonitoring, and routing table export
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2009 IITP RAS
*
* 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
*
* This is an example script for AODV manet routing protocol.
*
* Authors: Pavel Boyko <boyko@iitp.ru>
*/
#include "ns3/aodv-module.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/flow-monitor-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/wifi-module.h"
#include "ns3/v4ping-helper.h"
#include "ns3/netanim-module.h"
#include <iostream>
#include <cmath>
using namespace ns3;
class Aodv
{
public:
Aodv ();
bool Configure (int argc, char **argv);
void Run ();
void Report (std::ostream & os);
void RunRandomPing ();
void CheckThroughput();
Ptr<Socket> SetupPacketReceive (Ipv4Address addr, Ptr<Node> node);
void ReceivePacket (Ptr<Socket> socket);
static void CourseChange (std::string foo, Ptr<const MobilityModel> mobility)
{
Vector pos = mobility->GetPosition ();
Vector vel = mobility->GetVelocity ();
if ( pos.x > 490 || pos.x < 10 ||
pos.y > 490 || pos.y < 10 ) {
std::cout << Simulator::Now () << ", model=" << mobility << ", POS: x=" << pos.x << ", y=" << pos.y
<< ", z=" << pos.z << "; VEL:" << vel.x << ", y=" << vel.y
<< ", z=" << vel.z << ". Walking near the bound!!" << std::endl;
}
};
static inline std::string PrintReceivedPacket (Ptr<Socket> socket, Ptr<Packet> packet, Address senderAddress)
{
std::ostringstream oss;
oss << Simulator::Now ().GetSeconds () << " " << socket->GetNode ()->GetId ();
if (InetSocketAddress::IsMatchingType (senderAddress)) {
InetSocketAddress addr = InetSocketAddress::ConvertFrom (senderAddress);
oss << " received one packet from " << addr.GetIpv4 ();
} else {
oss << " received one packet!";
}
return oss.str ();
}
private:
uint32_t size, packetsReceived=0, bytesTotal=0, port=9;
double step, time, txp;
std::string protocol="aodv", dataRate = "2";
bool pcap, printRoutes, netflowMonitor;
NodeContainer nodes;
NetDeviceContainer devices;
Ipv4InterfaceContainer interfaces;
std::ostringstream filename;
private:
void CreateNodes ();
/// Create the devices
void CreateDevices ();
/// Create the network
void InstallInternetStack ();
/// Create the simulation applications
void InstallApplications ();
};
int main (int argc, char **argv)
{
Aodv test;
if (!test.Configure (argc, argv))
NS_FATAL_ERROR ("Configuration failed. Aborted.");
test.Run ();
test.Report (std::cout);
return 0;
}
Aodv::Aodv() :
size (20),
step (500),
time (20),
txp(7.5),
dataRate ("2"), // "5_5", "11"
pcap (true),
printRoutes (true),
netflowMonitor (true)
{}
bool Aodv::Configure (int argc, char **argv)
{
SeedManager::SetSeed (12345);
CommandLine cmd;
cmd.AddValue ("pcap", "Write PCAP traces.", pcap);
cmd.AddValue ("printRoutes", "Print routing table dumps.", printRoutes);
cmd.AddValue ("size", "Number of nodes.", size);
cmd.AddValue ("time", "Simulation time, s.", time);
cmd.AddValue ("step", "Grid step, m", step);
cmd.Parse (argc, argv);
return true;
}
void Aodv::Run ()
{
filename << dataRate << "Mbps-" << std::to_string (size) << "nodes";
CreateNodes ();
CreateDevices ();
InstallInternetStack ();
std::ofstream out ("aodv_throughput-" + filename.str () + ".output.csv");
out << "SimulationSecond,"
<< "ReceiveRate,"
<< "PacketsReceived,"
<< "NumberOfSinks,"
<< "RoutingProtocol,"
<< "TransmissionPower"
<< std::endl;
out.close ();
CheckThroughput();
InstallApplications ();
std::cout << "Starting simulation for " << time << " s ...\n";
AnimationInterface anim ("aodv_anim-" + filename.str () + ".xml");
anim.SetMobilityPollInterval (Seconds (1));
anim.EnablePacketMetadata (true);
// Flow monitor
FlowMonitorHelper flowmonHelper;
if(netflowMonitor)
flowmonHelper.InstallAll ();
Simulator::Stop (Seconds (time));
Simulator::Run ();
if(netflowMonitor) {
flowmonHelper.SerializeToXmlFile("aodv_flowmonitor-" + filename.str () + ".xml", false, false);
}
Simulator::Destroy ();
}
void Aodv::Report (std::ostream &)
{
}
void Aodv::CreateNodes ()
{
std::cout << "Creating " << (unsigned)size << " nodes " << step << " m apart.\n";
nodes.Create (size);
for (uint32_t i = 0; i < size; ++i) {
std::ostringstream os;
os << "node-" << i;
Names::Add (os.str (), nodes.Get (i));
}
MobilityHelper mobility;
// // location list
// Ptr<ListPositionAllocator> positionAlloc = CreateObject <ListPositionAllocator>();
// for (size_t i = 0; i < size; i++) {
// double x, y;
// x = ( (double)rand() / (double)RAND_MAX ) * step;
// y = ( (double)rand() / (double)RAND_MAX ) * step;
// std::cout << "set node-" << i << " to " << x << "," << y << "...\n";
// positionAlloc->Add(Vector(x, y, 0));
// }
// mobility.SetPositionAllocator(positionAlloc);
// // grid position
// mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
// "MinX", DoubleValue (0),
// "MinY", DoubleValue (0),
// "DeltaX", DoubleValue (step/sqrt(size)),
// "DeltaY", DoubleValue (step/sqrt(size)),
// "GridWidth", UintegerValue (sqrt(size)));
// random in rectangle
mobility.SetPositionAllocator ( "ns3::RandomRectanglePositionAllocator",
"X", StringValue ("ns3::UniformRandomVariable"
"[Min=" + std::to_string(0) +
"|Max=" + std::to_string(step) + "]"),
"Y", StringValue ("ns3::UniformRandomVariable"
"[Min=" + std::to_string(0) +
"|Max=" + std::to_string(step) + "]"));
// // random around corner
// mobility.SetPositionAllocator ( "ns3::RandomDiscPositionAllocator",
// "X", StringValue (std::to_string(step/2)),
// "Y", StringValue (std::to_string(step/2)),
// "Rho", StringValue ("ns3::UniformRandomVariable"
// "[Min=" + std::to_string(-1*step/2) +
// "|Max=" + std::to_string(step/2) + "]"));
// // random walk mode Time
// mobility.SetMobilityModel ( "ns3::RandomWalk2dMobilityModel",
// "Mode", StringValue ("Time"),
// "Time", StringValue ("1s"),
// "Speed", StringValue ("ns3::ConstantRandomVariable[Constant=2.0]"),
// "Bounds", RectangleValue(Rectangle (0, 500, 0, 500))
// );
mobility.Install (nodes);
Config::Connect ("/NodeList/*/$ns3::MobilityModel/CourseChange",
MakeCallback (&CourseChange));
}
void Aodv::CreateDevices ()
{
WifiMacHelper wifiMac;
wifiMac.SetType ("ns3::AdhocWifiMac");
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
wifiPhy.SetChannel (wifiChannel.Create ());
WifiHelper wifi;
wifi.SetStandard (WIFI_PHY_STANDARD_80211b);
wifi.SetRemoteStationManager ( "ns3::ConstantRateWifiManager",
// "DataMode", StringValue ("OfdmRate6Mbps"),
"DataMode", StringValue ("DsssRate" + dataRate + "Mbps"),
"ControlMode", StringValue ("DsssRate" + dataRate + "Mbps"),
"RtsCtsThreshold", UintegerValue (0));
wifiPhy.Set ("TxPowerStart",DoubleValue (txp));
wifiPhy.Set ("TxPowerEnd", DoubleValue (txp));
devices = wifi.Install (wifiPhy, wifiMac, nodes);
if (pcap){
wifiPhy.EnablePcapAll ("aodv_pcap-" + filename.str ());
}
}
void Aodv::InstallInternetStack ()
{
AodvHelper aodv;
// you can configure AODV attributes here using aodv.Set(name, value)
InternetStackHelper stack;
stack.SetRoutingHelper (aodv); // has effect on the next Install ()
stack.Install (nodes);
Ipv4AddressHelper address;
address.SetBase ("10.0.0.0", "255.0.0.0");
interfaces = address.Assign (devices);
if (printRoutes) {
Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper> ("aodv_route-" + filename.str () + ".routes", std::ios::out);
aodv.PrintRoutingTableAllAt (Seconds (8), routingStream);
}
OnOffHelper onoff ("ns3::UdpSocketFactory",Address ());
onoff.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1.0]"));
onoff.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0.0]"));
for (uint32_t i = 0; i < size; i++) {
Ptr<Socket> sink = SetupPacketReceive (interfaces.GetAddress (i), nodes.Get (i));
AddressValue remoteAddress (InetSocketAddress (interfaces.GetAddress (i), port));
onoff.SetAttribute ("Remote", remoteAddress);
Ptr<UniformRandomVariable> var = CreateObject<UniformRandomVariable> ();
ApplicationContainer temp = onoff.Install (nodes.Get ( (i + 1) % size ));
temp.Start (Seconds (var->GetValue (10.0,11.0)));
temp.Stop (Seconds (time));
}
}
Ptr<Socket> Aodv::SetupPacketReceive (Ipv4Address addr, Ptr<Node> node)
{
TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
Ptr<Socket> sink = Socket::CreateSocket (node, tid);
InetSocketAddress local = InetSocketAddress (addr, port);
sink->Bind (local);
sink->SetRecvCallback (MakeCallback (&Aodv::ReceivePacket, this));
return sink;
}
void Aodv::InstallApplications ()
{
// V4PingHelper ping (interfaces.GetAddress (size - 1));
// ping.SetAttribute ("Verbose", BooleanValue (true));
//
// ApplicationContainer p = ping.Install (nodes.Get (0));
// p.Start (Seconds (0));
// p.Stop (Seconds (time) - Seconds (0.001));
//
// // move node away
// Ptr<Node> node = nodes.Get (size/2);
// Ptr<MobilityModel> mob = node->GetObject<MobilityModel> ();
// Simulator::Schedule (Seconds (time/3), &MobilityModel::SetPosition, mob, Vector (1e5, 1e5, 1e5));
// RunRandomPing();
}
void Aodv::RunRandomPing()
{
int src, dst;
src = (int)( ( (double)rand() / (double)RAND_MAX ) * ( size - 1 ) ) ;
dst = (int)( ( (double)rand() / (double)RAND_MAX ) * ( size - 1 ) ) ;
std::cout << "Doing ping from node-" << src << "(" << interfaces.GetAddress (src)
<< ") to node-" << dst << "(" << interfaces.GetAddress (dst) << ")"
<< std::endl;
V4PingHelper ping (interfaces.GetAddress (src));
ping.SetAttribute ("Verbose", BooleanValue (true));
ApplicationContainer p = ping.Install (nodes.Get (dst));
p.Start (Seconds (0));
p.Stop (Seconds (time) - Seconds (0.001));
}
void Aodv::CheckThroughput ()
{
double kbs = (bytesTotal * 8.0) / 1000;
bytesTotal = 0;
std::ofstream out ("aodv_throughput-" + filename.str () + ".output.csv", std::ios::app);
out << (Simulator::Now ()).GetSeconds () << ","
<< kbs << ","
<< packetsReceived << ","
<< size << ","
<< protocol << ","
<< txp << ""
<< std::endl;
out.close ();
packetsReceived = 0;
Simulator::Schedule (Seconds (1.0), &Aodv::CheckThroughput, this);
}
void Aodv::ReceivePacket (Ptr<Socket> socket)
{
Ptr<Packet> packet;
Address senderAddress;
while ((packet = socket->RecvFrom (senderAddress))) {
bytesTotal += packet->GetSize ();
packetsReceived += 1;
NS_LOG_UNCOND (PrintReceivedPacket (socket, packet, senderAddress));
}
}
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-netanim
def build(bld):
obj = bld.create_ns3_program('tugas2_aodv',
['netanim','wifi', 'internet', 'aodv', 'internet-apps', 'flow-monitor'])
obj.source = 'tugas2_aodv.cc'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment