Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CN Lab Record Final

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

LAKIREDDY BALI REDDY COLLEGE OF ENGINEERING

(AUTONOMOUS)

Department of Information Technology

20CS60 – COMPUTER NETWORKS LAB

Name of the Student: ---------------------------------------------------------------------

Registered Number: ----------------------------------------------------------------------

Branch & Section: IT & B

Academic Year: 2024 - 2025


LAKIREDDY BALI REDDY COLLEGE OF
ENGINEERING
(AUTONOMOUS)

CERTIFICATE

This is to certify that this is a bonafide record of the practical workdone

By Mr./Ms. _________________________________________________________,

Bearing Regd Num: _______________ of B. Tech V Semester, IT,

B Section in the 20CS60 – COMPUTER NETWORKS LAB during the

Academic Year: 2024-25.

No. of Experiments held : 10

No. of Experiments Done: 10

Date: ______________

Signature of the Faculty

INTERNAL EXAMINER EXTERNAL EXAMINER


INDEX

S.NO. DATE NAME OF THE EXPERIMENT PAGE SIGNATURE


NO
1 To gain familiarity with the basic ‘Networks’
Commands & utilities available in the Linux
OS.

2 To learn about network layer tools and analyze


captures for congestion.

3 To learn about Queue Management Techniques,


and Global Routing in NS3

4 To learn about broadcasting, multicasting, and


bridging in a Local Area Network using NS3.

5 To learn about Wifi and Mobile Adhoc


topologies with NS3.

6 To introduce Socket Programming in TCP and


UDP

7 Observations of Transmission Control


Protocol(TCP)Connection states, Flags and
Flow control.

8 To learn Transmission Control


Protocol(TCP)Flow Control, Error Control, and
Congestion

9 To introduce Wireshark & tcp dump, and


observation of packets in a LAN network

10 To analyze HTTP packets using Wireshark tool,


and understand the records returned by a DNS
server
Experiment-1

Aim: To gain familiarity with the basic ‘Networks’ Commands & utilities available in the
Linux OS.

1) Troubleshooting network hosts


a) ping <address>
Short for Packet InterNet Groper, the ping command is used to test the ability of your
computer to reach a specified destination computer. The ping command is usually used as a
simple way to verify that a computer can communicate over the network with another
computer or network device.

OUTPUT:

b) ifconfig [options]
ifconfig is used to configure the network interfaces. It is used at boot time to set up interfaces
as necessary. After that, it is usually only needed when debugging or when system tuning is
needed.
OUTPUT :
If no arguments are given, ifconfig displays the status of the currently active interfaces.

1
If a single interface argument is given, it displays the status of the given interface only ;

If a
single -a argument is given, it displays the status of all interfaces, even those that are
down .

c) sudo ifconfig eth0 down


The above command will bring the ethernet interface down, meaning, the system would be
disconnected from the network. Now, try to ping any network host. What is the observed
output?

2
d) sudo ifconfig eth0 up
This command will call DHCP service which is involved in obtaining an IP address. Now,
ping
to any external system. What is the observed output?

e) ifplugstatus
The ifplugstatus command will tell you whether a cable is plugged into a network interface or
not. It isn’t installed by default on Ubuntu. Use the following command to install it:

sudo apt-get install ifplugd.

OUTPUT:

OUTPUT:
ifplugstatus command when the cable is plugged.

2) Finding all the intermediate network systems

a) traceroute <address>

It isn’t installed by default on Ubuntu. Use the following command to install it:

sudo apt-get install traceroute

3
traceroute is a command used to display the intermediate nodes through which a packet
flows from a source location to a destination location. A program capable of doing the same
in Microsoft Windows is tracert.

OUTPUT:

3) DNS tools

Find the IP addresses of the following :

a) nslookup <address>

nslookup is a program to query Internet domain name servers. nslookup has two modes:
interactive and noninteractive. Interactive mode allows the user to query name servers for
information about various hosts and domains or to print a list of hosts in a domain. Non-
interactive mode is used to print just the name and requested information for a host or
domain.

OUTPUT:

b) host <address>

host is a simple utility for performing DNS lookups. It is normally used to convert names to
IP
addresses and vice versa. When no arguments or options are given, host prints a short
summary of its command line arguments and options.

OUTPUT:

4
c) dig <address>

domain information groper or dig is a flexible tool for interrogating DNS name servers. It
performs DNS lookups and displays the answers that are returned from the name server(s)
that were queried.

OUTPUT:

5
Experiment-2

AIM:- To learn about network layer tools and analyze captures for congestion.

To view routing table entries:


A routing table, or routing information base (RIB), is a data table stored in a router or a
networked computer that lists the routes to particular network destinations, and in some cases,
metrics (distances) associated with those routes. The routing table contains information about the
topology of the network immediately around it. The construction of routing tables is the primary goal
of routing protocols. Static routes are entries made in a routing table by non-automatic means, which
are fixed rather than being the result of some network topology "discovery" procedure.

OUTPUT:

b. Option “n” displays all symbolic references in numeric values.

c. For faster processing, the routing table is stored in kernel cache. To retrieve table from
cache, use option “C”. By default, “route” command shows the table
stored in FIB.

6
Analyzation Using Nmap/Zenmap:
In the command area Give : nmap –sS (secure shell)

In the Target area Give: IPV4 Address(your system IPV4) Copy as below IPV4

7
NEXT CLICK ON TOPOLOGY AS SHOWN BELOW GRAPHICAL REPRESENTATION

8
In the command area Give : nmap –h (help)

Click on the legend on right side of the window

9
In the command prompt: type nmap –v (verbose)

In the command prompt: type nmap –sU –v 172.16.12.175 (for UDP Packets in IPV4 Add)

10
Experiment - 3

Aim: To learn about Queue Management Techniques, and Global Routing in NS3.

1.Simple Global 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/applications-module.h"
#include "ns3/flow-monitor-helper.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/netanim-module.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);

11
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

12
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 ();
}

AnimationInterface anim("third.xml");
anim.SetConstantPosition(c.Get(0),10.0,30.0);
anim.SetConstantPosition(c.Get(1),20.0,40.0);
anim.SetConstantPosition(c.Get(2),30.0,50.0);
anim.SetConstantPosition(c.Get(3),40.0,60.0);
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;
}

13
OUTPUT:

2. Dynmic-global-routing:

// Network topology
//
// n0
// \ p-p
// \ (shared csma/cd)
// n2 -------------------------n3
// / | |
// / p-p n4 n5 ---------- n6
// n1 p-p
// | |
// ----------------------------------------
// p-p
//

#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"

14
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/netanim-module.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("DynamicGlobalRoutingExample");

int
main (int argc, char *argv[])
{
// The below value configures the default behavior of global routing.
// By default, it is disabled. To respond to interface events, set to true
Config::SetDefault ("ns3::Ipv4GlobalRouting::RespondToInterfaceEvents", BooleanValue
(true));

// 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 n1n6 = NodeContainer (c.Get (1), 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 d1d6 = p2p.Install (n1n6);

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

15
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);

ipv4.SetBase ("172.16.1.0", "255.255.255.0");


Ipv4InterfaceContainer i1i6 = ipv4.Assign (d1d6);

// 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 ("2kbps"));
onoff.SetAttribute ("PacketSize", UintegerValue (50));

ApplicationContainer apps = onoff.Install (c.Get (1));


apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));

// Create a second OnOff application to send UDP datagrams of size


// 210 bytes at a rate of 448 Kb/s
OnOffHelper onoff2 ("ns3::UdpSocketFactory",
InetSocketAddress (i1i6.GetAddress (1), port));
onoff2.SetAttribute ("OnTime", StringValue
("ns3::ConstantRandomVariable[Constant=1]"));
onoff2.SetAttribute ("OffTime", StringValue
("ns3::ConstantRandomVariable[Constant=0]"));

16
onoff2.SetAttribute ("DataRate", StringValue ("2kbps"));
onoff2.SetAttribute ("PacketSize", UintegerValue (50));

ApplicationContainer apps2 = onoff2.Install (c.Get (1));


apps2.Start (Seconds (11.0));
apps2.Stop (Seconds (16.0));

// Create an optional packet sink to receive these packets


PacketSinkHelper sink ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
apps = sink.Install (c.Get (6));
apps.Start (Seconds (1.0));
apps.Stop (Seconds (10.0));

PacketSinkHelper sink2 ("ns3::UdpSocketFactory",


Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
apps2 = sink2.Install (c.Get (6));
apps2.Start (Seconds (11.0));
apps2.Stop (Seconds (16.0));

AsciiTraceHelper ascii;
Ptr<OutputStreamWrapper> stream = ascii.CreateFileStream ("dynamic-global-routing.tr");
p2p.EnableAsciiAll (stream);
csma.EnableAsciiAll (stream);
internet.EnableAsciiIpv4All (stream);

p2p.EnablePcapAll ("dynamic-global-routing");
csma.EnablePcapAll ("dynamic-global-routing", false);

Ptr<Node> n1 = c.Get (1);


Ptr<Ipv4> ipv41 = n1->GetObject<Ipv4> ();
// The first ifIndex is 0 for loopback, then the first p2p is numbered 1,
// then the next p2p is numbered 2
uint32_t ipv4ifIndex1 = 2;

Simulator::Schedule (Seconds (2),&Ipv4::SetDown,ipv41, ipv4ifIndex1);


Simulator::Schedule (Seconds (4),&Ipv4::SetUp,ipv41, ipv4ifIndex1);

Ptr<Node> n6 = c.Get (6);


Ptr<Ipv4> ipv46 = n6->GetObject<Ipv4> ();
// The first ifIndex is 0 for loopback, then the first p2p is numbered 1,
// then the next p2p is numbered 2
uint32_t ipv4ifIndex6 = 2;
Simulator::Schedule (Seconds (6),&Ipv4::SetDown,ipv46, ipv4ifIndex6);
Simulator::Schedule (Seconds (8),&Ipv4::SetUp,ipv46, ipv4ifIndex6);

Simulator::Schedule (Seconds (12),&Ipv4::SetDown,ipv41, ipv4ifIndex1);

17
Simulator::Schedule (Seconds (14),&Ipv4::SetUp,ipv41, ipv4ifIndex1);

// Trace routing tables


Ipv4GlobalRoutingHelper g;
Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper> ("dynamic-
global-routing.routes", std::ios::out);
g.PrintRoutingTableAllAt (Seconds (12), routingStream);
AnimationInterface anim("DynamicGlobalRoutingExample.xml");
anim.SetConstantPosition(c.Get(0),10.0,30.0);
anim.SetConstantPosition(c.Get(1),20.0,40.0);
anim.SetConstantPosition(c.Get(2),30.0,50.0);
anim.SetConstantPosition(c.Get(3),40.0,60.0);
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}

OUTPUT:

3. Manet-routing-compare:
#include <fstream>
#include <iostream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/aodv-module.h"
#include "ns3/olsr-module.h"
#include "ns3/dsdv-module.h"

18
#include "ns3/dsr-module.h"
#include "ns3/applications-module.h"
#include "ns3/yans-wifi-helper.h"
#include "ns3/netanim-module.h"

using namespace ns3;


using namespace dsr;

NS_LOG_COMPONENT_DEFINE ("manet-routing-compare");

class RoutingExperiment
{
public:
RoutingExperiment ();
void Run (int nSinks, double txp, std::string CSVfileName);
//static void SetMACParam (ns3::NetDeviceContainer & devices,
// int slotDistance);
std::string CommandSetup (int argc, char **argv);

private:
Ptr<Socket> SetupPacketReceive (Ipv4Address addr, Ptr<Node> node);
void ReceivePacket (Ptr<Socket> socket);
void CheckThroughput ();

uint32_t port;
uint32_t bytesTotal;
uint32_t packetsReceived;

std::string m_CSVfileName;
int m_nSinks;
std::string m_protocolName;
double m_txp;
bool m_traceMobility;
uint32_t m_protocol;
};

RoutingExperiment::RoutingExperiment ()
: port (9),
bytesTotal (0),
packetsReceived (0),
m_CSVfileName ("manet-routing.output.csv"),
m_traceMobility (false),
m_protocol (2) // AODV
{
}

static inline std::string


PrintReceivedPacket (Ptr<Socket> socket, Ptr<Packet> packet, Address senderAddress)

19
{
std::ostringstream oss;

oss << Simulator::Now ().GetSeconds () << " " << socket->GetNode ()->GetId ();

if (InetSocketAddress::IsMatchingType (senderAddress))
{
InetSocketAddress addr = InetSocketAddress::ConvertFrom (senderAddress);
oss << " received one packet from " << addr.GetIpv4 ();
}
else
{
oss << " received one packet!";
}
return oss.str ();
}

void
RoutingExperiment::ReceivePacket (Ptr<Socket> socket)
{
Ptr<Packet> packet;
Address senderAddress;
while ((packet = socket->RecvFrom (senderAddress)))
{
bytesTotal += packet->GetSize ();
packetsReceived += 1;
NS_LOG_UNCOND (PrintReceivedPacket (socket, packet, senderAddress));
}
}

void
RoutingExperiment::CheckThroughput ()
{
double kbs = (bytesTotal * 8.0) / 1000;
bytesTotal = 0;

std::ofstream out (m_CSVfileName.c_str (), std::ios::app);

out << (Simulator::Now ()).GetSeconds () << ","


<< kbs << ","
<< packetsReceived << ","
<< m_nSinks << ","
<< m_protocolName << ","
<< m_txp << ""
<< std::endl;

out.close ();
packetsReceived = 0;

20
Simulator::Schedule (Seconds (1.0), &RoutingExperiment::CheckThroughput, this);
}

Ptr<Socket>
RoutingExperiment::SetupPacketReceive (Ipv4Address addr, Ptr<Node> node)
{
TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
Ptr<Socket> sink = Socket::CreateSocket (node, tid);
InetSocketAddress local = InetSocketAddress (addr, port);
sink->Bind (local);
sink->SetRecvCallback (MakeCallback (&RoutingExperiment::ReceivePacket, this));

return sink;
}

std::string
RoutingExperiment::CommandSetup (int argc, char **argv)
{
CommandLine cmd;
cmd.AddValue ("CSVfileName", "The name of the CSV output file name",
m_CSVfileName);
cmd.AddValue ("traceMobility", "Enable mobility tracing", m_traceMobility);
cmd.AddValue ("protocol", "1=OLSR;2=AODV;3=DSDV;4=DSR", m_protocol);
cmd.Parse (argc, argv);
return m_CSVfileName;
}

int
main (int argc, char *argv[])
{
RoutingExperiment experiment;
std::string CSVfileName = experiment.CommandSetup (argc,argv);

//blank out the last output file and write the column headers
std::ofstream out (CSVfileName.c_str ());
out << "SimulationSecond," <<
"ReceiveRate," <<
"PacketsReceived," <<
"NumberOfSinks," <<
"RoutingProtocol," <<
"TransmissionPower" <<
std::endl;
out.close ();

int nSinks = 10;


double txp = 7.5;

experiment.Run (nSinks, txp, CSVfileName);

21
}

void
RoutingExperiment::Run (int nSinks, double txp, std::string CSVfileName)
{
Packet::EnablePrinting ();
m_nSinks = nSinks;
m_txp = txp;
m_CSVfileName = CSVfileName;

int nWifis = 50;

double TotalTime = 200.0;


std::string rate ("2048bps");
std::string phyMode ("DsssRate11Mbps");
std::string tr_name ("manet-routing-compare");
int nodeSpeed = 20; //in m/s
int nodePause = 0; //in s
m_protocolName = "protocol";

Config::SetDefault ("ns3::OnOffApplication::PacketSize",StringValue ("64"));


Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue (rate));

//Set Non-unicastMode rate to unicast mode


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

NodeContainer adhocNodes;
adhocNodes.Create (nWifis);

// setting up wifi phy and channel using helpers


WifiHelper wifi;
wifi.SetStandard (WIFI_PHY_STANDARD_80211b);

YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();


YansWifiChannelHelper wifiChannel;
wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
wifiChannel.AddPropagationLoss ("ns3::FriisPropagationLossModel");
wifiPhy.SetChannel (wifiChannel.Create ());

// Add a mac and disable rate control


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

wifiPhy.Set ("TxPowerStart",DoubleValue (txp));


wifiPhy.Set ("TxPowerEnd", DoubleValue (txp));

22
wifiMac.SetType ("ns3::AdhocWifiMac");
NetDeviceContainer adhocDevices = wifi.Install (wifiPhy, wifiMac, adhocNodes);

MobilityHelper mobilityAdhoc;
int64_t streamIndex = 0; // used to get consistent mobility across scenarios

ObjectFactory pos;
pos.SetTypeId ("ns3::RandomRectanglePositionAllocator");
pos.Set ("X", StringValue ("ns3::UniformRandomVariable[Min=0.0|Max=300.0]"));
pos.Set ("Y", StringValue ("ns3::UniformRandomVariable[Min=0.0|Max=1500.0]"));

Ptr<PositionAllocator> taPositionAlloc = pos.Create ()->GetObject<PositionAllocator> ();


streamIndex += taPositionAlloc->AssignStreams (streamIndex);

std::stringstream ssSpeed;
ssSpeed << "ns3::UniformRandomVariable[Min=0.0|Max=" << nodeSpeed << "]";
std::stringstream ssPause;
ssPause << "ns3::ConstantRandomVariable[Constant=" << nodePause << "]";
mobilityAdhoc.SetMobilityModel ("ns3::RandomWaypointMobilityModel",
"Speed", StringValue (ssSpeed.str ()),
"Pause", StringValue (ssPause.str ()),
"PositionAllocator", PointerValue (taPositionAlloc));
mobilityAdhoc.SetPositionAllocator (taPositionAlloc);
mobilityAdhoc.Install (adhocNodes);
streamIndex += mobilityAdhoc.AssignStreams (adhocNodes, streamIndex);
NS_UNUSED (streamIndex); // From this point, streamIndex is unused

AodvHelper aodv;
OlsrHelper olsr;
DsdvHelper dsdv;
DsrHelper dsr;
DsrMainHelper dsrMain;
Ipv4ListRoutingHelper list;
InternetStackHelper internet;

switch (m_protocol)
{
case 1:
list.Add (olsr, 100);
m_protocolName = "OLSR";
break;
case 2:
list.Add (aodv, 100);
m_protocolName = "AODV";
break;
case 3:
list.Add (dsdv, 100);

23
m_protocolName = "DSDV";
break;
case 4:
m_protocolName = "DSR";
break;
default:
NS_FATAL_ERROR ("No such protocol:" << m_protocol);
}

if (m_protocol < 4)
{
internet.SetRoutingHelper (list);
internet.Install (adhocNodes);
}
else if (m_protocol == 4)
{
internet.Install (adhocNodes);
dsrMain.Install (dsr, adhocNodes);
}

NS_LOG_INFO ("assigning ip address");

Ipv4AddressHelper addressAdhoc;
addressAdhoc.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer adhocInterfaces;
adhocInterfaces = addressAdhoc.Assign (adhocDevices);

OnOffHelper onoff1 ("ns3::UdpSocketFactory",Address ());


onoff1.SetAttribute ("OnTime", StringValue
("ns3::ConstantRandomVariable[Constant=1.0]"));
onoff1.SetAttribute ("OffTime", StringValue
("ns3::ConstantRandomVariable[Constant=0.0]"));

for (int i = 0; i < nSinks; i++)


{
Ptr<Socket> sink = SetupPacketReceive (adhocInterfaces.GetAddress (i),
adhocNodes.Get (i));

AddressValue remoteAddress (InetSocketAddress (adhocInterfaces.GetAddress (i),


port));
onoff1.SetAttribute ("Remote", remoteAddress);

Ptr<UniformRandomVariable> var = CreateObject<UniformRandomVariable> ();


ApplicationContainer temp = onoff1.Install (adhocNodes.Get (i + nSinks));
temp.Start (Seconds (var->GetValue (100.0,101.0)));
temp.Stop (Seconds (TotalTime));
}

24
std::stringstream ss;
ss << nWifis;
std::string nodes = ss.str ();

std::stringstream ss2;
ss2 << nodeSpeed;
std::string sNodeSpeed = ss2.str ();

std::stringstream ss3;
ss3 << nodePause;
std::string sNodePause = ss3.str ();

std::stringstream ss4;
ss4 << rate;
std::string sRate = ss4.str ();

//NS_LOG_INFO ("Configure Tracing.");


//tr_name = tr_name + "_" + m_protocolName +"_" + nodes + "nodes_" + sNodeSpeed +
"speed_" + sNodePause + "pause_" + sRate + "rate";

//AsciiTraceHelper ascii;
//Ptr<OutputStreamWrapper> osw = ascii.CreateFileStream ( (tr_name + ".tr").c_str());
//wifiPhy.EnableAsciiAll (osw);
AsciiTraceHelper ascii;
MobilityHelper::EnableAsciiAll (ascii.CreateFileStream (tr_name + ".mob"));

//Ptr<FlowMonitor> flowmon;
//FlowMonitorHelper flowmonHelper;
//flowmon = flowmonHelper.InstallAll ();

NS_LOG_INFO ("Run Simulation.");

CheckThroughput ();

Simulator::Stop (Seconds (TotalTime));


AnimationInterface anim("manet-routing-compare.xml");
anim.SetConstantPosition(adhocNodes.Get(0),100.10,2000);
anim.SetConstantPosition(adhocNodes.Get(1),300.10,200,0);
anim.SetConstantPosition(adhocNodes.Get(2),100.10,500,0);
anim.SetConstantPosition(adhocNodes.Get(3),200.10,600.0);
anim.SetConstantPosition(adhocNodes.Get(4),300.0,800.0);
anim.SetConstantPosition(adhocNodes.Get(5),500,0,400.0);
anim.SetConstantPosition(adhocNodes.Get(7),3000,600.0);
anim.SetConstantPosition(adhocNodes.Get(8),600.0,700.0);
anim.SetConstantPosition(adhocNodes.Get(9),300.0,600.0);
anim.SetConstantPosition(adhocNodes.Get(10),300.0,600.0);

25
Simulator::Stop (Seconds (11));
Simulator::Run ();

Simulator::Destroy ();
}

OUTPUT:

Experiment - 4

Aim: To learn about broadcasting, multicasting, and bridging in a Local Area Network using
NS3.

1. CSMA-Broadcasting:

// Example of the sending of a datagram to a broadcast address


//
// Network topology
// ==============
// | |
// n0 n1 n2
// | |
// ==========
//
// n0 originates UDP broadcast to 255.255.255.255/discard port, which
// is replicated and received on both n1 and n2

#include <iostream>
#include <fstream>
#include <string>

26
#include <cassert>

#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/internet-module.h"
#include "ns3/netanim-module.h"
using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("CsmaBroadcastExample");

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 ("CsmaBroadcastExample", LOG_LEVEL_INFO);
#endif
LogComponentEnable ("CsmaBroadcastExample", LOG_PREFIX_TIME);

// 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 (2);
NodeContainer c0 = NodeContainer (c.Get (0), c.Get (1));
NodeContainer c1 = NodeContainer (c.Get (0), c.Get (2));

NS_LOG_INFO ("Build Topology.");


CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (DataRate (5000000)));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));

NetDeviceContainer n0 = csma.Install (c0);


NetDeviceContainer n1 = csma.Install (c1);

InternetStackHelper internet;
internet.Install (c);

NS_LOG_INFO ("Assign IP Addresses.");


Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.0.0", "255.255.255.0");
ipv4.Assign (n0);

27
ipv4.SetBase ("192.168.1.0", "255.255.255.0");
ipv4.Assign (n1);

// RFC 863 discard port ("9") indicates packet should be thrown away
// by the system. We allow this silent discard to be overridden
// by the PacketSink application.
uint16_t port = 9;

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


// 512 bytes (default) at a rate of 500 Kb/s (default) from n0
NS_LOG_INFO ("Create Applications.");
OnOffHelper onoff ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address ("255.255.255.255"), port)));
onoff.SetConstantRate (DataRate ("500kb/s"));

ApplicationContainer app = onoff.Install (c0.Get (0));


// Start the application
app.Start (Seconds (1.0));
app.Stop (Seconds (10.0));

// Create an optional packet sink to receive these packets


PacketSinkHelper sink ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
app = sink.Install (c0.Get (1));
app.Add (sink.Install (c1.Get (1)));
app.Start (Seconds (1.0));
app.Stop (Seconds (10.0));

// Configure ascii tracing of all enqueue, dequeue, and NetDevice receive


// events on all devices. Trace output will be sent to the file
// "csma-one-subnet.tr"
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("csma-broadcast.tr"));

// Also configure some tcpdump traces; each interface will be traced


// The output files will be named
// csma-broadcast-<nodeId>-<interfaceId>.pcap
// and can be read by the "tcpdump -tt -r" command
csma.EnablePcapAll ("csma-broadcast", false);

NS_LOG_INFO ("Run Simulation.");


Simulator::Run ();

AnimationInterface anim("csma.broadcast.xml");
anim.SetConstantPosition(c.Get(0),10.0,30.0);
anim.SetConstantPosition(c.Get(1),20.0,50.0);

28
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}

OUTPUT:

2. CSMA– Multicasting:

// Network topology
//
// Lan1
// ===========
// | | |
// n0 n1 n2 n3 n4
// | | |
// ===========
// Lan0
//
// - Multicast source is at node n0;
// - Multicast forwarded by node n2 onto LAN1;
// - Nodes n0, n1, n2, n3, and n4 receive the multicast frame.
// - Node n4 listens for the data

#include <iostream>
#include <fstream>

#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"

29
#include "ns3/internet-module.h"
#include "ns3/netanim-module.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("CsmaMulticastExample");

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
//
// LogComponentEnable ("CsmaMulticastExample", LOG_LEVEL_INFO);

//
// Set up default values for the simulation.
//
// Select DIX/Ethernet II-style encapsulation (no LLC/Snap header)
Config::SetDefault ("ns3::CsmaNetDevice::EncapsulationMode", StringValue ("Dix"));

// Allow the user to override any of the defaults at


// run-time, via command-line arguments
CommandLine cmd;
cmd.Parse (argc, argv);

NS_LOG_INFO ("Create nodes.");


NodeContainer c;
c.Create (5);
// We will later want two subcontainers of these nodes, for the two LANs
NodeContainer c0 = NodeContainer (c.Get (0), c.Get (1), c.Get (2));
NodeContainer c1 = NodeContainer (c.Get (2), c.Get (3), c.Get (4));

NS_LOG_INFO ("Build Topology.");


CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (DataRate (5000000)));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));

// We will use these NetDevice containers later, for IP addressing


NetDeviceContainer nd0 = csma.Install (c0); // First LAN
NetDeviceContainer nd1 = csma.Install (c1); // Second LAN

NS_LOG_INFO ("Add IP Stack.");


InternetStackHelper internet;
internet.Install (c);

NS_LOG_INFO ("Assign IP Addresses.");

30
Ipv4AddressHelper ipv4Addr;
ipv4Addr.SetBase ("10.1.1.0", "255.255.255.0");
ipv4Addr.Assign (nd0);
ipv4Addr.SetBase ("10.1.2.0", "255.255.255.0");
ipv4Addr.Assign (nd1);

NS_LOG_INFO ("Configure multicasting.");


//
// Now we can configure multicasting. As described above, the multicast
// source is at node zero, which we assigned the IP address of 10.1.1.1
// earlier. We need to define a multicast group to send packets to. This
// can be any multicast address from 224.0.0.0 through 239.255.255.255
// (avoiding the reserved routing protocol addresses).
//

Ipv4Address multicastSource ("10.1.1.1");


Ipv4Address multicastGroup ("225.1.2.4");

// Now, we will set up multicast routing. We need to do three things:


// 1) Configure a (static) multicast route on node n2
// 2) Set up a default multicast route on the sender n0
// 3) Have node n4 join the multicast group
// We have a helper that can help us with static multicast
Ipv4StaticRoutingHelper multicast;

// 1) Configure a (static) multicast route on node n2 (multicastRouter)


Ptr<Node> multicastRouter = c.Get (2); // The node in question
Ptr<NetDevice> inputIf = nd0.Get (2); // The input NetDevice
NetDeviceContainer outputDevices; // A container of output NetDevices
outputDevices.Add (nd1.Get (0)); // (we only need one NetDevice here)

multicast.AddMulticastRoute (multicastRouter, multicastSource,


multicastGroup, inputIf, outputDevices);

// 2) Set up a default multicast route on the sender n0


Ptr<Node> sender = c.Get (0);
Ptr<NetDevice> senderIf = nd0.Get (0);
multicast.SetDefaultMulticastRoute (sender, senderIf);

//
// Create an OnOff application to send UDP datagrams from node zero to the
// multicast group (node four will be listening).
//
NS_LOG_INFO ("Create Applications.");

uint16_t multicastPort = 9; // Discard port (RFC 863)

// Configure a multicast packet generator that generates a packet

31
// every few seconds
OnOffHelper onoff ("ns3::UdpSocketFactory",
Address (InetSocketAddress (multicastGroup, multicastPort)));
onoff.SetConstantRate (DataRate ("255b/s"));
onoff.SetAttribute ("PacketSize", UintegerValue (128));

ApplicationContainer srcC = onoff.Install (c0.Get (0));

//
// Tell the application when to start and stop.
//
srcC.Start (Seconds (1.));
srcC.Stop (Seconds (10.));

// Create an optional packet sink to receive these packets


PacketSinkHelper sink ("ns3::UdpSocketFactory",
InetSocketAddress (Ipv4Address::GetAny (), multicastPort));

ApplicationContainer sinkC = sink.Install (c1.Get (2)); // Node n4


// Start the sink
sinkC.Start (Seconds (1.0));
sinkC.Stop (Seconds (10.0));

NS_LOG_INFO ("Configure Tracing.");


//
// Configure tracing of all enqueue, dequeue, and NetDevice receive events.
// Ascii trace output will be sent to the file "csma-multicast.tr"
//
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("csma-multicast.tr"));

// Also configure some tcpdump traces; each interface will be traced.


// The output files will be named:
// csma-multicast-<nodeId>-<interfaceId>.pcap
// and can be read by the "tcpdump -r" command (use "-tt" option to
// display timestamps correctly)
csma.EnablePcapAll ("csma-multicast", false);

//
// Now, do the actual simulation.
//
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
AnimationInterface anim("csma.multicast.xml");
anim.SetConstantPosition(c.Get(0),10.0,30.0);
anim.SetConstantPosition(c.Get(1),20.0,50.0);
Simulator::Destroy ();
NS_LOG_INFO ("Done.");

32
}
OUTPUT:

3. CSMA-Bridge:

// Network topology
//
// n0 n1
// | |
// ----------
// | Switch |
// ----------
// | |
// n2 n3
//
//
// - CBR/UDP flows from n0 to n1 and from n3 to n0
// - DropTail queues
// - Tracing of queues and packet receptions to file "csma-bridge.tr"

#include <iostream>
#include <fstream>

#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/bridge-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/netanim-module.h"

33
using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("CsmaBridgeExample");

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 ("CsmaBridgeExample", LOG_LEVEL_INFO);
#endif

//
// Allow the user to override any of the defaults and the above Bind() at
// run-time, via command-line arguments
//
CommandLine cmd;
cmd.Parse (argc, argv);

//
// Explicitly create the nodes required by the topology (shown above).
//
NS_LOG_INFO ("Create nodes.");
NodeContainer c;
c.Create (4);

NodeContainer csmaSwitch;
csmaSwitch.Create (1);

NS_LOG_INFO ("Build Topology");


CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (5000000));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));

// Create the csma links, from each terminal to the switch

NetDeviceContainer terminalDevices;
NetDeviceContainer switchDevices;

for (int i = 0; i < 3; i++)


{
NetDeviceContainer link = csma.Install (NodeContainer (c.Get (i), csmaSwitch));
terminalDevices.Add (link.Get (0));
switchDevices.Add (link.Get (1));

34
}

// Create the bridge netdevice, which will do the packet switching


Ptr<Node> switchNode = csmaSwitch.Get (0);
BridgeHelper bridge;
bridge.Install (switchNode, switchDevices);

// Add internet stack to the terminals


InternetStackHelper internet;
internet.Install (c);

// We've got the "hardware" in place. Now we need to add IP addresses.


//
NS_LOG_INFO ("Assign IP Addresses.");
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
ipv4.Assign (terminalDevices);

//
// Create an OnOff application to send UDP datagrams from node zero to node 1.
//
NS_LOG_INFO ("Create Applications.");
uint16_t port = 9; // Discard port (RFC 863)

OnOffHelper onoff ("ns3::UdpSocketFactory",


Address (InetSocketAddress (Ipv4Address ("10.1.1.2"), port)));
onoff.SetConstantRate (DataRate ("500kb/s"));

ApplicationContainer app = onoff.Install (c.Get (0));


// Start the application
app.Start (Seconds (1.0));
app.Stop (Seconds (10.0));

// Create an optional packet sink to receive these packets


PacketSinkHelper sink ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
app = sink.Install (c.Get (1));
app.Start (Seconds (0.0));

//
// Create a similar flow from n3 to n0, starting at time 1.1 seconds
//
onoff.SetAttribute ("Remote",
AddressValue (InetSocketAddress (Ipv4Address ("10.1.1.1"), port)));
app = onoff.Install (c.Get (3));
app.Start (Seconds (1.1));
app.Stop (Seconds (10.0));

35
app = sink.Install (c.Get (0));
app.Start (Seconds (0.0));

NS_LOG_INFO ("Configure Tracing.");

//
// Configure tracing of all enqueue, dequeue, and NetDevice receive events.
// Trace output will be sent to the file "csma-bridge.tr"
//
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("csma-bridge.tr"));

//
// Also configure some tcpdump traces; each interface will be traced.
// The output files will be named:
// csma-bridge-<nodeId>-<interfaceId>.pcap
// and can be read by the "tcpdump -r" command (use "-tt" option to
// display timestamps correctly)
//
csma.EnablePcapAll ("csma-bridge", false);

//
// Now, do the actual simulation.
//
AnimationInterface anim("CsmaBridgeExample.xml");
anim.SetConstantPosition(c.Get(0),10.0,30.0);
anim.SetConstantPosition(c.Get(1),20.0,50.0);
anim.SetConstantPosition(c.Get(2),30.0,60.0);
anim.SetConstantPosition(c.Get(3),40.0,80.0);
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}

OUTPUT:

36
4. Bridge-one-hop:

// Network topology
//
// bridge1 The node named bridge1 (node 5 in the nodelist)
// ------------------ has three CMSA net devices that are bridged
// CSMA CSMA CSMA together using a BridgeNetDevice.
// | | |
// | | | The bridge node talks over three CSMA channels
// | | |
// CSMA CSMA CSMA to three other CSMA net devices
// ---- ---- ----
// n0 n1 n2 Node two acts as a router and talks to another
// ---- bridge that connects the remaining nodes.
// CSMA
// |
// n3 n4 |
// ---- ---- |
// CSMA CSMA |
// | | |
// | | |
// | | |
// CSMA CSMA CSMA The node named bridge2 (node 6 in the nodelist)
// ------------------ has three CMSA net devices that are bridged
// bridge2 together using a BridgeNetDevice.
//
// Or, more abstractly, recognizing that bridge 1 and bridge 2 are nodes
// with three net devices:
//
// n0 n1 (n0 = 10.1.1.2)

37
// | | (n1 = 10.1.1.3) Note odd addressing
// ----------- (n2 = 10.1.1.1)
// | bridge1 | <- n5
// -----------
// |
// router <- n2
// |
// -----------
// | bridge2 | <- n6
// ----------- (n2 = 10.1.2.1)
// | | (n3 = 10.1.2.2)
// n3 n4 (n4 = 10.1.2.3)
//
// So, this example shows two broadcast domains, each interconnected by a bridge
// with a router node (n2) interconnecting the layer-2 broadcast domains
//

#include <iostream>
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/bridge-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/netanim-module.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("CsmaBridgeOneHopExample");

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 ("CsmaBridgeOneHopExample", LOG_LEVEL_INFO);
#endif

//
// Allow the user to override any of the defaults and the above Bind() at
// run-time, via command-line arguments
//
CommandLine cmd;
cmd.Parse (argc, argv);

38
//
// Explicitly create the nodes required by the topology (shown above).
//
NS_LOG_INFO ("Create nodes.");
NodeContainer c;
c.Create (4);

Ptr<Node> n0 = CreateObject<Node> ();


Ptr<Node> n1 = CreateObject<Node> ();
Ptr<Node> n2 = CreateObject<Node> ();
Ptr<Node> n3 = CreateObject<Node> ();
Ptr<Node> n4 = CreateObject<Node> ();

Ptr<Node> bridge1 = CreateObject<Node> ();


Ptr<Node> bridge2 = CreateObject<Node> ();

NS_LOG_INFO ("Build Topology");


CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", DataRateValue (5000000));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));

// Create the csma links, from each terminal to the bridge


// This will create six network devices; we'll keep track separately
// of the devices on and off the bridge respectively, for later configuration
NetDeviceContainer topLanDevices;
NetDeviceContainer topBridgeDevices;

// It is easier to iterate the nodes in C++ if we put them into a container


NodeContainer topLan (n2, n0, n1);

for (int i = 0; i < 3; i++)


{
// install a csma channel between the ith toplan node and the bridge node
NetDeviceContainer link = csma.Install (NodeContainer (topLan.Get (i), bridge1));
topLanDevices.Add (link.Get (0));
topBridgeDevices.Add (link.Get (1));
}

//
// Now, Create the bridge netdevice, which will do the packet switching. The
// bridge lives on the node bridge1 and bridges together the topBridgeDevices
// which are the three CSMA net devices on the node in the diagram above.
//
BridgeHelper bridge;
bridge.Install (bridge1, topBridgeDevices);

// Add internet stack to the router nodes

39
NodeContainer routerNodes (n0, n1, n2, n3, n4);
InternetStackHelper internet;
internet.Install (routerNodes);

// Repeat for bottom bridged LAN


NetDeviceContainer bottomLanDevices;
NetDeviceContainer bottomBridgeDevices;
NodeContainer bottomLan (n2, n3, n4);
for (int i = 0; i < 3; i++)
{
NetDeviceContainer link = csma.Install (NodeContainer (bottomLan.Get (i), bridge2));
bottomLanDevices.Add (link.Get (0));
bottomBridgeDevices.Add (link.Get (1));
}
bridge.Install (bridge2, bottomBridgeDevices);

// We've got the "hardware" in place. Now we need to add IP addresses.


NS_LOG_INFO ("Assign IP Addresses.");
Ipv4AddressHelper ipv4;
ipv4.SetBase ("10.1.1.0", "255.255.255.0");
ipv4.Assign (topLanDevices);
ipv4.SetBase ("10.1.2.0", "255.255.255.0");
ipv4.Assign (bottomLanDevices);

//
// Create router nodes, initialize routing database and set up the routing
// tables in the nodes. We excuse the bridge nodes from having to serve as
// routers, since they don't even have internet stacks on them.
//
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();

//
// Create an OnOff application to send UDP datagrams from node zero to node 1.
//
NS_LOG_INFO ("Create Applications.");
uint16_t port = 9; // Discard port (RFC 863)

OnOffHelper onoff ("ns3::UdpSocketFactory",


Address (InetSocketAddress (Ipv4Address ("10.1.1.3"), port)));
onoff.SetConstantRate (DataRate ("500kb/s"));

ApplicationContainer app = onoff.Install (n0);


// Start the application
app.Start (Seconds (1.0));
app.Stop (Seconds (10.0));

// Create an optional packet sink to receive these packets


PacketSinkHelper sink ("ns3::UdpSocketFactory",

40
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
ApplicationContainer sink1 = sink.Install (n1);
sink1.Start (Seconds (1.0));
sink1.Stop (Seconds (10.0));

//
// Create a similar flow from n3 to n0, starting at time 1.1 seconds
//
onoff.SetAttribute ("Remote",
AddressValue (InetSocketAddress (Ipv4Address ("10.1.1.2"), port)));
ApplicationContainer app2 = onoff.Install (n3);
app2.Start (Seconds (1.1));
app2.Stop (Seconds (10.0));

ApplicationContainer sink2 = sink.Install (n0);


sink2.Start (Seconds (1.1));
sink2.Stop (Seconds (10.0));

NS_LOG_INFO ("Configure Tracing.");


//
// Configure tracing of all enqueue, dequeue, and NetDevice receive events.
// Trace output will be sent to the file "csma-bridge-one-hop.tr"
//
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("csma-bridge-one-hop.tr"));

//
// Also configure some tcpdump traces; each interface will be traced.
// The output files will be named:
// csma-bridge-one-hop-<nodeId>-<interfaceId>.pcap
// and can be read by the "tcpdump -r" command (use "-tt" option to
// display timestamps correctly)
//
csma.EnablePcapAll ("csma-bridge-one-hop", false);

//
// Now, do the actual simulation.
//
AnimationInterface anim("csm.xml");
anim.SetConstantPosition(c.Get(0),10.0,30.0);
anim.SetConstantPosition(c.Get(1),20.0,50.0);
anim.SetConstantPosition(c.Get(2),30.0,60.0);
anim.SetConstantPosition(c.Get(3),40.0,80.0);
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}

41
OUTPUT:

Experiment - 5

Aim: To learn about Wifi and Mobile Adhoc topologies with NS3.

1. Test-interface-helper:

#include "ns3/log.h"
#include "ns3/packet.h"
#include "ns3/config.h"
#include "ns3/double.h"
#include "ns3/simulator.h"
#include "ns3/command-line.h"
#include "ns3/yans-wifi-channel.h"
#include "ns3/yans-wifi-phy.h"
#include "ns3/propagation-loss-model.h"
#include "ns3/propagation-delay-model.h"
#include "ns3/nist-error-rate-model.h"
#include "ns3/constant-position-mobility-model.h"

42
#include "ns3/simple-frame-capture-model.h"
#include "ns3/netanim-module.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("test-interference-helper");

bool checkResults = false;


bool expectRxASuccessfull = false;
bool expectRxBSuccessfull = false;

/// InterferenceExperiment
class InterferenceExperiment
{
public:
/// Input atructure
struct Input
{
Input ();
Time interval; ///< interval
double xA; ///< x A
double xB; ///< x B
std::string txModeA; ///< transmit mode A
std::string txModeB; ///< transmit mode B
double txPowerLevelA; ///< transmit power level A
double txPowerLevelB; ///< transmit power level B
uint32_t packetSizeA; ///< packet size A
uint32_t packetSizeB; ///< packet size B
WifiPhyStandard standard; ///< standard
WifiPreamble preamble; ///< preamble
bool captureEnabled; ///< whether physical layer capture is enabled
double captureMargin; ///< margin used for physical layer capture
};

InterferenceExperiment ();
/**
* Run function
* \param input the interference experiment data
*/
void Run (struct InterferenceExperiment::Input input);

private:
/**
* Function triggered when a packet is dropped
* \param packet the packet that was dropped
* \param reason the reason why it was dropped
*/
void PacketDropped (Ptr<const Packet> packet, WifiPhyRxfailureReason reason);

43
/// Send A function
void SendA (void) const;
/// Send B function
void SendB (void) const;
Ptr<YansWifiPhy> m_txA; ///< transmit A function
Ptr<YansWifiPhy> m_txB; ///< transmit B function
struct Input m_input; ///< input
bool m_droppedA; ///< flag to indicate whether packet A has been dropped
bool m_droppedB; ///< flag to indicate whether packet B has been dropped
};

void
InterferenceExperiment::SendA (void) const
{
Ptr<Packet> p = Create<Packet> (m_input.packetSizeA);
WifiTxVector txVector;
txVector.SetTxPowerLevel (0); //only one TX power level
txVector.SetMode (WifiMode (m_input.txModeA));
txVector.SetPreambleType (m_input.preamble);
m_txA->SendPacket (p, txVector);
}

void
InterferenceExperiment::SendB (void) const
{
Ptr<Packet> p = Create<Packet> (m_input.packetSizeB);
WifiTxVector txVector;
txVector.SetTxPowerLevel (0); //only one TX power level
txVector.SetMode (WifiMode (m_input.txModeB));
txVector.SetPreambleType (m_input.preamble);
m_txB->SendPacket (p, txVector);
}

void
InterferenceExperiment::PacketDropped (Ptr<const Packet> packet, WifiPhyRxfailureReason
reason)
{
if (packet->GetUid () == 0)
{
m_droppedA = true;
}
else if (packet->GetUid () == 1)
{
m_droppedB = true;
}
else
{
NS_LOG_ERROR ("Unknown packet!");

44
exit (1);
}
}

InterferenceExperiment::InterferenceExperiment ()
: m_droppedA (false),
m_droppedB (false)
{
}

InterferenceExperiment::Input::Input ()
: interval (MicroSeconds (0)),
xA (-5),
xB (5),
txModeA ("OfdmRate54Mbps"),
txModeB ("OfdmRate54Mbps"),
txPowerLevelA (16.0206),
txPowerLevelB (16.0206),
packetSizeA (1500),
packetSizeB (1500),
standard (WIFI_PHY_STANDARD_80211a),
preamble (WIFI_PREAMBLE_LONG),
captureEnabled (false),
captureMargin (0)
{
}

void
InterferenceExperiment::Run (struct InterferenceExperiment::Input input)
{
m_input = input;

double range = std::max (std::abs (input.xA), input.xB);


Config::SetDefault ("ns3::RangePropagationLossModel::MaxRange", DoubleValue
(range));

Ptr<YansWifiChannel> channel = CreateObject<YansWifiChannel> ();


channel->SetPropagationDelayModel
(CreateObject<ConstantSpeedPropagationDelayModel> ());
Ptr<RangePropagationLossModel> loss = CreateObject<RangePropagationLossModel> ();
channel->SetPropagationLossModel (loss);

Ptr<MobilityModel> posTxA = CreateObject<ConstantPositionMobilityModel> ();


posTxA->SetPosition (Vector (input.xA, 0.0, 0.0));
Ptr<MobilityModel> posTxB = CreateObject<ConstantPositionMobilityModel> ();
posTxB->SetPosition (Vector (input.xB, 0.0, 0.0));
Ptr<MobilityModel> posRx = CreateObject<ConstantPositionMobilityModel> ();
posRx->SetPosition (Vector (0.0, 0.0, 0.0));

45
m_txA = CreateObject<YansWifiPhy> ();
m_txA->SetTxPowerStart (input.txPowerLevelA);
m_txA->SetTxPowerEnd (input.txPowerLevelA);
m_txB = CreateObject<YansWifiPhy> ();
m_txB->SetTxPowerStart (input.txPowerLevelB);
m_txB->SetTxPowerEnd (input.txPowerLevelB);
Ptr<YansWifiPhy> rx = CreateObject<YansWifiPhy> ();

Ptr<ErrorRateModel> error = CreateObject<NistErrorRateModel> ();


m_txA->SetErrorRateModel (error);
m_txB->SetErrorRateModel (error);
rx->SetErrorRateModel (error);
m_txA->SetChannel (channel);
m_txB->SetChannel (channel);
rx->SetChannel (channel);
m_txA->SetMobility (posTxA);
m_txB->SetMobility (posTxB);
rx->SetMobility (posRx);
if (input.captureEnabled)
{
Ptr<SimpleFrameCaptureModel> frameCaptureModel =
CreateObject<SimpleFrameCaptureModel> ();
frameCaptureModel->SetMargin (input.captureMargin);
rx->SetFrameCaptureModel (frameCaptureModel);
}

m_txA->ConfigureStandard (input.standard);
m_txB->ConfigureStandard (input.standard);
rx->ConfigureStandard (input.standard);

rx->TraceConnectWithoutContext ("PhyRxDrop", MakeCallback


(&InterferenceExperiment::PacketDropped, this));

Simulator::Schedule (Seconds (0), &InterferenceExperiment::SendA, this);


Simulator::Schedule (Seconds (0) + input.interval, &InterferenceExperiment::SendB, this);

Simulator::Run ();
Simulator::Destroy ();
m_txB->Dispose ();
m_txA->Dispose ();
rx->Dispose ();

if (checkResults && (m_droppedA == expectRxASuccessfull || m_droppedB ==


expectRxBSuccessfull))
{
NS_LOG_ERROR ("Results are not expected!");
exit (1);

46
}
}

int main (int argc, char *argv[])


{
InterferenceExperiment::Input input;
std::string str_standard = "WIFI_PHY_STANDARD_80211a";
std::string str_preamble = "WIFI_PREAMBLE_LONG";
uint64_t delay = 0; //microseconds
NS_LOG_INFO ("Create nodes.");
NodeContainer c;
c.Create (4);
CommandLine cmd;
cmd.AddValue ("delay", "Delay in microseconds between frame transmission from sender
A and frame transmission from sender B", delay);
cmd.AddValue ("xA", "The position of transmitter A (< 0)", input.xA);
cmd.AddValue ("xB", "The position of transmitter B (> 0)", input.xB);
cmd.AddValue ("packetSizeA", "Packet size in bytes of transmitter A", input.packetSizeA);
cmd.AddValue ("packetSizeB", "Packet size in bytes of transmitter B", input.packetSizeB);
cmd.AddValue ("txPowerA", "TX power level of transmitter A", input.txPowerLevelA);
cmd.AddValue ("txPowerB", "TX power level of transmitter B", input.txPowerLevelB);
cmd.AddValue ("txModeA", "Wifi mode used for payload transmission of sender A",
input.txModeA);
cmd.AddValue ("txModeB", "Wifi mode used for payload transmission of sender B",
input.txModeB);
cmd.AddValue ("standard", "IEEE 802.11 flavor", str_standard);
cmd.AddValue ("preamble", "Type of preamble", str_preamble);
cmd.AddValue ("enableCapture", "Enable/disable physical layer capture",
input.captureEnabled);
cmd.AddValue ("captureMargin", "Margin used for physical layer capture",
input.captureMargin);
cmd.AddValue ("checkResults", "Used to check results at the end of the test",
checkResults);
cmd.AddValue ("expectRxASuccessfull", "Indicate whether packet A is expected to be
successfully received", expectRxASuccessfull);
cmd.AddValue ("expectRxBSuccessfull", "Indicate whether packet B is expected to be
successfully received", expectRxBSuccessfull);
cmd.Parse (argc, argv);

input.interval = MicroSeconds (delay);

if (input.xA >= 0 || input.xB <= 0)


{
std::cout << "Value of xA must be smaller than 0 and value of xB must be bigger than 0!"
<< std::endl;
return 0;
}

47
if (str_standard == "WIFI_PHY_STANDARD_80211a")
{
input.standard = WIFI_PHY_STANDARD_80211a;
}
else if (str_standard == "WIFI_PHY_STANDARD_80211b")
{
input.standard = WIFI_PHY_STANDARD_80211b;
}
else if (str_standard == "WIFI_PHY_STANDARD_80211g")
{
input.standard = WIFI_PHY_STANDARD_80211g;
}
else if (str_standard == "WIFI_PHY_STANDARD_80211n_2_4GHZ")
{
input.standard = WIFI_PHY_STANDARD_80211n_2_4GHZ;
}
else if (str_standard == "WIFI_PHY_STANDARD_80211n_5GHZ")
{
input.standard = WIFI_PHY_STANDARD_80211n_5GHZ;
}
else if (str_standard == "WIFI_PHY_STANDARD_80211ac")
{
input.standard = WIFI_PHY_STANDARD_80211ac;
}

if (str_preamble == "WIFI_PREAMBLE_LONG" && (input.standard ==


WIFI_PHY_STANDARD_80211a || input.standard == WIFI_PHY_STANDARD_80211b ||
input.standard == WIFI_PHY_STANDARD_80211g))
{
input.preamble = WIFI_PREAMBLE_LONG;
}
else if (str_preamble == "WIFI_PREAMBLE_SHORT" && (input.standard ==
WIFI_PHY_STANDARD_80211b || input.standard == WIFI_PHY_STANDARD_80211g))
{
input.preamble = WIFI_PREAMBLE_SHORT;
}
else if (str_preamble == "WIFI_PREAMBLE_HT_MF" && (input.standard ==
WIFI_PHY_STANDARD_80211n_2_4GHZ || input.standard ==
WIFI_PHY_STANDARD_80211n_5GHZ))
{
input.preamble = WIFI_PREAMBLE_HT_MF;
}
else if (str_preamble == "WIFI_PREAMBLE_HT_GF" && (input.standard ==
WIFI_PHY_STANDARD_80211n_2_4GHZ || input.standard ==
WIFI_PHY_STANDARD_80211n_5GHZ))
{
input.preamble = WIFI_PREAMBLE_HT_GF;
}

48
else if (str_preamble == "WIFI_PREAMBLE_VHT_SU" && input.standard ==
WIFI_PHY_STANDARD_80211ac)
{
input.preamble = WIFI_PREAMBLE_VHT_SU;
}
else
{
std::cout << "Preamble does not exist or is not compatible with the selected standard!" <<
std::endl;
return 0;
}
AnimationInterface anim("test-interference-helper.xml");
anim.SetConstantPosition(c.Get(0),10.0,30.0);
anim.SetConstantPosition(c.Get(1),20.0,50.0);
anim.SetConstantPosition(c.Get(2),30.0,60.0);
anim.SetConstantPosition(c.Get(3),40.0,80.0);
NS_LOG_INFO ("Run Simulation.");
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
InterferenceExperiment experiment;
experiment.Run (input);
return 0;
}

OUTPUT:

49
2. WiFi-Manager:

#include "ns3/log.h"
#include "ns3/config.h"
#include "ns3/uinteger.h"
#include "ns3/boolean.h"
#include "ns3/double.h"
#include "ns3/gnuplot.h"
#include "ns3/command-line.h"
#include "ns3/yans-wifi-helper.h"
#include "ns3/ssid.h"
#include "ns3/propagation-loss-model.h"
#include "ns3/propagation-delay-model.h"
#include "ns3/rng-seed-manager.h"
#include "ns3/mobility-helper.h"
#include "ns3/wifi-net-device.h"
#include "ns3/packet-socket-helper.h"
#include "ns3/packet-socket-client.h"
#include "ns3/packet-socket-server.h"
#include "ns3/ht-configuration.h"
#include "ns3/he-configuration.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("WifiManagerExample");

// 290K @ 20 MHz
const double NOISE_DBM_Hz = -174.0;
double noiseDbm = NOISE_DBM_Hz;

double g_intervalBytes = 0;
uint64_t g_intervalRate = 0;

void
PacketRx (Ptr<const Packet> pkt, const Address &addr)
{
NS_LOG_DEBUG ("Received size " << pkt->GetSize ());
g_intervalBytes += pkt->GetSize ();
}

void
RateChange (uint64_t oldVal, uint64_t newVal)
{
NS_LOG_DEBUG ("Change from " << oldVal << " to " << newVal);
g_intervalRate = newVal;
}

/// Step structure

50
struct Step
{
double stepSize; ///< step size in dBm
double stepTime; ///< step size in seconds
};

/// StandardInfo structure


struct StandardInfo
{
StandardInfo ()
{
m_name = "none";
}
/**
* Constructor
*
* \param name reference name
* \param standard wifi phy standard
* \param width channel width
* \param snrLow SNR low
* \param snrHigh SNR high
* \param xMin x minimum
* \param xMax x maximum
* \param yMax y maximum
*/
StandardInfo (std::string name, WifiPhyStandard standard, uint16_t width, double snrLow,
double snrHigh, double xMin, double xMax, double yMax)
: m_name (name),
m_standard (standard),
m_width (width),
m_snrLow (snrLow),
m_snrHigh (snrHigh),
m_xMin (xMin),
m_xMax (xMax),
m_yMax (yMax)
{
}
std::string m_name; ///< name
WifiPhyStandard m_standard; ///< standard
uint16_t m_width; ///< channel width
double m_snrLow; ///< lowest SNR
double m_snrHigh; ///< highest SNR
double m_xMin; ///< X minimum
double m_xMax; ///< X maximum
double m_yMax; ///< Y maximum
};

void

51
ChangeSignalAndReportRate (Ptr<FixedRssLossModel> rssModel, struct Step step, double
rss, Gnuplot2dDataset& rateDataset, Gnuplot2dDataset& actualDataset)
{
NS_LOG_FUNCTION (rssModel << step.stepSize << step.stepTime << rss);
double snr = rss - noiseDbm;
rateDataset.Add (snr, g_intervalRate / 1000000.0);
// Calculate received rate since last interval
double currentRate = ((g_intervalBytes * 8) / step.stepTime) / 1e6; // Mb/s
actualDataset.Add (snr, currentRate);
rssModel->SetRss (rss - step.stepSize);
NS_LOG_INFO ("At time " << Simulator::Now ().As (Time::S) << "; observed rate " <<
currentRate << "; setting new power to " << rss - step.stepSize);
g_intervalBytes = 0;
Simulator::Schedule (Seconds (step.stepTime), &ChangeSignalAndReportRate, rssModel,
step, (rss - step.stepSize), rateDataset, actualDataset);
}

int main (int argc, char *argv[])


{
std::vector <StandardInfo> serverStandards;
std::vector <StandardInfo> clientStandards;
uint32_t steps;
uint32_t rtsThreshold = 999999; // disabled even for large A-MPDU
uint32_t maxAmpduSize = 65535;
double stepSize = 1; // dBm
double stepTime = 1; // seconds
uint32_t packetSize = 1024; // bytes
bool broadcast = 0;
int ap1_x = 0;
int ap1_y = 0;
int sta1_x = 5;
int sta1_y = 0;
uint16_t serverNss = 1;
uint16_t clientNss = 1;
uint16_t serverShortGuardInterval = 800;
uint16_t clientShortGuardInterval = 800;
uint16_t serverChannelWidth = 20;
uint16_t clientChannelWidth = 20;
std::string wifiManager ("Ideal");
std::string standard ("802.11a");
StandardInfo serverSelectedStandard;
StandardInfo clientSelectedStandard;
bool infrastructure = false;
uint32_t maxSlrc = 7;
uint32_t maxSsrc = 7;

CommandLine cmd;

52
cmd.AddValue ("maxSsrc", "The maximum number of retransmission attempts for a RTS
packet", maxSsrc);
cmd.AddValue ("maxSlrc", "The maximum number of retransmission attempts for a DATA
packet", maxSlrc);
cmd.AddValue ("rtsThreshold", "RTS threshold", rtsThreshold);
cmd.AddValue ("maxAmpduSize", "Max A-MPDU size", maxAmpduSize);
cmd.AddValue ("stepSize", "Power between steps (dBm)", stepSize);
cmd.AddValue ("stepTime", "Time on each step (seconds)", stepTime);
cmd.AddValue ("broadcast", "Send broadcast instead of unicast", broadcast);
cmd.AddValue ("serverChannelWidth", "Set channel width of the server (valid only for
802.11n or ac)", serverChannelWidth);
cmd.AddValue ("clientChannelWidth", "Set channel width of the client (valid only for
802.11n or ac)", clientChannelWidth);
cmd.AddValue ("serverNss", "Set nss of the server (valid only for 802.11n or ac)",
serverNss);
cmd.AddValue ("clientNss", "Set nss of the client (valid only for 802.11n or ac)",
clientNss);
cmd.AddValue ("serverShortGuardInterval", "Set short guard interval of the server
(802.11n/ac/ax) in nanoseconds", serverShortGuardInterval);
cmd.AddValue ("clientShortGuardInterval", "Set short guard interval of the client
(802.11n/ac/ax) in nanoseconds", clientShortGuardInterval);
cmd.AddValue ("standard", "Set standard (802.11a, 802.11b, 802.11g, 802.11n-5GHz,
802.11n-2.4GHz, 802.11ac, 802.11-holland, 802.11-10MHz, 802.11-5MHz, 802.11ax-5GHz,
802.11ax-2.4GHz)", standard);
cmd.AddValue ("wifiManager", "Set wifi rate manager (Aarf, Aarfcd, Amrr, Arf, Cara,
Ideal, Minstrel, MinstrelHt, Onoe, Rraa)", wifiManager);
cmd.AddValue ("infrastructure", "Use infrastructure instead of adhoc", infrastructure);
cmd.Parse (argc,argv);

// Print out some explanation of what this program does


std::cout << std::endl << "This program demonstrates and plots the operation of different "
<< std::endl;
std::cout << "Wi-Fi rate controls on different station configurations," << std::endl;
std::cout << "by stepping down the received signal strength across a wide range" <<
std::endl;
std::cout << "and observing the adjustment of the rate." << std::endl;
std::cout << "Run 'wifi-manager-example --PrintHelp' to show program options." <<
std::endl << std::endl;

if (infrastructure == false)
{
NS_ABORT_MSG_IF (serverNss != clientNss, "In ad hoc mode, we assume sender and
receiver are similarly configured");
}

if (standard == "802.11b")
{

53
NS_ABORT_MSG_IF (serverChannelWidth != 22 && serverChannelWidth != 22,
"Invalid channel width for standard " << standard);
NS_ABORT_MSG_IF (serverNss != 1, "Invalid nss for standard " << standard);
NS_ABORT_MSG_IF (clientChannelWidth != 22 && clientChannelWidth != 22,
"Invalid channel width for standard " << standard);
NS_ABORT_MSG_IF (clientNss != 1, "Invalid nss for standard " << standard);
}
else if (standard == "802.11a" || standard == "802.11g")
{
NS_ABORT_MSG_IF (serverChannelWidth != 20, "Invalid channel width for standard "
<< standard);
NS_ABORT_MSG_IF (serverNss != 1, "Invalid nss for standard " << standard);
NS_ABORT_MSG_IF (clientChannelWidth != 20, "Invalid channel width for standard "
<< standard);
NS_ABORT_MSG_IF (clientNss != 1, "Invalid nss for standard " << standard);
}
else if (standard == "802.11n-5GHz" || standard == "802.11n-2.4GHz")
{
NS_ABORT_MSG_IF (serverChannelWidth != 20 && serverChannelWidth != 40,
"Invalid channel width for standard " << standard);
NS_ABORT_MSG_IF (serverNss == 0 || serverNss > 4, "Invalid nss " << serverNss << "
for standard " << standard);
NS_ABORT_MSG_IF (clientChannelWidth != 20 && clientChannelWidth != 40,
"Invalid channel width for standard " << standard);
NS_ABORT_MSG_IF (clientNss == 0 || clientNss > 4, "Invalid nss " << clientNss << "
for standard " << standard);
}
else if (standard == "802.11ac")
{
NS_ABORT_MSG_IF (serverChannelWidth != 20 && serverChannelWidth != 40 &&
serverChannelWidth != 80 && serverChannelWidth != 160, "Invalid channel width for
standard " << standard);
NS_ABORT_MSG_IF (serverNss == 0 || serverNss > 4, "Invalid nss " << serverNss << "
for standard " << standard);
NS_ABORT_MSG_IF (clientChannelWidth != 20 && clientChannelWidth != 40 &&
clientChannelWidth != 80 && clientChannelWidth != 160, "Invalid channel width for
standard " << standard);
NS_ABORT_MSG_IF (clientNss == 0 || clientNss > 4, "Invalid nss " << clientNss << "
for standard " << standard);
}
else if (standard == "802.11ax-5GHz" || standard == "802.11ax-2.4GHz")
{
NS_ABORT_MSG_IF (serverChannelWidth != 20 && serverChannelWidth != 40 &&
serverChannelWidth != 80 && serverChannelWidth != 160, "Invalid channel width for
standard " << standard);
NS_ABORT_MSG_IF (serverNss == 0 || serverNss > 4, "Invalid nss " << serverNss << "
for standard " << standard);

54
NS_ABORT_MSG_IF (clientChannelWidth != 20 && clientChannelWidth != 40 &&
clientChannelWidth != 80 && clientChannelWidth != 160, "Invalid channel width for
standard " << standard);
NS_ABORT_MSG_IF (clientNss == 0 || clientNss > 4, "Invalid nss " << clientNss << "
for standard " << standard);
}

// As channel width increases, scale up plot's yRange value


uint32_t channelRateFactor = std::max (clientChannelWidth, serverChannelWidth) / 20;
channelRateFactor = channelRateFactor * std::max (clientNss, serverNss);

// The first number is channel width, second is minimum SNR, third is maximum
// SNR, fourth and fifth provide xrange axis limits, and sixth the yaxis
// maximum
serverStandards.push_back (StandardInfo ("802.11a", WIFI_PHY_STANDARD_80211a,
20, 3, 27, 0, 30, 60));
serverStandards.push_back (StandardInfo ("802.11b", WIFI_PHY_STANDARD_80211b,
22, -5, 11, -6, 15, 15));
serverStandards.push_back (StandardInfo ("802.11g", WIFI_PHY_STANDARD_80211g,
20, -5, 27, -6, 30, 60));
serverStandards.push_back (StandardInfo ("802.11n-5GHz",
WIFI_PHY_STANDARD_80211n_5GHZ, serverChannelWidth, 3, 30, 0, 35, 80 *
channelRateFactor));
serverStandards.push_back (StandardInfo ("802.11n-2.4GHz",
WIFI_PHY_STANDARD_80211n_2_4GHZ, serverChannelWidth, 3, 30, 0, 35, 80 *
channelRateFactor));
serverStandards.push_back (StandardInfo ("802.11ac", WIFI_PHY_STANDARD_80211ac,
serverChannelWidth, 5, 50, 0, 55, 120 * channelRateFactor));
serverStandards.push_back (StandardInfo ("802.11-holland",
WIFI_PHY_STANDARD_holland, 20, 3, 27, 0, 30, 60));
serverStandards.push_back (StandardInfo ("802.11-10MHz",
WIFI_PHY_STANDARD_80211_10MHZ, 10, 3, 27, 0, 30, 60));
serverStandards.push_back (StandardInfo ("802.11-5MHz",
WIFI_PHY_STANDARD_80211_5MHZ, 5, 3, 27, 0, 30, 60));
serverStandards.push_back (StandardInfo ("802.11ax-5GHz",
WIFI_PHY_STANDARD_80211ax_5GHZ, serverChannelWidth, 5, 55, 0, 60, 120 *
channelRateFactor));
serverStandards.push_back (StandardInfo ("802.11ax-2.4GHz",
WIFI_PHY_STANDARD_80211ax_2_4GHZ, serverChannelWidth, 5, 55, 0, 60, 120 *
channelRateFactor));

clientStandards.push_back (StandardInfo ("802.11a", WIFI_PHY_STANDARD_80211a,


20, 3, 27, 0, 30, 60));
clientStandards.push_back (StandardInfo ("802.11b", WIFI_PHY_STANDARD_80211b,
22, -5, 11, -6, 15, 15));
clientStandards.push_back (StandardInfo ("802.11g", WIFI_PHY_STANDARD_80211g,
20, -5, 27, -6, 30, 60));

55
clientStandards.push_back (StandardInfo ("802.11n-5GHz",
WIFI_PHY_STANDARD_80211n_5GHZ, clientChannelWidth, 3, 30, 0, 35, 80 *
channelRateFactor));
clientStandards.push_back (StandardInfo ("802.11n-2.4GHz",
WIFI_PHY_STANDARD_80211n_2_4GHZ, clientChannelWidth, 3, 30, 0, 35, 80 *
channelRateFactor));
clientStandards.push_back (StandardInfo ("802.11ac", WIFI_PHY_STANDARD_80211ac,
clientChannelWidth, 5, 50, 0, 55, 120 * channelRateFactor));
clientStandards.push_back (StandardInfo ("802.11-holland",
WIFI_PHY_STANDARD_holland, 20, 3, 27, 0, 30, 60));
clientStandards.push_back (StandardInfo ("802.11-10MHz",
WIFI_PHY_STANDARD_80211_10MHZ, 10, 3, 27, 0, 30, 60));
clientStandards.push_back (StandardInfo ("802.11-5MHz",
WIFI_PHY_STANDARD_80211_5MHZ, 5, 3, 27, 0, 30, 60));
clientStandards.push_back (StandardInfo ("802.11ax-5GHz",
WIFI_PHY_STANDARD_80211ax_5GHZ, clientChannelWidth, 5, 55, 0, 60, 160 *
channelRateFactor));
clientStandards.push_back (StandardInfo ("802.11ax-2.4GHz",
WIFI_PHY_STANDARD_80211ax_2_4GHZ, clientChannelWidth, 5, 55, 0, 60, 160 *
channelRateFactor));

for (std::vector<StandardInfo>::size_type i = 0; i != serverStandards.size (); i++)


{
if (standard == serverStandards[i].m_name)
{
serverSelectedStandard = serverStandards[i];
}
}
for (std::vector<StandardInfo>::size_type i = 0; i != clientStandards.size (); i++)
{
if (standard == clientStandards[i].m_name)
{
clientSelectedStandard = clientStandards[i];
}
}

NS_ABORT_MSG_IF (serverSelectedStandard.m_name == "none", "Standard " <<


standard << " not found");
NS_ABORT_MSG_IF (clientSelectedStandard.m_name == "none", "Standard " <<
standard << " not found");
std::cout << "Testing " << serverSelectedStandard.m_name << " with " << wifiManager <<
" ..." << std::endl;
NS_ABORT_MSG_IF (clientSelectedStandard.m_snrLow >=
clientSelectedStandard.m_snrHigh, "SNR values in wrong order");
steps = static_cast<uint32_t> (std::abs (static_cast<double>
(clientSelectedStandard.m_snrHigh - clientSelectedStandard.m_snrLow ) / stepSize) + 1);
NS_LOG_DEBUG ("Using " << steps << " steps for SNR range " <<
clientSelectedStandard.m_snrLow << ":" << clientSelectedStandard.m_snrHigh);

56
Ptr<Node> clientNode = CreateObject<Node> ();
Ptr<Node> serverNode = CreateObject<Node> ();

std::string plotName = "wifi-manager-example-";


std::string dataName = "wifi-manager-example-";
plotName += wifiManager;
dataName += wifiManager;
plotName += "-";
dataName += "-";
plotName += standard;
dataName += standard;
if (standard == "802.11n-5GHz"
|| standard == "802.11n-2.4GHz"
|| standard == "802.11ac"
|| standard == "802.11ax-5GHz"
|| standard == "802.11ax-2.4GHz")
{
plotName += "-server_";
dataName += "-server_";
std::ostringstream oss;
oss << serverChannelWidth << "MHz_" << serverShortGuardInterval << "ns_" <<
serverNss << "SS";
plotName += oss.str ();
dataName += oss.str ();
plotName += "-client_";
dataName += "-client_";
oss.str ("");
oss << clientChannelWidth << "MHz_" << clientShortGuardInterval << "ns_" <<
clientNss << "SS";
plotName += oss.str ();
dataName += oss.str ();
}
plotName += ".eps";
dataName += ".plt";
std::ofstream outfile (dataName.c_str ());
Gnuplot gnuplot = Gnuplot (plotName);

Config::SetDefault ("ns3::WifiRemoteStationManager::MaxSlrc", UintegerValue


(maxSlrc));
Config::SetDefault ("ns3::WifiRemoteStationManager::MaxSsrc", UintegerValue
(maxSsrc));
Config::SetDefault ("ns3::MinstrelWifiManager::PrintStats", BooleanValue (true));
Config::SetDefault ("ns3::MinstrelWifiManager::PrintSamples", BooleanValue (true));
Config::SetDefault ("ns3::MinstrelHtWifiManager::PrintStats", BooleanValue (true));

WifiHelper wifi;
wifi.SetStandard (serverSelectedStandard.m_standard);
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();

57
Ptr<YansWifiChannel> wifiChannel = CreateObject<YansWifiChannel> ();
Ptr<ConstantSpeedPropagationDelayModel> delayModel =
CreateObject<ConstantSpeedPropagationDelayModel> ();
wifiChannel->SetPropagationDelayModel (delayModel);
Ptr<FixedRssLossModel> rssLossModel = CreateObject<FixedRssLossModel> ();
wifiChannel->SetPropagationLossModel (rssLossModel);
wifiPhy.SetChannel (wifiChannel);

wifi.SetRemoteStationManager ("ns3::" + wifiManager + "WifiManager",


"RtsCtsThreshold", UintegerValue (rtsThreshold));

NetDeviceContainer serverDevice;
NetDeviceContainer clientDevice;

WifiMacHelper wifiMac;
if (infrastructure)
{
Ssid ssid = Ssid ("ns-3-ssid");
wifiMac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid));
serverDevice = wifi.Install (wifiPhy, wifiMac, serverNode);
wifiMac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid));
clientDevice = wifi.Install (wifiPhy, wifiMac, clientNode);
}
else
{
wifiMac.SetType ("ns3::AdhocWifiMac");
serverDevice = wifi.Install (wifiPhy, wifiMac, serverNode);
clientDevice = wifi.Install (wifiPhy, wifiMac, clientNode);
}

RngSeedManager::SetSeed (1);
RngSeedManager::SetRun (2);
wifi.AssignStreams (serverDevice, 100);
wifi.AssignStreams (clientDevice, 100);

Config::Set ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/BE_MaxAmpduSize",
UintegerValue (maxAmpduSize));

Config::ConnectWithoutContext
("/NodeList/0/DeviceList/*/$ns3::WifiNetDevice/RemoteStationManager/$ns3::" +
wifiManager + "WifiManager/Rate", MakeCallback (&RateChange));

// Configure the mobility.


MobilityHelper mobility;
Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();

58
//Initial position of AP and STA
positionAlloc->Add (Vector (ap1_x, ap1_y, 0.0));
NS_LOG_INFO ("Setting initial AP position to " << Vector (ap1_x, ap1_y, 0.0));
positionAlloc->Add (Vector (sta1_x, sta1_y, 0.0));
NS_LOG_INFO ("Setting initial STA position to " << Vector (sta1_x, sta1_y, 0.0));
mobility.SetPositionAllocator (positionAlloc);
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (clientNode);
mobility.Install (serverNode);

Gnuplot2dDataset rateDataset (clientSelectedStandard.m_name + std::string ("-rate


selected"));
Gnuplot2dDataset actualDataset (clientSelectedStandard.m_name + std::string ("-
observed"));
struct Step step;
step.stepSize = stepSize;
step.stepTime = stepTime;

// Perform post-install configuration from defaults for channel width,


// guard interval, and nss, if necessary
// Obtain pointer to the WifiPhy
Ptr<NetDevice> ndClient = clientDevice.Get (0);
Ptr<NetDevice> ndServer = serverDevice.Get (0);
Ptr<WifiNetDevice> wndClient = ndClient->GetObject<WifiNetDevice> ();
Ptr<WifiNetDevice> wndServer = ndServer->GetObject<WifiNetDevice> ();
Ptr<WifiPhy> wifiPhyPtrClient = wndClient->GetPhy ();
Ptr<WifiPhy> wifiPhyPtrServer = wndServer->GetPhy ();
uint8_t t_clientNss = static_cast<uint8_t> (clientNss);
uint8_t t_serverNss = static_cast<uint8_t> (serverNss);
wifiPhyPtrClient->SetNumberOfAntennas (t_clientNss);
wifiPhyPtrClient->SetMaxSupportedTxSpatialStreams (t_clientNss);
wifiPhyPtrClient->SetMaxSupportedRxSpatialStreams (t_clientNss);
wifiPhyPtrServer->SetNumberOfAntennas (t_serverNss);
wifiPhyPtrServer->SetMaxSupportedTxSpatialStreams (t_serverNss);
wifiPhyPtrServer->SetMaxSupportedRxSpatialStreams (t_serverNss);
// Only set the channel width and guard interval for HT and VHT modes
if (serverSelectedStandard.m_name == "802.11n-5GHz"
|| serverSelectedStandard.m_name == "802.11n-2.4GHz"
|| serverSelectedStandard.m_name == "802.11ac")
{
wifiPhyPtrServer->SetChannelWidth (serverSelectedStandard.m_width);
wifiPhyPtrClient->SetChannelWidth (clientSelectedStandard.m_width);
Ptr<HtConfiguration> clientHtConfiguration = wndClient->GetHtConfiguration ();
clientHtConfiguration->SetShortGuardIntervalSupported (clientShortGuardInterval ==
400);
Ptr<HtConfiguration> serverHtConfiguration = wndServer->GetHtConfiguration ();
serverHtConfiguration->SetShortGuardIntervalSupported (serverShortGuardInterval ==
400);

59
}
else if (serverSelectedStandard.m_name == "802.11ax-5GHz"
|| serverSelectedStandard.m_name == "802.11ax-2.4GHz")
{
wifiPhyPtrServer->SetChannelWidth (serverSelectedStandard.m_width);
wifiPhyPtrClient->SetChannelWidth (clientSelectedStandard.m_width);
wndServer->GetHeConfiguration ()->SetGuardInterval (NanoSeconds
(clientShortGuardInterval));
wndClient->GetHeConfiguration ()->SetGuardInterval (NanoSeconds
(clientShortGuardInterval));
}
NS_LOG_DEBUG ("Channel width " << wifiPhyPtrClient->GetChannelWidth () << "
noiseDbm " << noiseDbm);
NS_LOG_DEBUG ("NSS " << wifiPhyPtrClient->GetMaxSupportedTxSpatialStreams ());

// Configure signal and noise, and schedule first iteration


noiseDbm += 10 * log10 (clientSelectedStandard.m_width * 1000000);
double rssCurrent = (clientSelectedStandard.m_snrHigh + noiseDbm);
rssLossModel->SetRss (rssCurrent);
NS_LOG_INFO ("Setting initial Rss to " << rssCurrent);
//Move the STA by stepsSize meters every stepTime seconds
Simulator::Schedule (Seconds (0.5 + stepTime), &ChangeSignalAndReportRate,
rssLossModel, step, rssCurrent, rateDataset, actualDataset);

PacketSocketHelper packetSocketHelper;
packetSocketHelper.Install (serverNode);
packetSocketHelper.Install (clientNode);

PacketSocketAddress socketAddr;
socketAddr.SetSingleDevice (serverDevice.Get (0)->GetIfIndex ());
if (broadcast)
{
socketAddr.SetPhysicalAddress (serverDevice.Get (0)->GetBroadcast ());
}
else
{
socketAddr.SetPhysicalAddress (serverDevice.Get (0)->GetAddress ());
}
// Arbitrary protocol type.
// Note: PacketSocket doesn't have any L4 multiplexing or demultiplexing
// The only mux/demux is based on the protocol field
socketAddr.SetProtocol (1);

Ptr<PacketSocketClient> client = CreateObject<PacketSocketClient> ();


client->SetRemote (socketAddr);
client->SetStartTime (Seconds (0.5)); // allow simulation warmup
client->SetAttribute ("MaxPackets", UintegerValue (0)); // unlimited
client->SetAttribute ("PacketSize", UintegerValue (packetSize));

60
// Set a maximum rate 10% above the yMax specified for the selected standard
double rate = clientSelectedStandard.m_yMax * 1e6 * 1.10;
double clientInterval = static_cast<double> (packetSize) * 8 / rate;
NS_LOG_DEBUG ("Setting interval to " << clientInterval << " sec for rate of " << rate <<
" bits/sec");

client->SetAttribute ("Interval", TimeValue (Seconds (clientInterval)));


clientNode->AddApplication (client);

Ptr<PacketSocketServer> server = CreateObject<PacketSocketServer> ();


server->SetLocal (socketAddr);
server->TraceConnectWithoutContext ("Rx", MakeCallback (&PacketRx));
serverNode->AddApplication (server);

Simulator::Stop (Seconds ((steps + 1) * stepTime));


Simulator::Run ();
Simulator::Destroy ();

gnuplot.AddDataset (rateDataset);
gnuplot.AddDataset (actualDataset);

std::ostringstream xMinStr, xMaxStr, yMaxStr;


std::string xRangeStr ("set xrange [");
xMinStr << clientSelectedStandard.m_xMin;
xRangeStr.append (xMinStr.str ());
xRangeStr.append (":");
xMaxStr << clientSelectedStandard.m_xMax;
xRangeStr.append (xMaxStr.str ());
xRangeStr.append ("]");
std::string yRangeStr ("set yrange [0:");
yMaxStr << clientSelectedStandard.m_yMax;
yRangeStr.append (yMaxStr.str ());
yRangeStr.append ("]");

std::string title ("Results for ");


title.append (standard);
title.append (" with ");
title.append (wifiManager);
title.append ("\\n");
if (standard == "802.11n-5GHz"
|| standard == "802.11n-2.4GHz"
|| standard == "802.11ac"
|| standard == "802.11n-5GHz"
|| standard == "802.11ax-2.4GHz")
{
std::ostringstream serverGiStrStr;
std::ostringstream serverWidthStrStr;

61
std::ostringstream serverNssStrStr;
title.append ("server: width=");
serverWidthStrStr << serverSelectedStandard.m_width;
title.append (serverWidthStrStr.str ());
title.append ("MHz");
title.append (" GI=");
serverGiStrStr << serverShortGuardInterval;
title.append (serverGiStrStr.str ());
title.append ("ns");
title.append (" nss=");
serverNssStrStr << serverNss;
title.append (serverNssStrStr.str ());
title.append ("\\n");
std::ostringstream clientGiStrStr;
std::ostringstream clientWidthStrStr;
std::ostringstream clientNssStrStr;
title.append ("client: width=");
clientWidthStrStr << clientSelectedStandard.m_width;
title.append (clientWidthStrStr.str ());
title.append ("MHz");
title.append (" GI=");
clientGiStrStr << clientShortGuardInterval;
title.append (clientGiStrStr.str ());
title.append ("ns");
title.append (" nss=");
clientNssStrStr << clientNss;
title.append (clientNssStrStr.str ());
}
gnuplot.SetTerminal ("postscript eps color enh \"Times-BoldItalic\"");
gnuplot.SetLegend ("SNR (dB)", "Rate (Mb/s)");
gnuplot.SetTitle (title);
gnuplot.SetExtra (xRangeStr);
gnuplot.AppendExtra (yRangeStr);
gnuplot.AppendExtra ("set key top left");
gnuplot.GenerateOutput (outfile);
outfile.close ();

return 0;
}

OUTPUT:

62
3. Wireless-Animation:
#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/csma-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/mobility-module.h"
#include "ns3/internet-module.h"
#include "ns3/netanim-module.h"
#include "ns3/basic-energy-source.h"
#include "ns3/simple-device-energy-model.h"
#include "ns3/yans-wifi-helper.h"
#include "ns3/ssid.h"
#include "ns3/wifi-radio-energy-model.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("WirelessAnimationExample");

int
main (int argc, char *argv[])
{
uint32_t nWifi = 20;
CommandLine cmd;
cmd.AddValue ("nWifi", "Number of wifi STA devices", nWifi);

cmd.Parse (argc,argv);
NodeContainer allNodes;
NodeContainer wifiStaNodes;
wifiStaNodes.Create (nWifi);

63
allNodes.Add (wifiStaNodes);
NodeContainer wifiApNode ;
wifiApNode.Create (1);
allNodes.Add (wifiApNode);

YansWifiChannelHelper channel = YansWifiChannelHelper::Default ();


YansWifiPhyHelper phy = YansWifiPhyHelper::Default ();
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);

NodeContainer p2pNodes;
p2pNodes.Add (wifiApNode);
p2pNodes.Create (1);
allNodes.Add (p2pNodes.Get (1));

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 (1);
allNodes.Add (csmaNodes.Get (1));

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

NetDeviceContainer csmaDevices;

64
csmaDevices = csma.Install (csmaNodes);

// Mobility

MobilityHelper mobility;
mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
"MinX", DoubleValue (10.0),
"MinY", DoubleValue (10.0),
"DeltaX", DoubleValue (5.0),
"DeltaY", DoubleValue (2.0),
"GridWidth", UintegerValue (5),
"LayoutType", StringValue ("RowFirst"));
mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel",
"Bounds", RectangleValue (Rectangle (-50, 50, -25, 50)));
mobility.Install (wifiStaNodes);
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (wifiApNode);
AnimationInterface::SetConstantPosition (p2pNodes.Get (1), 10, 30);
AnimationInterface::SetConstantPosition (csmaNodes.Get (1), 10, 33);

Ptr<BasicEnergySource> energySource = CreateObject<BasicEnergySource>();


Ptr<WifiRadioEnergyModel> energyModel = CreateObject<WifiRadioEnergyModel>();
/
energySource->SetInitialEnergy (300);
energyModel->SetEnergySource (energySource);
energySource->AppendDeviceEnergyModel (energyModel);

wifiApNode.Get (0)->AggregateObject (energySource);

InternetStackHelper stack;
stack.Install (allNodes);

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);
address.SetBase ("10.1.3.0", "255.255.255.0");
Ipv4InterfaceContainer staInterfaces;
staInterfaces = address.Assign (staDevices);
Ipv4InterfaceContainer apInterface;
apInterface = address.Assign (apDevices);

UdpEchoServerHelper echoServer (9);


ApplicationContainer serverApps = echoServer.Install (csmaNodes.Get (1));
serverApps.Start (Seconds (1.0));

65
serverApps.Stop (Seconds (15.0));
UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (1), 9);
echoClient.SetAttribute ("MaxPackets", UintegerValue (10));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.)));
echoClient.SetAttribute ("PacketSize", UintegerValue (1024));
ApplicationContainer clientApps = echoClient.Install (wifiStaNodes);
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (15.0));

Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
Simulator::Stop (Seconds (15.0));

AnimationInterface anim ("wireless-animation.xml");


for (uint32_t i = 0; i < wifiStaNodes.GetN (); ++i)
{
anim.UpdateNodeDescription (wifiStaNodes.Get (i), "STA");
anim.UpdateNodeColor (wifiStaNodes.Get (i), 255, 0, 0);
}
for (uint32_t i = 0; i < wifiApNode.GetN (); ++i)
{
anim.UpdateNodeDescription (wifiApNode.Get (i), "AP");
anim.UpdateNodeColor (wifiApNode.Get (i), 0, 255, 0);
}
for (uint32_t i = 0; i < csmaNodes.GetN (); ++i)
{
anim.UpdateNodeDescription (csmaNodes.Get (i), "CSMA");
anim.UpdateNodeColor (csmaNodes.Get (i), 0, 0, 255);
}

anim.EnablePacketMetadata ();
anim.EnableIpv4RouteTracking ("routingtable-wireless.xml", Seconds (0), Seconds (5),
Seconds (0.25));
anim.EnableWifiMacCounters (Seconds (0), Seconds (10));
anim.EnableWifiPhyCounters (Seconds (0), Seconds (10));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}

OUTPUT:

66
4. Adhoc- Aodv:

#include <iostream>
#include <cmath>
#include "ns3/aodv-module.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/v4ping-helper.h"
#include "ns3/yans-wifi-helper.h"

using namespace ns3;

/**
* \ingroup aodv-examples
* \ingroup examples
* \brief Test script.
*
* This script creates 1-dimensional grid topology and then ping last node from the first one:
*
* [10.0.0.1] <-- step --> [10.0.0.2] <-- step --> [10.0.0.3] <-- step --> [10.0.0.4]
*
* ping 10.0.0.4
*
* When 1/3 of simulation time has elapsed, one of the nodes is moved out of
* range, thereby breaking the topology. By default, this will result in
* only 34 of 100 pings being received. If the step size is reduced
* to cover the gap, then all pings can be received.

67
*/
class AodvExample
{
public:
AodvExample ();
/**
* \brief Configure script parameters
* \param argc is the command line argument count
* \param argv is the command line arguments
* \return true on successful configuration
*/
bool Configure (int argc, char **argv);
/// Run simulation
void Run ();
/**
* Report results
* \param os the output stream
*/
void Report (std::ostream & os);

private:

// parameters
/// Number of nodes
uint32_t size;
/// Distance between nodes, meters
double step;
/// Simulation time, seconds
double totalTime;
/// Write per-device PCAP traces if true
bool pcap;
/// Print routes if true
bool printRoutes;

// network
/// nodes used in the example
NodeContainer nodes;
/// devices used in the example
NetDeviceContainer devices;
/// interfaces used in the example
Ipv4InterfaceContainer interfaces;

private:
/// Create the nodes
void CreateNodes ();
/// Create the devices
void CreateDevices ();
/// Create the network

68
void InstallInternetStack ();
/// Create the simulation applications
void InstallApplications ();
};

int main (int argc, char **argv)


{
AodvExample test;
if (!test.Configure (argc, argv))
NS_FATAL_ERROR ("Configuration failed. Aborted.");

test.Run ();
test.Report (std::cout);
return 0;
}

AodvExample::AodvExample () :
size (10),
step (50),
totalTime (100),
pcap (true),
printRoutes (true)
{
}

bool
AodvExample::Configure (int argc, char **argv)
{
// Enable AODV logs by default. Comment this if too noisy
// LogComponentEnable("AodvRoutingProtocol", LOG_LEVEL_ALL);

SeedManager::SetSeed (12345);
CommandLine cmd;

cmd.AddValue ("pcap", "Write PCAP traces.", pcap);


cmd.AddValue ("printRoutes", "Print routing table dumps.", printRoutes);
cmd.AddValue ("size", "Number of nodes.", size);
cmd.AddValue ("time", "Simulation time, s.", totalTime);
cmd.AddValue ("step", "Grid step, m", step);

cmd.Parse (argc, argv);


return true;
}

void
AodvExample::Run ()
{

69
// Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", UintegerValue
(1)); // enable rts cts all the time.
CreateNodes ();
CreateDevices ();
InstallInternetStack ();
InstallApplications ();

std::cout << "Starting simulation for " << totalTime << " s ...\n";

Simulator::Stop (Seconds (totalTime));


Simulator::Run ();
Simulator::Destroy ();
}

void
AodvExample::Report (std::ostream &)
{
}

void
AodvExample::CreateNodes ()
{
std::cout << "Creating " << (unsigned)size << " nodes " << step << " m apart.\n";
nodes.Create (size);
// Name nodes
for (uint32_t i = 0; i < size; ++i)
{
std::ostringstream os;
os << "node-" << i;
Names::Add (os.str (), nodes.Get (i));
}
// Create static grid
MobilityHelper mobility;
mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
"MinX", DoubleValue (0.0),
"MinY", DoubleValue (0.0),
"DeltaX", DoubleValue (step),
"DeltaY", DoubleValue (0),
"GridWidth", UintegerValue (size),
"LayoutType", StringValue ("RowFirst"));
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (nodes);
}

void
AodvExample::CreateDevices ()
{
WifiMacHelper wifiMac;

70
wifiMac.SetType ("ns3::AdhocWifiMac");
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
wifiPhy.SetChannel (wifiChannel.Create ());
WifiHelper wifi;
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode",
StringValue ("OfdmRate6Mbps"), "RtsCtsThreshold", UintegerValue (0));
devices = wifi.Install (wifiPhy, wifiMac, nodes);

if (pcap)
{
wifiPhy.EnablePcapAll (std::string ("aodv"));
}
}

void
AodvExample::InstallInternetStack ()
{
AodvHelper aodv;
// you can configure AODV attributes here using aodv.Set(name, value)
InternetStackHelper stack;
stack.SetRoutingHelper (aodv); // has effect on the next Install ()
stack.Install (nodes);
Ipv4AddressHelper address;
address.SetBase ("10.0.0.0", "255.0.0.0");
interfaces = address.Assign (devices);
if (printRoutes)
{
Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper>
("aodv.routes", std::ios::out);
aodv.PrintRoutingTableAllAt (Seconds (8), routingStream);
}
}
void
AodvExample::InstallApplications ()
{
V4PingHelper ping (interfaces.GetAddress (size - 1));
ping.SetAttribute ("Verbose", BooleanValue (true));

ApplicationContainer p = ping.Install (nodes.Get (0));


p.Start (Seconds (0));
p.Stop (Seconds (totalTime) - Seconds (0.001));
// move node away
Ptr<Node> node = nodes.Get (size/2);
Ptr<MobilityModel> mob = node->GetObject<MobilityModel> ();
Simulator::Schedule (Seconds (totalTime/3), &MobilityModel::SetPosition, mob, Vector
(1e5, 1e5, 1e5));
}

71
OUTPUT:

Experiment - 6

Aim: To introduce Socket Programming in TCP and UDP.

1. SERVER-TCP:
import socket
# Create and bind the server socket
s = socket.socket()
s.bind(('localhost', 9999))
s.listen(1)
print("Server is listening...")
# Accept a connection

72
conn, addr = s.accept()
print(f"Connected by {addr}")
# Receive data from the client
name = conn.recv(1024).decode('utf-8')
print(f"Received name: {name}")
# Send a response back to the client
response = f"Hello, {name}!"
conn.send(bytes(response, 'utf-8'))
# Close the connection
conn.close()
s.close()

output:

2. CLIENT_TCP:

import socket

# Create a socket object


c = socket.socket()

# Connect to the server on localhost and port 9999


c.connect(('localhost', 9999))

# Prompt the user to enter their name


name = input("Enter your name: ")

# Send the name to the server


c.send(bytes(name, 'utf-8'))

# Receive the response from the server and print it

73
response = c.recv(1024).decode('utf-8')
print(response)

# Close the connection


c.close()

OUTPUT:

3. SERVER_UDP:

import socket

def udp_server():
# Define server address and port
server_address = ('localhost', 12345)

# Create a UDP socket


sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Bind the socket to the address


sock.bind(server_address)

print(f"Server listening on {server_address}")

while True:
# Receive message from client
message, client_address = sock.recvfrom(4096)
print(f"Received message from {client_address}: {message.decode()}")

# Send a response back to the client


response = f"Message received: {message.decode()}"
sock.sendto(response.encode(), client_address)

if __name__ == "__main__":
udp_server()

74
OUTPUT:

4. CLIENT_UDP:
import socket

def udp_client():
# Define server address and port
server_address = ('localhost', 12345)

# Create a UDP socket


sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

try:
# Send a message to the server
message = "Hello, UDP Server!"
sock.sendto(message.encode(), server_address)

# Receive a response from the server


response, _ = sock.recvfrom(4096)
print(f"Received response from server: {response.decode()}")

finally:
# Close the socket
sock.close()

if __name__ == "__main__":
udp_client()

OUTPUT:

75
Experiment-7

Aim: Observations of Transmission Control Protocol(TCP)Connection states, FLags and


Flow control.

Transmission Control Protocol (TCP) Connection States:


TCP connection states describe the stages a TCP connection goes through during its lifetime.
The following is a breakdown of the common states in a TCP connection:
1. LISTEN:
A server is waiting for a connection request from any remote TCP endpoint.
2. SYN-SENT:
A client has sent a SYN (synchronize) request to initiate a connection and is
waiting for a matching SYN-ACK from the server.
3. SYN-RECEIVED:
The server has received a SYN from a client and has sent a SYN-ACK in
return. The connection is halfway open, waiting for the client&#39;s ACK.
4. ESTABLISHED:
The connection is fully open, and both sides can send and receive data. This is
the normal data transfer state.
5. FIN-WAIT-1:

76
The client or server has sent a FIN to terminate the connection and is waiting
for an acknowledgment from the other side.
6. FIN-WAIT-2:
After receiving the acknowledgment for the FIN, the initiator is waiting for the
other side to send a FIN.
7. CLOSE-WAIT:
The side that received the first FIN is waiting for the application to close the
connection.
8. LAST-ACK:
The side that received the FIN has sent its own FIN and is waiting for the final
acknowledgment.
9. CLOSING:
Both sides have sent FINs but neither has received the acknowledgment, a rare
state.
10. TIME-WAIT:
After both FINs are exchanged and acknowledged, the connection remains in
this state for a period (2 * Maximum Segment Lifetime, or MSL) to ensure all
packets have been flushed.
11. CLOSED:
The connection is fully terminated and no further communication is possible.

TCP Flags:
TCP flags control the connection setup, data transfer, and connection teardown. Common
flags include:
1. SYN (Synchronize):
o Initiates a connection by synchronizing sequence numbers between sender and
receiver.

2. ACK (Acknowledgment): Acknowledges receipt of data or other control information.


3. FIN (Finish): Requests to terminate the connection gracefully.
4. RST (Reset): Abruptly terminates the connection.
5. PSH (Push):Forces the immediate delivery of data to the application layer.
6. URG (Urgent): Indicates that the data following the urgent pointer is of high priority and
should be processed immediately.

TCP Flow Control:


Flow control ensures that a sender does not overwhelm a receiver with more data than it can
handle. TCP uses a sliding window mechanism for flow control:
1. Sliding Window: The sender can only send a certain number of bytes, defined by the
window size, before waiting for an acknowledgment from the receiver.
The receiver advertises its window size, which indicates how much data it can
accept at a time.
2. Window Size: If the receiver’s buffer is full, it may advertise a window size of zero,
causing the sender to pause until more buffer space is available.
3. Acknowledgment (ACK): The receiver sends ACKs to confirm received data and to
update the window size for the sender, allowing more data to be transmitted. Flow control
helps maintain a balanced data transfer rate and prevents buffer overflow in the
receiver.

77
FLAG.PY

import socket
from scapy.all import sniff, TCP
from scapy.layers.inet import IP

# Function to simulate TCP connection establishment and termination


def create_tcp_connection(server_ip, server_port):
# Creating a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
print("Attempting to connect to the server...")
# Initiating a connection to the server
client_socket.connect((server_ip, server_port))
print(f"Connected to {server_ip}:{server_port}")

# Sending a simple HTTP GET request (for example purposes)


request = "GET / HTTP/1.1\r\nHost: {}\r\n\r\n".format(server_ip)
client_socket.send(request.encode())
response = client_socket.recv(4096)
print("Received Response:\n", response.decode())

# Closing the connection


client_socket.close()
print("Connection closed")

except Exception as e:
print(f"Error occurred: {e}")

# Function to capture TCP packets and observe flags and flow control
def capture_tcp_packets(interface):
print(f"Sniffing on interface {interface} for TCP packets...")

# Sniff function captures TCP packets and processes them in the callback
sniff(iface=interface, filter="tcp", prn=analyze_packet, store=False)

# Function to analyze captured packets for TCP flags and states


def analyze_packet(packet):
if packet.haslayer(TCP):
tcp_layer = packet.getlayer(TCP)
ip_layer = packet.getlayer(IP)

src_ip = ip_layer.src
dst_ip = ip_layer.dst
src_port = tcp_layer.sport
dst_port = tcp_layer.dport
flags = tcp_layer.flags

print(f"\n[+] Captured TCP Packet: {src_ip}:{src_port} -> {dst_ip}:{dst_port}")


print(f" Flags: {flags}")
print(f" Sequence Number: {tcp_layer.seq}")

78
print(f" Acknowledgment Number: {tcp_layer.ack}")
print(f" Window Size: {tcp_layer.window}")

# Analyzing flags for states


if flags == "S":
print(" State: SYN (Connection Request)")
elif flags == "SA":
print(" State: SYN-ACK (Connection Acknowledgment)")
elif flags == "F":
print(" State: FIN (Connection Termination)")
elif flags == "R":
print(" State: RST (Connection Reset)")
elif flags == "P":
print(" State: PSH (Data Push)")
elif flags == "A":
print(" State: ACK (Acknowledgment)")
elif flags == "FA":
print(" State: FIN-ACK (Connection Close Acknowledgment)")

# Main function to run the TCP connection and packet capture


if __name__ == "__main__":
# Target server (use your own server or a public one)
server_ip = "93.184.216.34" # Example IP (example.com)
server_port = 80 # HTTP Port

# Run TCP connection simulation


create_tcp_connection(server_ip, server_port)

# Capture packets (Replace with your network interface name, like 'eth0' or 'lo' for local)
capture_tcp_packets(interface="eth0") # Modify interface as needed

OUTPUT:

79
Experiment-8

80
Aim: To learn Transmission Control Protocol(TCP)Flow Control, Error Control, and
Congestion.

1. Flow Control: Manages the amount of data the sender can transmit to prevent
overwhelming the receiver. It uses a sliding window that adjusts dynamically based
on the receiver’s capacity.
2. Error Control: Ensures reliable data delivery by using checksums,
acknowledgments, sequence numbers, and retransmissions. It detects and corrects
errors like packet loss and corruption.
3. Congestion Control: Prevents the sender from overwhelming the network, using
congestion window mechanisms, slow start, congestion avoidance, and fast recovery
to adjust transmission rates based on network conditions.
Checksums: Each TCP segment contains a checksum field, which is used to verify the
integrity of the data. Both the sender and receiver calculate checksums to ensure that no
errors occurred during transmission.If the receiver detects an error (e.g., a mismatch in
checksums), the corrupt segment is discarded, and the sender is notified via
acknowledgments (or lack thereof). These mechanisms ensure that TCP provides robust,
reliable, and efficient communication
across the network.

ERROR.PY
import socket
import time
import random

# Simulating a TCP-like sender with flow control, error control, and congestion control
class TCPSimulator:
def __init__(self, server_ip, server_port, initial_window_size=1024):
self.server_ip = server_ip
self.server_port = server_port
self.window_size = initial_window_size
self.congestion_window = 1 # Simulating slow start (congestion control)
self.data_to_send = 10000 # Total data in bytes
self.sent_data = 0
self.mtu = 1024 # Maximum Transmission Unit (size of each packet)
self.loss_probability = 0.1 # Simulate 10% packet loss
def send_data(self):
# Simulate TCP connection setup (3-way handshake)
print(f"Establishing connection to {self.server_ip}:{self.server_port}...")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((self.server_ip, self.server_port))
print("Connection established!")
while self.sent_data < self.data_to_send:
sendable_size = min(self.window_size, self.congestion_window * self.mtu)
data_chunk = min(sendable_size, self.data_to_send - self.sent_data)
# Simulating Flow Control
print(f"Flow Control: Sending {data_chunk} bytes of data.")
sock.send(b"A" * data_chunk) # Sending dummy data
self.sent_data += data_chunk

81
# Simulate packet loss and Error Control (retransmissions)
if random.random() < self.loss_probability:
print("Error Control: Packet lost, retransmitting...")
self.sent_data -= data_chunk # Simulate data loss
continue # Retransmit the packet
# Simulate receiving an acknowledgment from the server
ack = sock.recv(4096)
print(f"Received ACK for {data_chunk} bytes")
# Simulating Congestion Control (slow start and congestion avoidance)
self.congestion_control()
print("All data sent and acknowledged!")
def congestion_control(self):
# Simulating Slow Start and Congestion Avoidance
if self.congestion_window < 10: # Slow start phase
self.congestion_window *= 2
print(f"Congestion Control (Slow Start): Congestion window size is now
{self.congestion_window * self.mtu} bytes")
else: # Congestion avoidance phase
self.congestion_window += 1
print(f"Congestion Control (Avoidance): Congestion window size increased to
{self.congestion_window * self.mtu} bytes")
if __name__ == "__main__":
# Simulating TCP connection to localhost for simplicity
server_ip = "127.0.0.1"
server_port = 8080

# Simulating Flow Control, Error Control, and Congestion Control


tcp_sim = TCPSimulator(server_ip, server_port)
tcp_sim.send_data()

OUTPUT:

Experiment - 9

82
Aim: To introduce Wireshark & tcpdump, and observation of packets in a LAN network.

•Wireshark is a powerful open-source packet analyzer.


• Used to capture and analyze network traffic in real-time.
• Important for network troubleshooting, security analysis, and protocol development.
Wireshark Installation (Windows/Linux)
•Windows:
• Download from https://www.wireshark.org/download.html
• After open link click on this Windows x64 Installer
•• Install and follow prompts (WinPcap installation required)
•Linux:
• Debian/Ubuntu: sudo apt-get install wireshark
•Main sections: Packet List Pane, Packet Details Pane, Packet Bytes Pane
• Toolbar overview: Open file, start/stop capture, etc.

OUTPUT:

83
Capturing and Analyzing Traffic
•Start capture by selecting an interface
•• Common capture filters:
• - tcp.port == 80 (Capture HTTP traffic)
• - ip.src == 192.168.1.1 (Traffic from specific IP)
• - udp (UDP traffic)
•-tcp.port == 443 (Capture HTTPS traffic)

84
85
Wireshark Display Filters
•Refine displayed packets:
• - http (Display HTTP traffic)
• - ip.addr == 192.168.0.1 (Packets from/to specific IP)
• - tcp.flags.syn == 1 (SYN packets)
•• Display filters vs capture filters
•Udp.port == 53 (DNS traffic)

86
87
Experiment-10

Aim: To analyze HTTP packets using Wireshark tool, and understand the records returned by
a DNS server.

1. Analyzing HTTP Packets

● Select a Packet: Click on a packet to see its details in the lower pane.
● Inspect Packet Layers:
○ Frame Layer: Provides overall metadata about the captured packet, including
timestamps.
○ Ethernet Layer: Shows MAC addresses of the source and destination.
○ IP Layer: Displays source and destination IP addresses, as well as protocol
information.
○ TCP Layer: Contains details about the TCP connection, like source and
destination ports, sequence numbers, etc.
○ HTTP Layer: This is where you’ll see the HTTP request or response. For
example, you might see HTTP GET, POST requests, or HTTP status codes like
200 (OK), 404 (Not Found).

2. Analyzing DNS Packets in Wireshark

● Filter for DNS Traffic: Use the filter dns or udp.port == 53 to see DNS queries and
responses.
● Capture DNS Traffic: Visit a website, and the DNS requests will appear in
Wireshark as the client tries to resolve the domain name.
● Select a DNS Packet: Click on a DNS packet to view the details.

3. Understanding DNS Records in Wireshark

● Query and Response: DNS traffic generally involves a query from the client (e.g.,
www.example.com) and a response from the DNS server.
● DNS Details:
○ Transaction ID: Identifies the DNS query-response pair.
○ Flags: Indicates whether the packet is a query or response.
○ Questions: Contains the domain name being queried.
○ Answers: Contains the resolved IP address for the domain name. You might
see different record types like:
■ A Record: Maps a domain name to an IPv4 address.
■ AAAA Record: Maps a domain name to an IPv6 address.
■ CNAME Record: Canonical Name, an alias for another domain.
■ MX Record: Mail exchange records that define mail servers for the
domain.
○ Authority and Additional Sections: May contain additional information, such
as authoritative name servers.

By filtering and analyzing HTTP and DNS traffic in Wireshark, you can gain insights into the
communication between clients and servers, including how domain names are resolved and
how HTTP data is transmitted.

88
OUTPUT:

89
90

You might also like