NW - Pallavi (1) - 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 53

MCAL26: Networking with Linux Page No.

Practical No: 1

Aim:- Installation of NS-3 in Linux

Objective: To learn to Install NS3 in Ubuntu Linux.

Theory: 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. NS-3 is primarily developed on GNU/Linux and macOS platforms, and the minimal
requirements to run basic simulations are a C++ compiler; either g++ or clang++ compiler, and
Python (version 3) interpreter.

Program: After Installing Ubuntu 20.04 LTS successfully, you can now start with installing of
NS3 packages.

List of Packages for Installing ns-3 in Ubuntu Systems

Prequisite for installing NS3.32


sudo apt upgrade
Sudo apt update

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 2

Minimal requirements for C++ users apt-get


install g++ python3

Minimal requirements for Python API users


apt-get install g++ python3 python3-dev pkg-config sqlite3

Netanim animator: qt5 development tools are needed for Netanim animator; apt-get
install qt5-default mercurial

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 3

ns-3-pyviz visualizer
apt-get install gir1.2-goocanvas-2.0 python-gi python-gi- cairo python-pygraphviz python3-gi
python3-gi-cairo python3-pygraphviz gir1.2-gtk-3.0 ipython ipython3

Debugging: apt-get install


gdb valgrind

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 4

Doxygen and related inline documentation:


sudo apt-get install doxygen graphviz imagemagick

Sudo apt-get install texlive texlive-extra-utils texlive-latex- extra texlive-font-utils dvipng


latexmk

The ns-3 manual and tutorial are written in reStructuredText for Sphinx (doc/tutorial,
doc/manual, doc/models), and figures typically in dia (also needs the texlive packages
above):
apt-get install python3-sphinx dia

To read pcap packet traces


apt-get install tcpdump

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 5

Support for generating modified python bindings


apt-get install cmake libc6-dev libc6-dev-i386 libclang- 6.0-dev llvm-6.0-dev automake
python3pip

After installing the required packages, create a folder named workspace in the home
directory and then put the NS3 tar package into the workspace.
Go to terminal and input these commands consecutively after each command finishes executing:
cd
cd workspace tar xjf <name of NS3 downloaded file name>
cd <name of extracted NS3>
./build.py --enable-examples --enable-tests It
takes time be patient !!
Test the NS3 build and installation success by running test.py in the ns directory using
the following commands: cd ns-<version number>
./test.py

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 6

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 7

Practical No: 2

Aim:- Installation of NetAnim

Objective: To learn to Install Net anim in Ubuntu Linux

Theory: NetAnim is an offline animator based on the Qt toolkit. It currently animates the
simulation using an XML trace file collected during simulation. The NetAnim application requires
a custom trace file for animation. This trace file is created by AnimationInterface in ns-3.

Installation: After Installing Ubuntu 20.04 LTS successfully, you can now start with installing of
Net anim packages.

List of Packages for Installing ns-3 in Ubantu Systems


Prequisite for installing NS3.32
sudo apt upgrade
Sudo apt update

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 8

Minimal requirements for C++ users apt-get


install g++ python3

Minimal requirements for Python API users


apt-get install g++ python3 python3-dev pkg-config sqlite3

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 9

Netanim animator:
qt5 development tools are needed for Netanim animator; apt-get install qt5-default mercurial

ns-3-pyviz visualizer
apt-get install gir1.2-goocanvas-2.0 python-gi python-gi- cairo python-pygraphviz python3-gi
python3-gi-cairo python3-pygraphviz gir1.2-gtk-3.0 ipython ipython3

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 10

Debugging:
apt-get install gdb valgrind

Doxygen and related inline documentation: apt-get


install doxygen graphviz imagemagick

apt-get install texlive texlive-extra-utils texlive-latex- extra texlive-font-utils dvipng latexmk

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 11

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 12

The ns-3 manual and tutorial are written in reStructuredText for Sphinx (doc/tutorial,
doc/manual, doc/models), and figures typically in dia (also needs the texlive packages
above): apt-get install python3-sphinx dia

To read pcap packet traces apt-get


install tcpdump

Support for generating modified python bindings


apt-get install cmake libc6-dev libc6-dev-i386 libclang- 6.0-dev llvm-6.0-dev automake
python3pip

After installing the required packages, create a folder named workspace in the home
directory and then put the NS3 tar package into the workspace.
Go to terminal and input these commands consecutively after each command finishes executing:
cd
cd workspace tar xjf <name of NS3 downloaded file name>
cd <name of extracted NS3>
./build.py --enable-examples --enable-tests It
takes time be patient !!
Test the NS3 build and installation success by running test.py in the ns directory using
the following commands: cd ns-<version number>
./test.py

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 13

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 14

Practical No: 3

Aim:- Installation of WireShark

Objective: To learn to Install Wireshark in Ubuntu Linux

Theory: Wireshark is a network protocol analyzer, or an application that captures


packets from a network connection, such as from your computer to your home office or the
internet. Packet is the name given to a discrete unit of data in a typical Ethernet network.
Wireshark is the most often-used packet sniffer in the world.

Here are some reasons people use Wireshark:


• Network administrators use it to troubleshoot network problems.
• Network security engineers use it to examine security problems.
• QA engineers use it to verify network applications.
• Developers use it to debug protocol implementations.

Installation Process:

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 15

Practical No: 4

Aim:- Program to simulate traffic between two nodes

Objective: To learn simulate traffic between two nodes and print String .

Theory: The Simulation Generate node provides an easy way to generate simulated data, either without
historical data using user specified statistical distributions, or automatically using the distributions obtained
from running a Simulation Fitting node on existing historical data.

Program:

First.cc
#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" // Default Network
Topology
//
// 10.1.1.0
// n0 n1
// point-to-point
//
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("FirstScriptExample"); int main
(int argc, char *argv[])
{
CommandLine cmd ( FILE ); cmd.Parse (argc, argv); Time::SetResolution (Time::NS);
LogComponentEnable ("UdpEchoClientApplication",
LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
NodeContainer nodes; nodes.Create (2); PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer devices;
devices = pointToPoint.Install (nodes); InternetStackHelper stack; stack.Install (nodes); Ipv4AddressHelper
address;
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
//server
UdpEchoServerHelper echoServer (9);
ApplicationContainer serverApps = echoServer.Install (nodes.Get (1));
serverApps.Start (Seconds (1.0)); serverApps.Stop (Seconds (10.0));
//client
UdpEchoClientHelper echoClient (interfaces.GetAddress (1), 9);
echoClient.SetAttribute ("MaxPackets", UintegerValue (1)); echoClient.SetAttribute ("Interval",
TimeValue (Seconds (1.0)));

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 16

echoClient.SetAttribute ("PacketSize", UintegerValue (1024));


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

Simulator::Run (); Simulator::Destroy (); return 0;


}

Terminal and Output Screen:

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 17

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 18

Practical No: 5

Aim:- Program to simulate star topology

Objective: To learn simulate star topology.

Theory: Star topology is a network topology in which each network component is physically
connected to a central node such as a router, hub or switch. In a star topology, the central hub acts
like a server and the connecting nodes act like clients.

When a computer sends data to other computers on the network, it is sent along the cable to a central hub or
switch, which then determines which port it needs to send the data through for it to reach the proper
destination.

Program:

Terminal and Output NetAnim Screen:

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 19

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 20

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 21

Practical No: 6

Aim:- Program to simulate bus topology

Objective: To learn simulate Program to simulate bus topology.

Theory: Bus topology, also known as line topology, is a type of network topology in which all
devices in the network are connected by one central RJ-45 network cable or coaxial cable.
The single cable, where all data is transmitted between devices, is referred to as the bus, backbone, or trunk.
A bus topology connects computers along a single or more cable to connect linearly. A
network that uses a bus topology is referred to as a "bus network" which was the original form of Ethernet
networks.

Line of Code:

Bus.cc

#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 "ns3/netanim-module.h"
// Default Network Topology
//
// 10.1.1.0
// n0 -------------- n1 n2 n3 n4

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 22

// point-to-point | | | |
// ================ //
LAN 10.1.2.0 using namespace ns3;
NS_LOG_COMPONENT_DEFINE
("SecondScriptExample");

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

CommandLine cmd (__FILE__);


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 ("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
} nCsma = nCsma == 0 ? 1 :

nCsma;

NodeContainer p2pNodes;
p2pNodes.Create (2);

NodeContainer csmaNodes;
csmaNodes.Add (p2pNodes.Get (1));
csmaNodes.Create (nCsma);

PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));

NetDeviceContainer p2pDevices; p2pDevices =


pointToPoint.Install (p2pNodes);

CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps"));
csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560)));

NetDeviceContainer csmaDevices;
csmaDevices = csma.Install (csmaNodes);

InternetStackHelper stack;
stack.Install (p2pNodes.Get (0));
stack.Install (csmaNodes);

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 23

Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer p2pInterfaces; p2pInterfaces
= address.Assign (p2pDevices);

address.SetBase ("10.1.2.0", "255.255.255.0");


Ipv4InterfaceContainer csmaInterfaces; csmaInterfaces
= address.Assign (csmaDevices); 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));

Ipv4GlobalRoutingHelper::PopulateRoutingTables ();

pointToPoint.EnablePcapAll ("second");
csma.EnablePcap ("second", csmaDevices.Get (1), true);
AnimationInterface anim("bus.xml");
Simulator::Run ();
Simulator::Destroy ();
return 0; }

Program:

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 24

Output Screen:

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 25

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 26

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 27

Practical No: 7

Aim:- Program to simulate mesh topology

Objective: To learn simulate mesh topology

Theory: In a mesh topology there is no central connection point. Instead, each node is
connected to at least one other node and usually to more than one. Each node is capable
of sending messages to and receiving messages from other nodes. The nodes act as
relays, passing on a message towards its final destination.

Line of Code:

Mesh.cc
/* -*- 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 <iostream>
#include <sstream>
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/network-module.h"

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 28

#include "ns3/applications-module.h"
#include "ns3/mesh-module.h"
#include "ns3/mobility-module.h"
#include "ns3/mesh-helper.h"
#include "ns3/yans-wifi-helper.h"
#include "ns3/netanim-module.h" using

namespace ns3;

NS_LOG_COMPONENT_DEFINE ("MeshExample");

// Declaring these variables outside of main() for use in trace sinks


uint32_t g_udpTxCount = 0; uint32_t g_udpRxCount = 0;

void
TxTrace (Ptr<const Packet> p)
{
NS_LOG_DEBUG ("Sent " << p->GetSize () << " bytes");
g_udpTxCount++;
}

void
RxTrace (Ptr<const Packet> p)
{
NS_LOG_DEBUG ("Received " << p->GetSize () << " bytes");
g_udpRxCount++;
}

/**
* \ingroup mesh
* \brief MeshTest class
*/
class MeshTest
{ public: ///
Init test
MeshTest ();
/**
* Configure test from command line arguments
*
* \param argc command line argument count
* \param argv command line arguments
*/
void Configure (int argc, char ** argv);
/**
* Run test
* \returns the test status
*/ int
Run ();
private:
int m_xSize; ///< X size int
m_ySize; ///< Y size double m_step; ///< step
double m_randomStart; ///< random start
double m_totalTime; ///< total time double

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 29

m_packetInterval; ///< packet interval uint16_t


m_packetSize; ///< packet size uint32_t
m_nIfaces; ///< number interfaces
bool m_chan; ///< channel
bool m_pcap; ///< PCAP bool
m_ascii; ///< ASCII std::string
m_stack; ///< stack std::string
m_root; ///< root
/// List of network nodes
NodeContainer nodes;
/// List of all mesh point devices
NetDeviceContainer meshDevices; ///
Addresses of interfaces:
Ipv4InterfaceContainer interfaces;
/// MeshHelper. Report is not static methods
MeshHelper mesh; private:
/// Create nodes and setup their mobility
void CreateNodes ();
/// Install internet m_stack on nodes
void InstallInternetStack (); ///
Install applications void
InstallApplication (); /// Print mesh
devices diagnostics void Report ();
};
MeshTest::MeshTest () :
m_xSize (3), m_ySize (3),
m_step (50.0), m_randomStart
(0.1), m_totalTime (100.0),
m_packetInterval (1),
m_packetSize (1024),
m_nIfaces (1), m_chan (true),
m_pcap (false), m_ascii
(false), m_stack
("ns3::Dot11sStack"),
m_root ("ff:ff:ff:ff:ff:ff")
{
}
void
MeshTest::Configure (int argc, char *argv[])
{
CommandLine cmd (__FILE__);
cmd.AddValue ("x-size", "Number of nodes in a row grid", m_xSize);
cmd.AddValue ("y-size", "Number of rows in a grid", m_ySize); cmd.AddValue
("step", "Size of edge in our grid (meters)", m_step); // Avoid starting
all mesh nodes at the same time (beacons may collide) cmd.AddValue ("start",
"Maximum random start delay for beacon jitter (sec)", m_randomStart);
cmd.AddValue ("time", "Simulation time (sec)", m_totalTime); cmd.AddValue
("packet-interval", "Interval between packets in UDP ping (sec)",
m_packetInterval);
cmd.AddValue ("packet-size", "Size of packets in UDP ping (bytes)", m_packetSize);
cmd.AddValue ("interfaces", "Number of radio interfaces used by each mesh point",
m_nIfaces);
cmd.AddValue ("channels", "Use different frequency channels for different
interfaces", m_chan);

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 30

cmd.AddValue ("pcap", "Enable PCAP traces on interfaces", m_pcap);


cmd.AddValue ("ascii", "Enable Ascii traces on interfaces", m_ascii);
cmd.AddValue ("stack", "Type of protocol stack. ns3::Dot11sStack by default",
m_stack);
cmd.AddValue ("root", "Mac address of root mesh point in HWMP", m_root);

cmd.Parse (argc, argv);


NS_LOG_DEBUG ("Grid:" << m_xSize << "*" << m_ySize);
NS_LOG_DEBUG ("Simulation time: " << m_totalTime << " s"); if
(m_ascii)
{
PacketMetadata::Enable ();
}
}
void
MeshTest::CreateNodes ()
{
/*
* Create m_ySize*m_xSize stations to form a grid topology
*/ nodes.Create
(m_ySize*m_xSize);
// Configure YansWifiChannel
YansWifiPhyHelper wifiPhy;
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
wifiPhy.SetChannel (wifiChannel.Create ());
/*
* Create mesh helper and set stack installer to it
* Stack installer creates all needed protocols and install them to
* mesh point device
*/
mesh = MeshHelper::Default (); if (!Mac48Address
(m_root.c_str ()).IsBroadcast ())
{
mesh.SetStackInstaller (m_stack, "Root", Mac48AddressValue (Mac48Address
(m_root.c_str ())));
}
else
{
//If root is not set, we do not use "Root" attribute, because it
//is specified only for 11s
mesh.SetStackInstaller (m_stack);
} if (m_chan) { mesh.SetSpreadInterfaceChannels
(MeshHelper::SPREAD_CHANNELS);
} else { mesh.SetSpreadInterfaceChannels
(MeshHelper::ZERO_CHANNEL);
} mesh.SetMacType ("RandomStart", TimeValue (Seconds
(m_randomStart))); // Set number of interfaces - default is single-
interface mesh point mesh.SetNumberOfInterfaces (m_nIfaces);
// Install protocols and return container if MeshPointDevices
meshDevices = mesh.Install (wifiPhy, nodes);
// AssignStreams can optionally be used to control random variable streams
mesh.AssignStreams (meshDevices, 0); // Setup mobility - static grid
topology MobilityHelper mobility;

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 31

mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
"MinX", DoubleValue (0.0), "MinY",
DoubleValue (0.0),
"DeltaX", DoubleValue (m_step),
"DeltaY", DoubleValue (m_step),
"GridWidth", UintegerValue (m_xSize),
"LayoutType", StringValue ("RowFirst")); mobility.SetMobilityModel
("ns3::ConstantPositionMobilityModel"); mobility.Install (nodes); if
(m_pcap) wifiPhy.EnablePcapAll (std::string ("mp")); if (m_ascii)
{
AsciiTraceHelper ascii;
wifiPhy.EnableAsciiAll (ascii.CreateFileStream ("mesh.tr"));
}
}
void
MeshTest::InstallInternetStack ()
{
InternetStackHelper internetStack;
internetStack.Install (nodes);
Ipv4AddressHelper address; address.SetBase
("10.1.1.0", "255.255.255.0"); interfaces =
address.Assign (meshDevices);
}
void
MeshTest::InstallApplication ()
{
uint16_t portNumber = 9;
UdpEchoServerHelper echoServer (portNumber);
uint16_t sinkNodeId = m_xSize * m_ySize - 1;
ApplicationContainer serverApps = echoServer.Install (nodes.Get (sinkNodeId));
serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (m_totalTime + 1));
UdpEchoClientHelper echoClient (interfaces.GetAddress (sinkNodeId), portNumber);
echoClient.SetAttribute ("MaxPackets", UintegerValue ((uint32_t)
(m_totalTime*(1/m_packetInterval))));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (m_packetInterval)));
echoClient.SetAttribute ("PacketSize", UintegerValue (m_packetSize));
ApplicationContainer clientApps = echoClient.Install (nodes.Get (0));
Ptr<UdpEchoClient> app = clientApps.Get (0)->GetObject<UdpEchoClient> ();
app->TraceConnectWithoutContext ("Tx", MakeCallback (&TxTrace)); app-
>TraceConnectWithoutContext ("Rx", MakeCallback (&RxTrace)); clientApps.Start
(Seconds (1.0));
clientApps.Stop (Seconds (m_totalTime + 1.5));
} int
MeshTest::Run ()
{
CreateNodes ();
InstallInternetStack ();
InstallApplication ();
Simulator::Schedule (Seconds (m_totalTime), &MeshTest::Report, this);
Simulator::Stop (Seconds (m_totalTime + 2));
AnimationInterface anim("Mesh.xml");

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 32

Simulator::Run (); Simulator::Destroy (); std::cout << "UDP echo


packets sent: " << g_udpTxCount << " received: " << g_udpRxCount <<
std::endl; return 0;
}
void
MeshTest::Report ()
{
unsigned n (0); for (NetDeviceContainer::Iterator i = meshDevices.Begin (); i !=
meshDevices.End (); ++i, ++n) {
std::ostringstream os; os << "mp-report-" << n << ".xml"; std::cerr
<< "Printing mesh point device #" << n << " diagnostics to " << os.str
() << "\n"; std::ofstream of;
of.open (os.str ().c_str ());
if (!of.is_open ())
{
std::cerr << "Error: Can't open file " << os.str () << "\n";
return; }
mesh.Report (*i, of);
of.close ();
}
} int main (int argc, char
*argv[])
{
MeshTest t;
t.Configure (argc, argv);
return t.Run ();
}

Program:

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 33

Output Screen:

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 34

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 35

Practical No: 8

Aim:- Program to simulate hybrid topology

Objective: To learn simulate hybrid topology

Theory: A hybrid topology is a type of network topology that uses two or more differing
network topologies. These topologies can include a mix of bus topology, mesh topology, ring topology,
star topology, and tree topology. Its usage and choice are dependent on its deployments and
requirements like the performance of the desired network, and the number of computers, their
location. The below figure is describing the structure of hybrid topology that contains more than one
topology.

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 36

Program:

Line of Code:
Hybrid.cc

/* -*- 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/point-to-point-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/mobility-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/yans-wifi-helper.h"
#include "ns3/ssid.h"
# include "ns3/netanim-module.h"
// Default Network Topology
//
// Wifi 10.1.3.0
// AP
// * * * *
// | | | | 10.1.1.0

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 37

// n5 n6 n7 n0 -------------- n1 n2 n3 n4
// point-to-point | | | |
// ================
// LAN 10.1.2.0 using

namespace ns3;

NS_LOG_COMPONENT_DEFINE ("ThirdScriptExample");

int
main (int argc, char *argv[])
{ bool verbose =
true; uint32_t nCsma
= 3; uint32_t nWifi =
3; bool tracing =
false;

CommandLine cmd (__FILE__);


cmd.AddValue ("nCsma", "Number of \"extra\" CSMA nodes/devices", nCsma);
cmd.AddValue ("nWifi", "Number of wifi STA devices", nWifi);
cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose);
cmd.AddValue ("tracing", "Enable pcap tracing", tracing); cmd.Parse
(argc,argv);

// The underlying restriction of 18 is due to the grid position


// allocator's configuration; the grid layout will exceed the
// bounding box if more than 18 nodes are provided.
if (nWifi > 18)
{
std::cout << "nWifi should be 18 or less; otherwise grid layout exceeds the
bounding box" << std::endl; return 1;
}

if (verbose)
{
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO); }

NodeContainer p2pNodes;
p2pNodes.Create (2);

PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));

NetDeviceContainer p2pDevices; p2pDevices =


pointToPoint.Install (p2pNodes);

NodeContainer csmaNodes;
csmaNodes.Add (p2pNodes.Get (1));
csmaNodes.Create (nCsma);

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 38

CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps"));
csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560)));
NetDeviceContainer csmaDevices; csmaDevices = csma.Install (csmaNodes);

NodeContainer wifiStaNodes;
wifiStaNodes.Create (nWifi);
NodeContainer wifiApNode = p2pNodes.Get (0);

YansWifiChannelHelper channel = YansWifiChannelHelper::Default ();


YansWifiPhyHelper phy; phy.SetChannel (channel.Create ());

WifiHelper wifi; wifi.SetRemoteStationManager


("ns3::AarfWifiManager");

WifiMacHelper mac;
Ssid ssid = Ssid ("ns-3-ssid");
mac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid),
"ActiveProbing", BooleanValue (false));

NetDeviceContainer staDevices;
staDevices = wifi.Install (phy, mac, wifiStaNodes);

mac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid));

NetDeviceContainer apDevices; apDevices =


wifi.Install (phy, mac, wifiApNode);
MobilityHelper mobility;

mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
"MinX", DoubleValue (0.0),
"MinY", DoubleValue (0.0),
"DeltaX", DoubleValue (5.0),
"DeltaY", DoubleValue (10.0),
"GridWidth", UintegerValue (3),
"LayoutType", StringValue ("RowFirst"));

mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel",
"Bounds", RectangleValue (Rectangle (-50, 50, -50, 50)));
mobility.Install (wifiStaNodes);

mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (wifiApNode);

InternetStackHelper stack;
stack.Install (csmaNodes); stack.Install
(wifiApNode); stack.Install
(wifiStaNodes); Ipv4AddressHelper
address;

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 39

address.SetBase ("10.1.1.0", "255.255.255.0");


Ipv4InterfaceContainer p2pInterfaces;
p2pInterfaces = address.Assign (p2pDevices);

address.SetBase ("10.1.2.0", "255.255.255.0");


Ipv4InterfaceContainer csmaInterfaces; csmaInterfaces
= address.Assign (csmaDevices);

address.SetBase ("10.1.3.0", "255.255.255.0");


address.Assign (staDevices); address.Assign
(apDevices);

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 (wifiStaNodes.Get (nWifi - 1));
clientApps.Start (Seconds (2.0)); clientApps.Stop
(Seconds (10.0));

Ipv4GlobalRoutingHelper::PopulateRoutingTables ();

Simulator::Stop (Seconds (10.0));

if (tracing == true)
{
pointToPoint.EnablePcapAll ("third");
phy.EnablePcap ("third", apDevices.Get (0));
csma.EnablePcap ("third", csmaDevices.Get (0), true); }

AnimationInterface anim("hybrid.xml");
Simulator::Run ();
Simulator::Destroy ();
return 0; }

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 40

Output Screen:

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 41

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 42

Practical No: 9

Aim:- Program to simulate UDP server client

Objective: To learn simulate UDP server client

Theory: In UDP, the client does not form a connection with the server like in TCP and
instead just sends a datagram. Similarly, the server need not accept a connection and just waits for
datagrams to arrive. Datagrams upon arrival contain the address of the sender which the server uses to send
data to the correct client.

Program:

Line of Code:

UDP.cc

/* -*- 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

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 43

* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA


*/
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/internet-module.h"
//netAnimation
#include "ns3/netanim-module.h" #include
"ns3/mobility-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("UdpClientServerExample"); int
main (int argc, char *argv[])
{
//
// Enable logging for UdpClient and
//
LogComponentEnable ("UdpClient", LOG_LEVEL_INFO); LogComponentEnable
("UdpServer", LOG_LEVEL_INFO);
bool useV6 = false; Address
serverAddress; CommandLine
cmd (__FILE__);
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;

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 44

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));
AnimationInterface anim("udp-cs.xml");
AnimationInterface::SetConstantPosition (n.Get(0), 10, 25);
AnimationInterface ::SetConstantPosition(n.Get(1), 40,25);
anim.EnablePacketMetadata(true); csma.EnablePcapAll("udp-cs");

//
// Now, do the actual simulation.
//
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done."); }

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 45

Output: Netanim Screen:

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 46

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 47

Output: WireShark:

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 48

Practical No: 10

Aim:- Program to simulate DHCP server and n clients

Objective: To learn simulate DHCP server and n clients

Theory: A DHCP Server is a network server that automatically provides and assigns IP
addresses, default gateways and other network parameters to client devices. It relies on the
standard protocol known as Dynamic Host Configuration Protocol or DHCP to respond to broadcast queries
by clients.

Program:

Line of Code:

DHCP.cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */

/*
* Copyright (c) 2011 UPB
* Copyright (c) 2017 NITK Surathkal
*
* 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
*
/

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 49

//
* Network layout:
*
* R0 is a DHCP server. The DHCP server announced R1 as the default router.
* Nodes N1 will send UDP Echo packets to node A.
*
*
* ┌-------------------------------------------------┐
* | DHCP Clients |
* | 172.30.0.14 |
* | DHCP static |
* | ┌──────┐ ┌──────┐ ┌──────┐ |
* | │ N0 │ │ N1 │ │ N2 │ | ┌──────┐
* | └──────┘ └──────┘ └──────┘ | ┌────│ A │
* | │ │ │ | │ └──────┘
* └-------│--------------│---------------│----------┘ │ 172.30.1.2
* DHCP Server │ │ │ │
* ┌──────┐ │ │ │ ┌──────┐ │
* │ R0
│────────┴──────────────┴───────────────┴──────│ R1 │────┘
* └──────┘ └──────┘172.30.1.1
* 172.30.0.12 172.30.0.17
*
* Things to notice:
* 1) The routes in A are manually set to have R1 as the default router,
* just because using a dynamic outing in this example is an overkill.
* 2) R1's address is set statically though the DHCP server helper interface.
* This is useful to prevent address conflicts with the dynamic pool.
* Not necessary if the DHCP pool is not conflicting with static addresses. * 3)
N2 has a dynamically-assigned, static address (i.e., a fixed address assigned
via DHCP).
*
*/
#include "ns3/core-module.h"
#include "ns3/internet-apps-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/netanim-module.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("DhcpExample");
int main (int argc, char *argv[])
{
CommandLine cmd (__FILE__);
bool verbose = false; bool
tracing = false;
std::string animFile = "dhcp-server-client-animation.xml";
cmd.AddValue ("verbose", "turn on the logs", verbose); cmd.AddValue
("tracing", "turn on the tracing", tracing); cmd.Parse (argc,
argv);
// GlobalValue::Bind ("ChecksumEnabled", BooleanValue (true)); if
(verbose)
{

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 50

LogComponentEnable ("DhcpServer", LOG_LEVEL_ALL);


LogComponentEnable ("DhcpClient", LOG_LEVEL_ALL);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO); }
Time stopTime = Seconds (20);
NS_LOG_INFO ("Create nodes.");
NodeContainer nodes;
NodeContainer router;
nodes.Create (3); router.Create
(2);
NodeContainer net (nodes, router);
NS_LOG_INFO ("Create channels."); CsmaHelper
csma;
csma.SetChannelAttribute ("DataRate", StringValue ("5Mbps"));
csma.SetChannelAttribute ("Delay", StringValue ("2ms"));
csma.SetDeviceAttribute ("Mtu", UintegerValue (1500));
NetDeviceContainer devNet = csma.Install (net);
NodeContainer p2pNodes; p2pNodes.Add (net.Get
(4)); p2pNodes.Create (1);
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer p2pDevices;
p2pDevices = pointToPoint.Install (p2pNodes);
InternetStackHelper tcpip;
tcpip.Install (nodes); tcpip.Install
(router);
tcpip.Install (p2pNodes.Get (1)); Ipv4AddressHelper
address;
address.SetBase ("172.30.1.0", "255.255.255.0");
Ipv4InterfaceContainer p2pInterfaces; p2pInterfaces
= address.Assign (p2pDevices);
// manually add a routing entry because we don't want to add a dynamic routing
Ipv4StaticRoutingHelper ipv4RoutingHelper;
Ptr<Ipv4> ipv4Ptr = p2pNodes.Get (1)->GetObject<Ipv4> ();
Ptr<Ipv4StaticRouting> staticRoutingA = ipv4RoutingHelper.GetStaticRouting
(ipv4Ptr);
staticRoutingA->AddNetworkRouteTo (Ipv4Address ("172.30.0.0"), Ipv4Mask
("/24"),
Ipv4Address ("172.30.1.1"), 1);
NS_LOG_INFO ("Setup the IP addresses and create DHCP applications.");
DhcpHelper dhcpHelper;
// The router must have a fixed IP.
Ipv4InterfaceContainer fixedNodes = dhcpHelper.InstallFixedAddress
(devNet.Get (4), Ipv4Address ("172.30.0.17"), Ipv4Mask ("/24")); //
Not really necessary, IP forwarding is enabled by default in IPv4.
fixedNodes.Get (0).first->SetAttribute ("IpForward", BooleanValue (true)); //
DHCP server
ApplicationContainer dhcpServerApp = dhcpHelper.InstallDhcpServer
(devNet.Get (3), Ipv4Address ("172.30.0.12"),
Ipv4Address ("172.30.0.0"), Ipv4Mask ("/24"),
Ipv4Address ("172.30.0.10"), Ipv4Address ("172.30.0.15"),
Ipv4Address ("172.30.0.17"));
// This is just to show how it can be done.

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 51

DynamicCast<DhcpServer> (dhcpServerApp.Get (0))->AddStaticDhcpEntry


(devNet.Get (2)->GetAddress (), Ipv4Address ("172.30.0.14"));
dhcpServerApp.Start (Seconds (0.0)); dhcpServerApp.Stop (stopTime);
// DHCP clients
NetDeviceContainer dhcpClientNetDevs; dhcpClientNetDevs.Add
(devNet.Get (0)); dhcpClientNetDevs.Add (devNet.Get (1));
dhcpClientNetDevs.Add (devNet.Get (2));
ApplicationContainer dhcpClients =
dhcpHelper.InstallDhcpClient
(dhcpClientNetDevs); dhcpClients.Start
(Seconds (1.0)); dhcpClients.Stop
(stopTime); UdpEchoServerHelper
echoServer (9);
ApplicationContainer serverApps = echoServer.Install (p2pNodes.Get (1));
serverApps.Start (Seconds (0.0)); serverApps.Stop (stopTime);
UdpEchoClientHelper echoClient (p2pInterfaces.GetAddress (1), 9);
echoClient.SetAttribute ("MaxPackets", UintegerValue (100));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0)));
echoClient.SetAttribute ("PacketSize", UintegerValue (1024));
ApplicationContainer clientApps = echoClient.Install (nodes.Get (1));
clientApps.Start (Seconds (10.0)); clientApps.Stop (stopTime);
Simulator::Stop (stopTime + Seconds (10.0));
// Create the animation object and configure for specified output
AnimationInterface anim ("dhcp.xml"); if
(tracing)
{
csma.EnablePcapAll ("dhcp-csma"); pointToPoint.EnablePcapAll
("dhcp-p2p");
}
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done."); }

Output: NetAnim Screen:

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 52

Name: Pallavi Roll


MCAL26: Networking with Linux Page No. 53

Name: Pallavi Roll

You might also like