0% found this document useful (0 votes)
117 views48 pages

52 Lakshita Malhotra ASNFile

Kejrtjjdjddjfjddjd d f. Gg g ht y y t tu y y y tt t t t t tt t t r r et t t r 3 e r tr e er f g. Gg u y t re e w dr e e e e rr e e er r e e we r r e e e 3.

Uploaded by

Vishal Choudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views48 pages

52 Lakshita Malhotra ASNFile

Kejrtjjdjddjfjddjd d f. Gg g ht y y t tu y y y tt t t t t tt t t r r et t t r 3 e r tr e er f g. Gg u y t re e w dr e e e e rr e e er r e e we r r e e e 3.

Uploaded by

Vishal Choudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Ad-hoc and Sensor

Networks Lab

Information Technology Department

MAHARAJA SURAJMAL INSTITUTE OF TECHNOLOGY

GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY DELHI, INDIA

JUNE - 2021

Submitted to: Submitted By:

Mr. B K HEMANT Name: Vishal Choudhary


Enroll. No. : 40696303117
Class Sr. No.: 31
B.Tech – IT - Evening (Sem 8)
INDEX

1. Study of Simulator for Ad hoc and Wireless Sensor Network 3

2. To implement Energy Model in NS-3 6

3. To implement Mixed Global Routing Protocol in NS-3 13

4. To implement Simple Global Routing Protocol in NS-3 17

5. Study and compare DSR, DSDV and AODV routing algorithms 22

6. Study of P2P Net Devices and P2P Model and P2P Channel in NS-3 27

7. Create a UDP Client application to send UDP datagrams from node 0 to 1 31

8. Implement Socket Bound Static Routing In NS-3 Simulator 36


PRACTICAL - 1

AIM: Study of Simulator for Ad hoc and Wireless Sensor Network

THEORY:
The ns-3 simulator is a discrete-event network simulator targeted primarily for research and
educational use. The ns-3 project, started in 2006, is an open-source project developing ns-3.

The purpose of this tutorial is to introduce new ns-3 users to the system in a structured way. It is
sometimes difficult for new users to glean information from detailed manuals and to convert this
information into working simulations. In this tutorial, we will build several example simulations,
introducing and explaining key concepts and features as we go.
As the tutorial unfolds, we will introduce the full ns-3 documentation and provide pointers to source
code for those interested in delving deeper into the workings of the system. A few key points are worth
noting at the onset:

● Ns-3 is open-source, and the project strives to maintain and open environment for researchers
to contribute and share their software.
● Ns-3 is not a backwards-compatible extension of ns-2; it is a new simulation. The two simulators
are both written in C++ but ns-3 is a new simulator that does not support ns-2 APIs. Some
models from ns-2 have already been ported from ns-2 to ns-3. The project will continue to
maintain ns-2 while ns-2 is being built, and will study transition and integration mechanisms.

About ns-3:
ns-3 has been developed to provide an open, extensible network simulation platform, for networking
research and education. In brief, ns-3 provides models of how packet data networks work and
perform, and provides a simulation engine for users to conduct simulation experiments. Some of the
reasons to use ns-3 include to perform studies that are more difficult or not possible to perform with
real systems, to study system behaviour in a highly controlled, reproducible environment, and to learn
about how networks work. Users will note that the available model set in ns-3 focuses on modeling
how Internet protocols and networks work, but ns-3 is not limited to Internet systems; several users
are using ns-3
to model non-Internet-based systems.

Many simulation tools exist for network simulation studies. Below are a few distinguishing features
of ns-3 in contrast to other tools:

● ns-3 is designed as a set of libraries that can be combined together and also work with other
external software libraries. While some simulation platforms provide users with a single,
integrated graphical user interface environment in which all tasks are carried out, ns-3 is more
popular in this regard. Several external animators and data analysis and visualization tools can be
used with ns-3. However, users should expect to work at the command line and with C++ and/or
Python software development tools.
● ns-3 is primarily used for Linux systems, although support exists for FreeBSD, Cygwin
(for Windows), and native Windows Visual Studio support is in the process of being
developed.
● ns-3 is not an officially support software product of any company. Support for ns-3 is done on
a best-effort basis on the ns-3 users mailing list.

For ns-3 users:


For those familiar with ns-2 (a popular tool that preceded ns-3), the most visible change when moving
to ns-3 is the choice of scripting language. Programs in ns-2 are scripted in OTcl and results of
simulations can be visualized using Network Animator nam. It is not possible to run a simulation in
ns2 purely from C++ (i.e. as a main() program without any OTcl). Moreover, some components of
ns- 2 are written in C++ and others in OTcl. In ns-3, the simulator is written entirely in C++, with
optional Python bindings. Simulation scripts can therefore be written in C++ or Python. New
animators and visualizers are available and under current development. Since ns-3 generates pcap
packet trace files, other utilities can be used to analyze traces as well. In this tutorial, we will first
concentrate on scripting directly in C++ and then interpreting results vis trace files.
But there are similarities as well (both, for example, are based on C++ objects, and some code from
ns2 has already been ported to ns-3). We will try to highlight differences between ns-2 and ns-3 as we
proceed in this tutorial.

A question that we often hear is “Should I still use ns-2 or move to ns-3?” In this author’s opinion,
unless the user is somehow vested in ns-2(either based on existing personal comfort with knowledge
of ns-2, or based on a specific simulation model that is only available in ns-2), a user will be more
productive with ns-3 for the following reasons:

● ns-3 is actively maintained with an active, responsive users mailing list, while ns-2 is only lightly
maintained and has not been given significant development in its main code tree for over a
decade.
● NS-3 provides features not available in NS-2, such as implementation code execution
environment (allowing users to run real implementation code in the simulator).
● NS-3 provides a lower base level of abstraction compared with NS-2, allowing it to align better
with how real systems are put together. Some limitations found in ns-2(such as support multiple
types of interfaces on codes currently) have been remedied in NS-3.

NS-2 has a more diverse set of combined modules than NS-3 does, owing to its long history. However,
NS-3 has more detailed models in several popular areas of research (including sophisticated LTE and
WiFi models), and its support of implementation code admits a very wide
spectrum of high-fidelity models. Users may be surprised to learn that the whole Linux networking
stack can be encapsulated in an NS-3 mode, using Direct Code Execution (DCE) framework. NS-3
can model can sometimes be ported to NS-3, particularly if they have been implemented in C++.
If in doubt, a good guideline would be to look at both simulators (as well as other simulators), and in
particular the models available for your research, but keep in mind that your experience may be better
in using the tool that is being actively developed and contain(NS-3).

RESULT: Simulator for Ad hoc and Wireless Sensor Network have been studied.
PRACTICAL - 2

AIM: To implement Energy Model in NS-3

THEORY:
With the rapid progress of information and communication technologies (ICT) and the wide range of
applications in wireless sensor networks (WSN), the performance evaluation and analysis techniques
in WSN have made great progress. Classical evaluation techniques, such as the data or bits flow
analysis, the state transition modeling based on Markov and the model-driven architecture analysis,
have to face some new challenges. On one hand, it is the large scale of wireless sensor networks and
the huge amount of WSN nodes, which make the physical testing become very complex when the
costs and scales of WSN applications must be taken into account. On the other hand, it is the diversity
of system tasks and the complexity of application environments, which make mathematical
calculation become extremely complex when considering a large number of time-varying factors,
such as network traffics, wireless channels, and network topologies.
In addition, the power state and its transition correlations in most of classical energy models are
generally oversimplified, which normally focuses on RF transceivers but ignoring other components
may result in an imprecise evaluation especially when taking into account of the cases with heavy
workloads on processors and sensors. Due to the employment of these imprecise models in the
simulation tools (such as NS-2/3, SHAWN, and OPNET) or on the evaluation platforms, the
evaluation accuracy is deteriorated and the evaluation scopes of WSN applications are thus
constrained.

In the following experiment, a model to simulate the energy consumption behaviors of sensor nodes
and a case study to evaluate the energy consumption of WSN nodes is introduced.

CODE:
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/mobility-module.h"
#include "ns3/config-store-module.h"
#include "ns3/wifi-module.h"
#include "ns3/energy-module.h"
#include "ns3/internet-module.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("EnergyExample"); static
inline std::string
PrintReceivedPacket(Address &from) {
InetSocketAddress iaddr = InetSocketAddress::ConvertFrom(from);
std::ostringstream oss;
oss << "--\nReceived one packet! Socket: " << iaddr.GetIpv4()
<< " port: " << iaddr.GetPort()<< " at time = " << Simulator::Now().GetSeconds() << "\n--"; return
oss.str();
} void ReceivePacket(Ptr<Socket> socket) { Ptr<Packet> packet;Address
from; while ((packet = socket->RecvFrom(from))) { if (packet->GetSize() >
0) {
NS_LOG_UNCOND(PrintReceivedPacket(from));

}}}
static void GenerateTraffic(Ptr<Socket> socket, uint32_t pktSize, Ptr<Node> n, uint32_t pktCount,
Time pktInterval) { if (pktCount > 0) {
socket->Send(Create<Packet>(pktSize)); Simulator::Schedule(pktInterval, &GenerateTraffic, socket,
pktSize, n, pktCount - 1, pktInterval);} else {socket->Close();}}

void RemainingEnergy(double oldValue, double remainingEnergy)


{ NS_LOG_UNCOND(Simulator::Now().GetSeconds()
<< "s Current remaining energy = " << remainingEnergy << "J");
}
void TotalEnergy(double oldValue, double totalEnergy)
{ NS_LOG_UNCOND(Simulator::Now().GetSeconds()
<< "s Total energy consumed by radio = " << totalEnergy << "J");
}
int main(int argc, char *argv[]) {
/*
LogComponentEnable ("EnergySource", LOG_LEVEL_DEBUG); LogComponentEnable
("BasicEnergySource", LOG_LEVEL_DEBUG); LogComponentEnable ("DeviceEnergyModel",
LOG_LEVEL_DEBUG); LogComponentEnable ("WifiRadioEnergyModel",
LOG_LEVEL_DEBUG);
*/
std::string phyMode("DsssRate1Mbps"); double Prss = -80; // dBm uint32_t PpacketSize =
200; // bytes bool verbose = false; // simulation parameters
uint32_t numPackets = 10000; // number of packets to send double interval = 1; // seconds
double startTime = 0.0;
// seconds double distanceToRx = 100.0; // meters
/* This is a magic number used to set the transmit power, based on other configuration.*/ double
offset = 81; CommandLine cmd;
cmd.AddValue("phyMode", "Wifi Phy mode", phyMode); cmd.AddValue("Prss", "Intended primary
RSS (dBm)", Prss); cmd.AddValue("PpacketSize", "size of application packet sent", PpacketSize);
cmd.AddValue("numPackets", "Total number of packets to send", numPackets);
cmd.AddValue("startTime", "Simulation start time", startTime);
cmd.AddValue("distanceToRx", "X-Axis distance between nodes", distanceToRx);
cmd.AddValue("verbose", "Turn on all device log components", verbose); cmd.Parse(argc,argv);

// Convert to time object


Time interPacketInterval = Seconds(interval);
// disable fragmentation for frames below 2200 bytes
Config::SetDefault("ns3::WifiRemoteStationManager::FragmentationThreshold",
StringValue("2200"));
// turn off RTS/CTS for frames below 2200 bytes
Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold"
, StringValue("2200"));
// Fix non-unicast data rate to be the same as that of unicast

Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode”StringValue(phyMode));

NodeContainer c; reate(2);

// create 2 nodes
NodeContainer networkNodes; networkNodes.Add(c.Get(0));
networkNodes.Add(c.Get(1));
// The below set of helpers will help us to put together the wifi NICs we want WifiHelper wifi; if
(verbose)
{ wifi.EnableLogComponents();}
wifi.SetStandard(WIFI_PHY_STANDARD_80211b);
/************************************************************************* /
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default();
wifiPhy.Set("RxGain", DoubleValue(-10)); wifiPhy.Set("TxGain", DoubleValue(offset + Prss));
wifiPhy.Set("CcaMode1Threshold", DoubleValue(0.0));
/***************************************************************************/
YansWifiChannelHelper wifiChannel;
wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel");

// create wifi channel


Ptr<YansWifiChannel> wifiChannelPtr = wifiChannel.Create(); wifiPhy.SetChannel(wifiChannelPtr);

// Add a MAC and disable rate control WifiMacHelper


wifiMac;
wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",”DataMode,String , "ControlMode",
StringValue(phyMode));

// Set it to ad-hoc mode wifiMac.SetType("ns3::AdhocWifiMac");


NetDeviceContainer devices = wifi.Install(wifiPhy, wifiMac, networkNodes); MobilityHelper
mobility;
Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator>(); positionAlloc-
>Add(Vector(0.0, 0.0, 0.0));
positionAlloc->Add(Vector(2 * distanceToRx, 0.0, 0.0));
mobility.SetPositionAllocator(positionAlloc);
mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
mobility.Install(c);
************************************************************************** /
/* energy source */
BasicEnergySourceHelper basicSourceHelper;
// configure energy source basicSourceHelper.Set("BasicEnergySourceInitialEnergyJ",
DoubleValue(0.1));
// install source
EnergySourceContainer sources = basicSourceHelper.Install(c);
/* device energy model */
WifiRadioEnergyModelHelper radioEnergyHelper;
// configure radio energy model radioEnergyHelper.Set("TxCurrentA", DoubleValue(0.0174));

// install device model DeviceEnergyModelContainer deviceModels =


radioEnergyHelper.Install(devices,sources);
/***************************************************************************/
InternetStackHelper internet; internet.Install(networkNodes);
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(networkNodes.Get(1), tid);
// node 1,
receiver InetSocketAddress local = InetSocketAddress(Ipv4Address::GetAny(), 80); recvSink-
>Bind(local);
recvSink->SetRecvCallback(MakeCallback(&ReceivePacket));
Ptr<Socket> source =
Socket::CreateSocket(networkNodes.Get(0), tid);
// node 0, sender
InetSocketAddress remote = InetSocketAddress(Ipv4Address::GetBroadcast(), 80);
source->SetAllowBroadcast(true); source->Connect(remote);
// all sources are connected to node 1
// energy source
Ptr<BasicEnergySource -> basicSourcePtr=DynamicCast<BasicEnergySource>sources.Get (1));
basicSourcePtr->TraceConnectWithoutContext("RemainingEnergy",MakeCallback
&RemainingEnergy));
// device energy model
Ptr<DeviceEnergyModel> basicRadioModelPtr=
basicSourcePtr->FindDeviceEnergyModels("ns3::WifiRadioEnergyModel").Get(0);
NS_ASSERT(basicRadioModelPtr != NULL);
basicRadioModelPtr->TraceConnectWithoutContext("TotalEnergyConsumption",
MakeCallback(&TotalEnergy));
/***************************************************************************/

// start traffic
Simulator::Schedule(Seconds(startTime), &GenerateTraffic, source, PpacketSize,
networkNodes.Get(0), numPackets, interPacketInterval);
Simulator::Stop(Seconds(10.0));
Simulator::Run();
Simulator::Destroy();
return 0;}
OUTPUT:
PRACTICAL - 3

AIM: To implement Mixed Global Routing Protocol in NS-3

THEORY:
With the fast growth of various mobile terminals, the heterogeneous terminals that have different
capabilities and resources are required and mixed in the deployment. Using this feature, we can
improve the routing protocol. The available routing protocols for mobile Ad Hoc networks are
designed mainly for homogeneous wireless networks. The heterogeneous wireless networks are now
needed urgently in many important applications. However, rare dedicated routing protocols are
available yet for mixed deployment scenarios for heterogeneous nodes. The main idea is to properly
divide the network deployment area into grids according to the location, each of which contains one
backbone routing node and some ordinary nodes. The key design issues of this protocol, including
grid division, local routing within one grid, and global routing among grids, will be introduced to see
the overall performance in the following experiment.

CODE:
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/point-to-point-
module.h" #include "ns3/csma-
module.h" #include "ns3/applications-
module.h" #include "ns3/internet-
module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("MixedGlobalRoutingExample"); int
main(int argc, char *argv[])

{
Config::SetDefault("ns3::OnOffApplication::PacketSize", UintegerValue(210));
Config::SetDefault("ns3::OnOffApplication::DataRate", StringValue("448kb/s"));
// Allow the user to override any of the defaults and the above
// Bind ()s at run-time, via command-line arguments CommandLine
cmd;
cmd.Parse(argc, argv);
NS_LOG_INFO("Create nodes.");
NodeContainer c; c.Create(7);
NodeContainer n0n2 = NodeContainer(c.Get(0),
c.Get(2)); NodeContainer n1n2 =
NodeContainer(c.Get(1), c.Get(2)); NodeContainer n5n6
= NodeContainer(c.Get(5), c.Get(6));
NodeContainer n2345 = NodeContainer(c.Get(2), c.Get(3), c.Get(4), c.Get(5));
InternetStackHelper internet; internet.Install(c);
// We create the channels first without any IP addressing information NS_LOG_INFO("Create
channels.");
PointToPointHelper p2p;
p2p.SetDeviceAttribute("DataRate", StringValue("5Mbps")); p2p.SetChannelAttribute("Delay",
StringValue("2ms"));
NetDeviceContainer d0d2 = p2p.Install(n0n2); NetDeviceContainer
d1d2 = p2p.Install(n1n2);
p2p.SetDeviceAttribute("DataRate", StringValue("1500kbps")); p2p.SetChannelAttribute("Delay",
StringValue("10ms"));
NetDeviceContainer d5d6 = p2p.Install(n5n6);

// We create the channels first without any IP addressing information


CsmaHelper csma;
csma.SetChannelAttribute("DataRate", StringValue("5Mbps")); csma.SetChannelAttribute("Delay",
StringValue("2ms"));
NetDeviceContainer d2345 = csma.Install(n2345); //
Later, we add IP addresses.
NS_LOG_INFO("Assign IP Addresses.");
Ipv4AddressHelper ipv4; ipv4.SetBase("10.1.1.0", "255.255.255.0");
ipv4.Assign(d0d2); ipv4.SetBase("10.1.2.0", "255.255.255.0");
ipv4.Assign(d1d2); ipv4.SetBase("10.1.3.0", "255.255.255.0");
Ipv4InterfaceContainer i5i6 = ipv4.Assign(d5d6);
ipv4.SetBase("10.250.1.0", "255.255.255.0"); ipv4.Assign(d2345);
// Create router nodes, initialize routing database and set up the routing //
tables in the nodes.
Ipv4GlobalRoutingHelper::PopulateRoutingTables();

// Create the OnOff application to send UDP datagrams of size


// 210 bytes at a rate of 448 Kb/s
NS_LOG_INFO("Create Applications."); uint16_t port = 9;
// Discard port (RFC 863)
OnOffHelper onoff("ns3::UdpSocketFactory",InetSocketAddress(i5i6.GetAddress(1), port));
onoff.SetConstantRate(DataRate("300bps")); onoff.SetAttribute("PacketSize",
UintegerValue(50)); ApplicationContainer apps = onoff.Install(c.Get(0));
apps.Start(Seconds(1.0)); apps.Stop(Seconds(10.0));
AsciiTraceHelper ascii;
Ptr<OutputStreamWrapper> stream =ascii.CreateFileStream("mixed-global- routing.tr");
p2p.EnableAsciiAll(stream); csma.EnableAsciiAll(stream);

p2p.EnablePcapAll("mixed-global-routing"); csma.EnablePcapAll("mixed-global-routing",
false);
NS_LOG_INFO("Run Simulation.");
Simulator::Run();
Simulator::Destroy();
NS_LOG_INFO("Done.");
}
OUTPUT:
PRACTICAL - 4

AIM: To implement Simple Global Routing Protocol in NS-3

THEORY:
Global State Routing (GSR) is similar to DSDV. It takes the idea of link state routing but improves it
by avoiding flooding of routing messages.
In this algorithm, each node maintains a Neighbor list, a Topology table, a Next Hop table and a
Distance table. Neighbor list of a node contains the list of its neighbors (here all nodes that can be
heard by a node are assumed to be its neighbors.). For each destination node, the Topology table
contains the link state information as reported by the destination and the timestamp of the
information. For each destination, the Next Hop table contains the next hop to which the packets for
this destination must be forwarded. The Distance table contains the shortest distance to each
destination node.
The routing messages are generated on a link change as in link state protocols. On receiving a routing
message, the node updates its Topology table if the sequence number of the message is newer than
the sequence number stored in the table. After this, the node reconstructs its routing table and
broadcasts the information to its neighbors.

CODE:
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#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"
#include "ns3/flow-monitor-helper.h" #include
"ns3/ipv4-global-routing-helper.h" using
namespace ns3;
NS_LOG_COMPONENT_DEFINE("SimpleGlobalRoutingExample"); int main(int argc, char *argv[])
{
// Users may find it convenient to turn on explicit debugging
// for selected modules; the below lines suggest how to do this
#if 0
LogComponentEnable ("SimpleGlobalRoutingExample", LOG_LEVEL_INFO); #endif

// Set up some default values for the simulation. Use the


Config::SetDefault("ns3::OnOffApplication::PacketSize", UintegerValue(210));
Config::SetDefault("ns3::OnOffApplication::DataRate", StringValue("448kb/s"));
// DefaultValue::Bind ("DropTailQueue::m_maxPackets", 30);
// Allow the user to override any of the defaults and the above
// DefaultValue::Bind ()s at run-time, via command-line arguments CommandLine cmd; bool
enableFlowMonitor = false;
cmd.AddValue("EnableMonitor", "Enable Flow Monitor", enableFlowMonitor); cmd.Parse(argc,
argv);
// Here, we will explicitly create four nodes. In more sophisticated //
topologies, we could configure a node factory.
NS_LOG_INFO("Create nodes.");
NodeContainer c; c.Create(4);
NodeContainer n0n2 = NodeContainer(c.Get(0),
c.Get(2)); NodeContainer n1n2 =
NodeContainer(c.Get(1), c.Get(2)); NodeContainer n3n2
= NodeContainer(c.Get(3),
c.Get(2)); InternetStackHelper internet; internet.Install(c);

// We create the channels first without any IP addressing information NS_LOG_INFO("Create


channels.");
PointToPointHelper p2p;
p2p.SetDeviceAttribute("DataRate", StringValue("5Mbps")); p2p.SetChannelAttribute("Delay",
StringValue("2ms"));
NetDeviceContainer d0d2 = p2p.Install(n0n2); NetDeviceContainer
d1d2 = p2p.Install(n1n2);
p2p.SetDeviceAttribute("DataRate", StringValue("1500kbps")); p2p.SetChannelAttribute("Delay",
StringValue("10ms"));
NetDeviceContainer d3d2 = p2p.Install(n3n2); //
Later, we add IP addresses.
NS_LOG_INFO("Assign IP Addresses."); Ipv4AddressHelper
ipv4;
ipv4.SetBase("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer
i0i2 = ipv4.Assign(d0d2); ipv4.SetBase("10.1.2.0",
"255.255.255.0"); Ipv4InterfaceContainer i1i2 =
ipv4.Assign(d1d2); ipv4.SetBase("10.1.3.0","255.255.255.0");
Ipv4InterfaceContainer i3i2 = ipv4.Assign(d3d2);
// Create router nodes, initialize routing database and set up the routing //
tables in the nodes.
Ipv4GlobalRoutingHelper::PopulateRoutingTables();

// Create the OnOff application to send UDP datagrams of size


// 210 bytes at a rate of 448 Kb/s
NS_LOG_INFO("Create Applications."); uint16_t port = 9; // Discard port (RFC
863) OnOffHelper onoff("ns3::UdpSocketFactory",
Address(InetSocketAddress(i3i2.GetAddress(0), port)));
onoff.SetConstantRate(DataRate("448kb/s"));
ApplicationContainer apps = onoff.Install(c.Get(0));
apps.Start(Seconds(1.0)); apps.Stop(Seconds(10.0));
// Create a packet sink to receive these packets
PacketSinkHelper sink("ns3::UdpSocketFactory",Address(InetSocketAddress(Ipv4Address::GetAny
(), port)));
apps = sink.Install(c.Get(3)); apps.Start(Seconds(1.0)); apps.Stop(Seconds(10.0));
// Create a similar flow from n3 to n1, starting at time 1.1 seconds onoff.SetAttribute("Remote",
AddressValue(InetSocketAddress(i1i2.GetAddress(0), port))); apps =
onoff.Install(c.Get(3)); apps.Start(Seconds(1.1));
apps.Stop(Seconds(10.0));
// Create a packet sink to receive these packets apps = sink.Install(c.Get(1));
apps.Start(Seconds(1.1)); apps.Stop(Seconds(10.0)); AsciiTraceHelper
ascii;
p2p.EnableAsciiAll(ascii.CreateFileStream("simple-global-routing.tr")); p2p.EnablePcapAll("simple-
global-routing");
// Flow Monitor
FlowMonitorHelper flowmonHelper; if
(enableFlowMonitor)
{ flowmonHelper.InstallAll();
}
NS_LOG_INFO("Run Simulation.");
Simulator::Stop(Seconds(11));
Simulator::Run(); NS_LOG_INFO("Done."); if
(enableFlowMonitor) {
flowmonHelper.SerializeToXmlFile("simple-global-routing.flowmon", false, false);

}
Simulator::Destroy(); return
0;
}
OUTPUT:
PRACTICAL - 5

AIM: Study and compare DSR, DSDV and AODV routing algorithms.

THEORY:
Ad hoc On-Demand Distance Vector Routing (AODV):
AODV is an on-demand routing protocol which is confluence of DSDV and DSR. Route is calculated
on demand, just as it is in DSR via route discovery process. However, AODV maintains a routing
table where it maintains one entry per destination unlike the DSR that maintains multiple route cache
entries for each target. AODV provides loop free routes while repairing link breakages unlike DSDV
it doesn’t require global periodic routing advertisements.

Dynamic Source Routing (DSR):


Dynamic Source Routing is a Pure On-Demand routing protocol, where the route is calculated only
when it is necessary. It is designed for use in multi hop ad hoc networks of mobile nodes. DSR allows
the network to be self-organized and self-configured without any central administration and network
setup. It uses no periodic routing messages like AODV, thus reduces bandwidth overhead and
conserved battery power and also huge routing updates. It needs only the effort from the MAC layer
to identify link failure’s uses source routing where the whole route is carried as an overhead.

Advantages and Disadvantages:


This protocol uses a reactive approach which eliminates the need to periodically flood the network
with table update messages which are required in a table-driven approach. In a reactive (on-demand)
approach such as this, a route is established only when it is required and hence the need to find routes
of all other nodes in the network as required by the table-driven approach is eliminated. The
intermediate nodes also utilize the route cache information efficiently to reduce the control overhead.
The disadvantage of this protocol is that the Route Maintenance mechanism does not locally repair a
broken link. Stale route cache information could also result in inconsistencies during the route
reconstruction phase. The connection setup delay is higher than in table-driven protocols. Even
though the protocol performs well in static and low mobility environments, the performance degrades
rapidly with increasing mobility. Also, considerable routing overhead is involved due to the source-
routing mechanism in protocols like DSR. This routing overhead is directly proportional to the path
length.
Destination-Sequenced Distance Vector Routing (DSDV):
Destination-Sequenced Distance Vector Routing (DSDV) is a table-driven routing scheme for ad hoc
mobile networks based on the Bellman-Ford algorithm. It was developed by C. Perkins and P.
Bhagwat in 1994. The main contribution of the algorithm was to solve the routing loop problem.
Each entry in the routing table contains a sequence number, the sequence numbers are generally even
if a link is present; else, an odd number is used.
The number is generated by the destination, and the emitter needs to send out the next update with
this number. Routing information is distributed between nodes by sending full dumps infrequently
and smaller incremental updates more frequently. For example, the routing table of Node A in this
network is

Destinatio Next Number of Sequence Install


n Hop Hops Number Time

A A 0 A 46 002000

B B 1 B 36 002200

C B 2 C 28 002500

Naturally the table contains description of all possible paths reachable by node A, along with the next
hop, number of hops and sequence number.

Selection of Route
If a router receives new information, then it uses the latest sequence number. If the sequence number
is the same as the one already in the table, the route with the better metric is used. Stale entries are
those entries that have not been updated for a while. Such entries as well as the routes using those
nodes as next hops are deleted.
Advantages
The availability of paths to all destinations in network always shows that less delay is required in the
path set up process.
The method of incremental update with sequence number labels marks the existing wired network
protocols adaptable to Ad-hoc wireless networks. Therefore, all available wired network protocol can
be useful to ad hoc wireless networks with less modification.

Disadvantages
DSDV requires a regular update of its routing tables, which uses up battery power and a small amount
of bandwidth even when the network is idle.
Whenever the topology of the network changes, a new sequence number is necessary before the
network re-converges; thus, DSDV is not suitable for highly dynamic networks. (As in all
distancevector protocols, this does not perturb traffic in regions of the network that are not concerned
by the topology change).

Influence
While DSDV itself does not appear to be much used today, other protocols have used similar
techniques. The best known sequenced distance vector protocol is AODV, which, by virtue of being a
reactive protocol, can use simpler sequencing heuristics. Babel is an attempt at making DSDV more
robust, more efficient and more widely applicable, while staying within the frameworks of proactive
protocols.

DSR vs AODV:
Dynamic Source Routing and Ad Hoc On-demand Distance Vector Routing are both routing
protocols for wireless mesh/ad hoc networks. Both protocols employ different mechanisms that result
in varied performance levels. DSR and AODV can be compared and evaluated based on the packet
delivery ratio, normalized MAC load, normalized routing load, and average end-to-end delay by
altering the number of sources, speed, and pause time.
Both DSR and AODV are demand-driven protocols which form a route on demand when a
transmitting computer desires a route. The main difference between DSR and AODV is the source
routing feature. The DSR is based on source routing in which all the routing information such as is
maintained at the mobile nodes. The DSR computes the routes and also updates them. The source
routing is a technique in which the packet sender identifies the entire sequence of the node into which
the packet has to pass through. The packet sender lists the route in the packet’s header so that the next
node to which the
packet has to be transmitted can be identified by the address on the way to the destination host. The
AODV uses a combination of a DSR and DSDV mechanism. It uses the route discovery and route
maintenance from a DSR and hop-by-hop routing, periodic advertisements, sequence numbers from
DSDV. The AODV easily overcomes the counting to infinity and Bellman Ford problems, and it also
provides quick convergence whenever the ad hoc network topology is altered.
When DSR and AODV are analyzed using a packet delivery ratio parameter by varying the paused
time in the intervals of 0, 10, 20, 40, 100, the results obtained for both on demand routing protocols
look similar.
The normalized routing load is analyzed for both protocols by varying paused times. The values for
the DSR protocol were less as compared to the AODV which show fairly stable results even after
increasing the number of sources. If normalized routing load is stable, the protocol is considered to be
scalable. The routing overhead for AODV is mainly from the route requests. DSR finds the route in
the cache as a result of aggressive caching. This helps to avoid a frequent route discovery process in
DSR thereby decreasing the routing overhead for DSR when compared to AODV.
The normalized MAC load is analyzed by varying different paused times. The values for AODV is
less when compared to DSR when analyzed for lower paused times.
When it comes to performance comparison between the two protocols, the cache staleness and high
MAC overhead degrade the performance of DSR in high mobility scenarios. In lower-mobility
scenarios, the performance of DSR is better than AODV as the route is always found quickly in cache
avoiding the route discovery process.

Summary:
• DSR has less routing overhead than AODV.
• AODV has less normalized MAC overhead than DSR.
• DSR is based on a source routing mechanism whereas AODV uses a combination of DSR and
DSDV mechanisms.
• AODV has better performance than DSR in higher-mobility scenarios.
• DSR has less frequent route discovery processes than AODV.
DSDV vs DSR

• DSDV performs well under low node mobility o High delivery rate
o Fails to converge for increased mobility DSR
performs well at all mobility rates
o Increased overhead of routing tables and control
packets o Scalability for dense networks

OUTPUT:

DSR, DSDV and AODV routing algorithms have been studied and compared.
PRACTICAL - 6

AIM: Study of Point-to-Point Net Devices and Point-to-Point Model and Point-to-Point Channel
in NS-3.

THEORY:
The ns-3 point-to-point model is of a very simple point to point data link connecting exactly two
PointToPointNetDevice devices over an PointToPointChannel. This can be viewed as equivalent to a
full duplex RS-232 or RS-422 link with null modem and no handshaking.
Data is encapsulated in the Point-to-Point Protocol (PPP – RFC 1661), however the Link Control
Protocol (LCP) and associated state machine is not implemented. The PPP link is assumed to be
established and authenticated at all times.
Data is not framed, therefore Address and Control fields will not be found. Since the data is not
framed, there is no need to provide Flag Sequence and Control Escape octets, nor is a Frame Check
Sequence appended. All that is required to implement non-framed PPP is to prepend the PPP protocol
number for IP Version 4, which is the sixteen-bit number 0x21.

The PointToPointNetDevice provides following Attributes:


Address: The ns3::Mac48Address of the device (if desired);
DataRate: The data rate (ns3::DataRate) of the device;
TxQueue: The transmit queue (ns3::Queue) used by the device;

InterframeGap: The optional ns3::Time to wait between “frames”;

Rx: A trace source for received packets;

Drop: A trace source for dropped packets.

The PointToPointNetDevice models a transmitter section that puts bits on a corresponding channel
“wire.” The DataRate attribute specifies the number of bits per second that the device will simulate
sending over the channel. In reality no bits are sent, but an event is scheduled for an elapsed time
consistent with the number of bits in each packet and the specified DataRate. The implication here is
that the receiving device models a receiver section that can receive any any data rate. Therefore there
is no need, nor way to set a receive data rate in this model. By setting the DataRate on the transmitter
of both devices connected to a given PointToPointChannel one can model a symmetric channel; or by
setting different DataRates one can model an asymmetric channel (e.g., ADSL).
The PointToPointNetDevice supports the assignment of a “receive error model.” This is an ErrorModel
object that is used to simulate data corruption on the link.

Point-to-Point Channel Model:


The point to point net devices are connected via an PointToPointChannel. This channel models two
wires transmitting bits at the data rate specified by the source net device. There is no overhead beyond
the eight bits per byte of the packet sent. That is, we do not model Flag Sequences, Frame Check
Sequences nor do we “escape” any data.

Using the Point-To-Point Net-Device:


The Point-To-Point net devices and channels are typically created and configured using the associated
PointToPointHelper object. The various ns3 device helpers generally work in a similar way, and their
use is seen in many of our example programs and is also covered in the ns-3 tutorial.
The conceptual model of interest is that of a bare computer “husk” into which you plug net devices.
The bare computers are created using a NodeContainer helper. You just ask this helper to create as
many computers (we call them Nodes) as you need on your network: NodeContainer nodes;
nodes.Create (2);
Once you have your nodes, you need to instantiate a PointToPointHelper and set any attributes you
may want to change. Note that since this is a point-to-point (as compared to a point-to-multipoint)
there may only be two nodes with associated net devices connected by a PointToPointChannel.:
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute("DataRate”,StringValue("5Mbps"));pointToPoint.SetChannelAttri
b ute ("Delay", StringValue ("2ms"));

Once the attributes are set, all that remains is to create the devices and install them on the required
nodes, and to connect the devices together using a PointToPoint channel. When we create the net
devices, we add them to a container to allow you to use them in the future. This all takes just one line
of code.:
NetDeviceContainer devices = pointToPoint.Install (nodes); PointToPoint Tracing
Like all ns-3 devices, the Point-to-Point Model provides a number of trace sources. These trace
sources can be hooked using your own custom trace code, or you can use our helper functions to
arrange for tracing to be enabled on devices you specify.

Upper-Level (MAC) Hooks:


From the point of view of tracing in the net device, there are several interesting points to insert trace
hooks. A convention inherited from other simulators is that packets destined for transmission onto
attached networks pass through a single “transmit queue” in the net device. We provide trace hooks at
this point in packet flow, which corresponds (abstractly) only to a transition from the network to data
link layer, and call them collectively the device MAC hooks. When a packet is sent to the Point-
toPoint net device for transmission it always passes through the transmit queue.

The transmit queue in the PointToPointNetDevice inherits from Queue, and therefore inherits three
trace sources:
An Enqueue operation source (see ns3::Queue::m_traceEnqueue);

A Dequeue operation source (see ns3::Queue::m_traceDequeue); A Drop


operation source (see ns3::Queue::m_traceDrop).

The upper-level (MAC) trace hooks for the PointToPointNetDevice are, in fact, exactly these three
trace sources on the single transmit queue of the device.
The m_traceEnqueue event is triggered when a packet is placed on the transmit queue. This happens
at the time that ns3::PointtoPointNetDevice::Sendor ns3::PointToPointNetDevice::SendFrom is
called by a higher layer to queue a packet for transmission. An Enqueue trace event firing should be
interpreted as only indicating that a higher level protocol has sent a packet to the device.
The m_traceDequeue event is triggered when a packet is removed from the transmit queue. Dequeues
from the transmit queue can happen in two situations:

1) If the underlying channel is idle when PointToPointNetDevice::Send is called, a packet is


dequeued from the transmit queue and immediately transmitted;
2) a packet may be dequeued and immediately transmitted in an internal TransmitCompleteEvent
that functions much like a transmit complete interrupt service routine.
A Dequeue trace event firing may be viewed as indicating that the PointToPointNetDevice has begun
transmitting a packet.

Lower-Level (PHY) Hooks:


Similar to the upper level trace hooks, there are trace hooks available at the lower levels of the net
device. We call these the PHY hooks. These events fire from the device methods that talk directly to
the PointToPointChannel.
The trace source m_dropTrace is called to indicate a packet that is dropped by the device. This
happens when a packet is discarded as corrupt due to a receive error model indication.
The other low-level trace source fires on reception of a packet from the PointToPointChannel.

OUTPUT:
Point-to-Point Net Devices and Point-to-Point Model and Point-to-Point Channel in NS-3 have been
studied.
PRACTICAL - 7

AIM: Create one UDP Client application to send UDP datagrams from node zero to node one.

THEORY:
UDP (User Datagram Protocol) is an alternative communications protocol to Transmission Control
Protocol (TCP) used primarily for establishing low-latency and loss tolerating connections between
applications on the Internet. Both UDP and TCP run on top of the Internet Protocol (IP) and are
sometimes referred to as UDP/IP or TCP/IP. Both protocols send short packets of data, called
datagrams.
UDP provides two services not provided by the IP layer. It provides port numbers to help distinguish
different user requests and, optionally, a checksum capability to verify that the data arrived intact.
TCP has emerged as the dominant protocol used for the bulk of Internet connectivity owing to
services for breaking large data sets into individual packets, checking for and resending lost packets
and reassembling packets into the correct sequence. But these additional services come at a cost in
terms of additional data overhead, and delays called latency.
In contrast, UDP just sends the packets, which means that it has much lower bandwidth overhead and
latency. But packets can be lost or received out of order as a result, owing to the different paths
individual packets traverse between sender and receiver.
UDP is an ideal protocol for network applications in which perceived latency is critical such as
gaming, voice and video communications, which can suffer some data loss without adversely
affecting perceived quality. In some cases, forward error correction techniques are used to improve
audio and video quality in spite of some loss.
UDP can also be used in applications that require lossless data transmission when the application is
configured to manage the process of retransmitting lost packets and correctly arranging received
packets. This approach can help to improve the data transfer rate of large files compared with TCP.
In the Open Systems Interconnection (OSI) communication model, UDP, like TCP, is in layer 4, the
Transport Layer. UDP works in conjunction with higher level protocols to help manage data
transmission services including Trivial File Transfer Protocol (TFTP), Real Time Streaming Protocol
(RTSP), Simple Network Protocol (SNP) and Domain Name System (DNS) lookups. The following
experiment demonstrates the transfer of datagrams from one node to another.
CODE:
// - UDP flows from n0 to n1
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/core-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/internet-module.h" using
namespace ns3;
NS_LOG_COMPONENT_DEFINE("UdpClientServerExample");
int main(int argc, char *argv[]) {
// Enable logging for UdpClient
LogComponentEnable("UdpClient",LOG_LEVEL_INFO);
LogComponentEnable("UdpServer", LOG_LEVEL_INFO);
bool useV6 = false;
Address serverAddress; CommandLine
cmd;
cmd.AddValue("useIpv6", "Use Ipv6", useV6); cmd.Parse(argc,
argv);
//

// Explicitly create the nodes required by the topology (shown above).


//
NS_LOG_INFO("Create nodes.");
NodeContainer n; n.Create(2);
InternetStackHelper internet;
internet.Install(n);
NS_LOG_INFO("Create channels.");
//

// Explicitly create the channels required by the topology (shown above).


//
CsmaHelper csma;
csma.SetChannelAttribute("DataRate", DataRateValue(DataRate(5000000)));
csma.SetChannelAttribute("Delay", TimeValue(MilliSeconds(2)));
csma.SetDeviceAttribute("Mtu", UintegerValue(1400));
NetDeviceContainer d = csma.Install(n);
//
// We've got the "hardware" in place. Now we need to add IP addresses.
//
NS_LOG_INFO("Assign IP Addresses.");
if (useV6 == false) { Ipv4AddressHelper
ipv4; ipv4.SetBase("10.1.1.0",
"255.255.255.0"); Ipv4InterfaceContainer i
= ipv4.Assign(d); serverAddress =
Address(i.GetAddress(1));
} else

{
Ipv6AddressHelper ipv6;
ipv6.SetBase("2001:0000:f00d:cafe::", Ipv6Prefix(64));
Ipv6InterfaceContainer i6 = ipv6.Assign(d);
serverAddress = Address(i6.GetAddress(1, 1));
}

NS_LOG_INFO("Create Applications.");
//
// Create one udpServer applications on node one.
//
uint16_t port = 4000;
UdpServerHelper server(port);
ApplicationContainer apps = server.Install(n.Get(1));
apps.Start(Seconds(1.0)); apps.Stop(Seconds(10.0));
// Create one UdpClient application to send UDP datagrams from node zero to //
node one.
//
uint32_t MaxPacketSize = 1024; Time
interPacketInterval = Seconds(0.05);
uint32_t maxPacketCount = 320;
UdpClientHelper client(serverAddress,
port);
client.SetAttribute("MaxPackets", UintegerValue(maxPacketCount));
client.SetAttribute("Interval", TimeValue(interPacketInterval));
client.SetAttribute("PacketSize", UintegerValue(MaxPacketSize));
apps = client.Install(n.Get(0)); apps.Start(Seconds(2.0));
apps.Stop(Seconds(10.0));
//

// Now, do the actual simulation.


//
NS_LOG_INFO("Run Simulation.");
Simulator::Run();
Simulator::Destroy();
NS_LOG_INFO("Done.");
}
OUTPUT:
PRACTICAL - 8

AIM: Implement Socket Bound Static Routing In NS-3 Simulator.

THEORY:
Static routing is the most secure way of routing. It reduces overhead from network resources. In
this type of routing, we manually add routes in routing table. It is useful where numbers of route
are limited. Like other routing methods, static routing also has its pros and cons.

Advantage of static routing:


It is easy to implement.
It is most secure way of routing, since no information is shared with other routers.
It puts no overhead on resources such as CPU or memory. Disadvantage of static routing It is
suitable only for small network.
If a link fails, it cannot reroute the traffic.

CODE:
The following experiment demonstrates socket bound static routing: #include
<iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/ipv4-static-routing-helper.h"
#include "ns3/ipv4-list-routing-helper.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("SocketBoundRoutingExample");
void SendStuff(Ptr<Socket> sock, Ipv4Address dstaddr, uint16_t port);
void BindSock(Ptr<Socket> sock, Ptr<NetDevice> netdev); void
srcSocketRecv(Ptr<Socket> socket); void dstSocketRecv(Ptr<Socket> socket);
int main(int argc, char *argv[]) {
// Allow the user to override any of the defaults and the above
// DefaultValue::Bind ()s at run-time, via command-line arguments CommandLine
cmd;
cmd.Parse(argc, argv);
Ptr<Node> nSrc = CreateObject<Node>();
Ptr<Node> nDst = CreateObject<Node>();
Ptr<Node>nRtr1=CreateObject<Node>();
Ptr<Node> nRtr2 = CreateObject<Node>();
Ptr<Node> nDstRtr = CreateObject<Node>();
NodeContainer c = NodeContainer(nSrc, nDst, nRtr1, nRtr2, nDstRtr);
InternetStackHelper internet; internet.Install(c);
// Point-to-point links

NodeContainer nSrcnRtr1 = NodeContainer(nSrc, nRtr1);


NodeContainer nSrcnRtr2 = NodeContainer(nSrc, nRtr2);
NodeContainer nRtr1nDstRtr = NodeContainer(nRtr1, nDstRtr);
NodeContainer nRtr2nDstRtr = NodeContainer(nRtr2, nDstRtr);
NodeContainer nDstRtrnDst = NodeContainer(nDstRtr, nDst);
// We create the channels first without any IP addressing information PointToPointHelper p2p;
p2p.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
p2p.SetChannelAttribute("Delay", StringValue("2ms"));
NetDeviceContainer dSrcdRtr1 = p2p.Install(nSrcnRtr1);
NetDeviceContainer dSrcdRtr2 = p2p.Install(nSrcnRtr2);
NetDeviceContainer dRtr1dDstRtr = p2p.Install(nRtr1nDstRtr); NetDeviceContainer dRtr2dDstRtr
= p2p.Install(nRtr2nDstRtr);
NetDeviceContainer dDstRtrdDst = p2p.Install(nDstRtrnDst);
Ptr<NetDevice> SrcToRtr1 = dSrcdRtr1.Get(0);
Ptr<NetDevice> SrcToRtr2 = dSrcdRtr2.Get(0);
// Later, we add IP addresses.
Ipv4AddressHelper ipv4; ipv4.SetBase("10.1.1.0",
"255.255.255.0");
Ipv4InterfaceContainer iSrciRtr1 = ipv4.Assign(dSrcdRtr1); ipv4.SetBase("10.1.2.0",
"255.255.255.0");
Ipv4InterfaceContainer iSrciRtr2 = ipv4.Assign(dSrcdRtr2);
ipv4.SetBase("10.10.1.0", "255.255.255.0");
Ipv4InterfaceContainer iRtr1iDstRtr = ipv4.Assign(dRtr1dDstRtr); ipv4.SetBase("10.10.2.0",
"255.255.255.0");
Ipv4InterfaceContainer iRtr2iDstRtr = ipv4.Assign(dRtr2dDstRtr); ipv4.SetBase("10.20.1.0",
"255.255.255.0");
Ipv4InterfaceContainer iDstRtrDst = ipv4.Assign(dDstRtrdDst);
Ptr<Ipv4> ipv4Src = nSrc->GetObject<Ipv4>();
Ptr<Ipv4> ipv4Rtr1 = nRtr1->GetObject<Ipv4>();
Ptr<Ipv4> ipv4Rtr2 = nRtr2->GetObject<Ipv4>();
Ptr<Ipv4> ipv4DstRtr = nDstRtr->GetObject<Ipv4>();
Ptr<Ipv4> ipv4Dst = nDst->GetObject<Ipv4>();
Ipv4StaticRoutingHelper ipv4RoutingHelper; Ptr<Ipv4StaticRouting>
staticRoutingSrc = ipv4RoutingHelper.GetStaticRouting(ipv4Src);
Ptr<Ipv4StaticRouting> staticRoutingRtr1 = pv4RoutingHelper.GetStaticRouting(ipv4Rtr1);
Ptr<Ipv4StaticRouting> staticRoutingRtr2 = ipv4RoutingHelper.GetStaticRouting(ipv4Rtr2);
Ptr<Ipv4StaticRouting> staticRoutingDstRtr =
ipv4RoutingHelper.GetStaticRouting(ipv4DstRtr);
Ptr<Ipv4StaticRouting> staticRoutingDst = ipv4RoutingHelper.GetStaticRouting(ipv4Dst);
// Create static routes from Src to Dst staticRoutingRtr1-
>AddHostRouteTo(Ipv4Address("10.20.1.2"),Ipv4Address("10.10.1.2"), 2); staticRoutingRtr2-
>AddHostRouteTo(Ipv4Address("10.20.1.2"),Ipv4Address("10.10.2.2"), 2); // Two routes to same
destination - setting separate metrics.
// You can switch these to see how traffic gets diverted via different routes
staticRoutingSrc->AddHostRouteTo (Ipv4Address ("10.20.1.2"), Ipv4Address "10.1.1.2"), 1,5);
staticRoutingSrc->AddHostRouteTo(Ipv4Address("10.20.1.2"),Ipv4Address("10.1.2.2"), 2,
10);
// Creating static routes from DST to Source pointing to Rtr1 VIA Rtr2(!)
staticRoutingDst->AddHostRouteTo(Ipv4Address("10.1.1.1"),Ipv4Address("10.20.1.1"), 1);
staticRoutingDstRtr->AddHostRouteTo(Ipv4Address("10.1.1.1"),Ipv4Address("10.10.2.1"), 2);
staticRoutingRtr2->AddHostRouteTo(Ipv4Address("10.1.1.1"),Ipv4Address("10.1.2.1"), 1); //
There are no apps that can utilize the Socket Option so doing the work // directly..
// Taken from tcp-large-transfer example Ptr<Socket>
srcSocket = Socket::CreateSocket(nSrc,
TypeId::LookupByName("ns3::UdpSocketFactory")); srcSocket->Bind(); srcSocket-
>SetRecvCallback(MakeCallback(&srcSocketRecv)); Ptr<Socket>
dstSocket = Socket::CreateSocket(nDst,
TypeId::LookupByName("ns3::UdpSocketFactory")); uint16_t dstport = 12345;
Ipv4Address dstaddr("10.20.1.2");
InetSocketAddress dst = InetSocketAddress(dstaddr, dstport); dstSocket->Bind(dst);
dstSocket->SetRecvCallback(MakeCallback(&dstSocketRecv)); AsciiTraceHelper
ascii;
p2p.EnableAsciiAll(ascii.CreateFileStream("socket-bound-static-routing.tr"));
p2p.EnablePcapAll("socket-bound-static-routing");
LogComponentEnableAll(LOG_PREFIX_TIME);
LogComponentEnable("SocketBoundRoutingExample", LOG_LEVEL_INFO);
// First packet as normal (goes via Rtr1)

Simulator::Schedule(Seconds(0.1), &SendStuff, srcSocket, dstaddr, dstport);


// Second via Rtr1 explicitly
Simulator::Schedule(Seconds(1.0), &BindSock, srcSocket, SrcToRtr1);
Simulator::Schedule(Seconds(1.1), &SendStuff, srcSocket, dstaddr, dstport);
// Third via Rtr2 explicitly
Simulator::Schedule(Seconds(2.0), &BindSock, srcSocket, SrcToRtr2);
Simulator::Schedule(Seconds(2.1), &SendStuff, srcSocket, dstaddr, dstport);
// Fourth again as normal (goes via Rtr1)
Simulator::Schedule(Seconds(3.0), &BindSock, srcSocket, Ptr<NetDevice>(0));
Simulator::Schedule(Seconds(3.1), &SendStuff, srcSocket, dstaddr, dstport);
// If you uncomment what's below, it results in ASSERT failing since you can't // bind
to a socket not existing on a node
//
Simulator::Schedule(Seconds(4.0),&BindSock, srcSocket, dDstRtrdDst.Get(0)); Simulator::Run();
Simulator::Destroy(); return 0;
}
void SendStuff(Ptr<Socket> sock, Ipv4Address dstaddr, uint16_t port) { Ptr<Packet> p =
Create<Packet>(); p->AddPaddingAtEnd(100);
sock->SendTo(p, 0, InetSocketAddress(dstaddr, port));
return; }
void BindSock(Ptr<Socket> sock, Ptr<NetDevice> netdev) { sock->BindToNetDevice(netdev);
return; }
void srcSocketRecv(Ptr<Socket> socket)
{ Address from;
Ptr<Packet> packet = socket->RecvFrom(from); packet-

>RemoveAllPacketTags(); packet->RemoveAllByteTags(); NS_LOG_INFO("Source


Received "<< packet->GetSize() << " bytes from "<<
InetSocketAddress::ConvertFrom(from).GetIpv4()); if (socket->GetBoundNetDevice())
{ NS_LOG_INFO("Socket was bound");
} else
{
NS_LOG_INFO("Socket was not bound");
}}
void dstSocketRecv(Ptr<Socket> socket)
{ Address from;
Ptr<Packet> packet = socket->RecvFrom(from); packet-
>RemoveAllPacketTags(); packet->RemoveAllByteTags(); InetSocketAddress
address = InetSocketAddress::ConvertFrom(from);
NS_LOG_INFO("Destination Received " << packet->GetSize() << " bytes from "

<< address.GetIpv4()); NS_LOG_INFO("Triggering packet back to source node's interface 1");


SendStuff(socket, Ipv4Address("10.1.1.1"), address.GetPort()); }

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy