CN Lab Record Final
CN Lab Record Final
CN Lab Record Final
(AUTONOMOUS)
CERTIFICATE
By Mr./Ms. _________________________________________________________,
Date: ______________
Aim: To gain familiarity with the basic ‘Networks’ Commands & utilities available in the
Linux OS.
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 .
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:
OUTPUT:
OUTPUT:
ifplugstatus command when the cable is plugged.
a) traceroute <address>
It isn’t installed by default on Ubuntu. Use the following command to install it:
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
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.
OUTPUT:
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)
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.
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
// 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);
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);
// Create router nodes, initialize routing database and set up the routing
// tables in the nodes.
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
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));
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"
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);
InternetStackHelper internet;
internet.Install (c);
15
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", StringValue ("5Mbps"));
csma.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer d2345 = csma.Install (n2345);
// Create router nodes, initialize routing database and set up the routing
// tables in the nodes.
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
16
onoff2.SetAttribute ("DataRate", StringValue ("2kbps"));
onoff2.SetAttribute ("PacketSize", UintegerValue (50));
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);
17
Simulator::Schedule (Seconds (14),&Ipv4::SetUp,ipv41, ipv4ifIndex1);
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"
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
{
}
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;
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 ();
21
}
void
RoutingExperiment::Run (int nSinks, double txp, std::string CSVfileName)
{
Packet::EnablePrinting ();
m_nSinks = nSinks;
m_txp = txp;
m_CSVfileName = CSVfileName;
NodeContainer adhocNodes;
adhocNodes.Create (nWifis);
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]"));
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);
}
Ipv4AddressHelper addressAdhoc;
addressAdhoc.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer adhocInterfaces;
adhocInterfaces = addressAdhoc.Assign (adhocDevices);
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 ();
//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 ();
CheckThroughput ();
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:
#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);
InternetStackHelper internet;
internet.Install (c);
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;
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"
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"));
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);
//
// 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.");
31
// every few seconds
OnOffHelper onoff ("ns3::UdpSocketFactory",
Address (InetSocketAddress (multicastGroup, multicastPort)));
onoff.SetConstantRate (DataRate ("255b/s"));
onoff.SetAttribute ("PacketSize", UintegerValue (128));
//
// Tell the application when to start and stop.
//
srcC.Start (Seconds (1.));
srcC.Stop (Seconds (10.));
//
// 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);
NetDeviceContainer terminalDevices;
NetDeviceContainer switchDevices;
34
}
//
// 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)
//
// 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));
//
// 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"
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);
//
// 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);
39
NodeContainer routerNodes (n0, n1, n2, n3, n4);
InternetStackHelper internet;
internet.Install (routerNodes);
//
// 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)
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));
//
// 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"
NS_LOG_COMPONENT_DEFINE ("test-interference-helper");
/// 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;
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> ();
m_txA->ConfigureStandard (input.standard);
m_txB->ConfigureStandard (input.standard);
rx->ConfigureStandard (input.standard);
Simulator::Run ();
Simulator::Destroy ();
m_txB->Dispose ();
m_txA->Dispose ();
rx->Dispose ();
46
}
}
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;
}
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"
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;
}
50
struct Step
{
double stepSize; ///< step size in dBm
double stepTime; ///< step size in seconds
};
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);
}
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);
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);
}
// 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));
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));
56
Ptr<Node> clientNode = CreateObject<Node> ();
Ptr<Node> serverNode = CreateObject<Node> ();
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);
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));
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);
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 ());
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);
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");
gnuplot.AddDataset (rateDataset);
gnuplot.AddDataset (actualDataset);
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"
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);
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);
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);
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));
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"
/**
* \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 ();
};
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;
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";
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));
71
OUTPUT:
Experiment - 6
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
73
response = c.recv(1024).decode('utf-8')
print(response)
OUTPUT:
3. SERVER_UDP:
import socket
def udp_server():
# Define server address and port
server_address = ('localhost', 12345)
while True:
# Receive message from client
message, client_address = sock.recvfrom(4096)
print(f"Received message from {client_address}: {message.decode()}")
if __name__ == "__main__":
udp_server()
74
OUTPUT:
4. CLIENT_UDP:
import socket
def udp_client():
# Define server address and port
server_address = ('localhost', 12345)
try:
# Send a message to the server
message = "Hello, UDP Server!"
sock.sendto(message.encode(), server_address)
finally:
# Close the socket
sock.close()
if __name__ == "__main__":
udp_client()
OUTPUT:
75
Experiment-7
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.
77
FLAG.PY
import socket
from scapy.all import sniff, TCP
from scapy.layers.inet import IP
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}")
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)
src_ip = ip_layer.src
dst_ip = ip_layer.dst
src_port = tcp_layer.sport
dst_port = tcp_layer.dport
flags = tcp_layer.flags
78
print(f" Acknowledgment Number: {tcp_layer.ack}")
print(f" Window Size: {tcp_layer.window}")
# 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
OUTPUT:
Experiment - 9
82
Aim: To introduce Wireshark & tcpdump, and observation of packets in a LAN network.
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.
● 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).
● 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.
● 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