CNS Lab Manual
CNS Lab Manual
PART-A
INTRODUCTION TO NS3
Features
It it a discrete event simulator
Modular design / Open source
Actively developed (Contrast NS-2)
Developed in C++. Python binding available.
Live visualizer
Logging facility for debugging
Tutorial : First.cc
Simple point to point (Wired network) link between server and client is established here. This program is
in your NS3 repository. (example/tutorial/first.cc)
Note : To know about NS3, you must have the base knowledge in c++ and OOPS concept.
1. Module Includes
#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"
Each of the ns-3 include files is placed in a directory called ns3 (under the build directory) during the build
process to help avoid include file name collisions. The ns3/core-module.h file corresponds to the ns-3 module
you will find in the directory src/core in your downloaded release distribution. If you list this directory you
will find a large number of header files. When you do a build, Waf will place public header files in an ns3
directory under the appropriate build/debug or build/optimized directory depending on your configuration.
Waf will also automatically generate a module include file to load all of the public header files.
2. NS3 Namespace
NS_LOG_COMPONENT_DEFINE ("FirstScriptExample");
this line declares a logging component called FirstScriptExample that allows you to enable and disable
console message logging by reference to the name.
5. Create nodes
NodeContainer nodes;
nodes.Create (2);
The NodeContainer topology helper provides a convenient way to create, manage and access any Node
objects that we create in order to run a simulation. The first line above just declares a NodeContainer which
we call nodes. The second line calls the Create method on the nodes object and asks the container to create
two nodes.
PointToPointHelper pointToPoint;
It instantiates a PointToPointHelper object on the stack. From a high-level perspective the next line,
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
Above line tells the PointToPointHelper object to use the value “5Mbps” (five megabits per second) as the
“DataRate” when it creates a PointToPointNetDevice object. From a more detailed perspective, the string
“DataRate” corresponds to what we call an Attribute of the PointToPointNetDevice.
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
It tells the PointToPointHelper to use the value “2ms” (two milliseconds) as the value of the transmission
delay of every point to point channel it subsequently creates.
NetDeviceContainer devices;
devices = pointToPoint.Install (nodes);
The first line declares the device container mentioned above and the second does the heavy lifting. The Install
method of the PointToPointHelper takes a NodeContainer as a parameter. Internally, a NetDeviceContainer
is created. For each node in the NodeContainer (there must be exactly two for a point-to-point link) a
PointToPointNetDevice is created and saved in the device container.
A PointToPointChannel is created and the two PointToPointNetDevices are attached. When objects are
created by the PointToPointHelper, the Attributes previously set in the helper are used to initialize the
corresponding Attributes in the created objects. After executing the pointToPoint.Install (nodes) call we will
have two nodes, each with an installed point-to-point net device and a single point-to-point channel between
them. Both devices will be configured to transmit data at five megabits per second over the channel which
has a two millisecond transmission delay.
The only user-visible API is to set the base IP address and network mask to use when performing the actual
address allocation (which is done at a lower level inside the helper).
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
It declares an address helper object and tell it that it should begin allocating IP addresses from the network
10.1.1.0 using the mask 255.255.255.0 to define the allocatable bits. By default the addresses allocated will
start at one and increase monotonically, so the first address allocated from this base will be 10.1.1.1, followed
by 10.1.1.2, etc. The low level ns3 system actually remembers all of the IP addresses allocated and will
generate a fatal error if you accidentally cause the same address to be generated twice (which is a very hard
to debug error, by the way).
echo client application. Again, this event may schedule many more events. The start event implementation
in the echo client application will begin the data transfer phase of the simulation by sending a packet to the
server.
Simulator::Run ();
When Simulator::Run is called, the system will begin looking through the list of scheduled events and
executing them. Eventually, since we only send one packet (recall the MaxPackets Attribute was set to one),
the chain of events triggered by that single client echo request will taper off and the simulation will go idle.
Once this happens, the remaining events will be the Stop events for the server and the client. When these
events are executed, there are no further events to process and Simulator::Run returns. The simulation is then
complete.
All that remains is to clean up. This is done by calling the global function Simulator::Destroy. As the helper
functions (or low level ns-3 code) executed, they arranged it so that hooks were inserted in the simulator to
destroy all of the objects that were created. You did not have to keep track of any of these objects yourself
— all you had to do was to call Simulator::Destroy and exit. The ns-3 system took care of the hard part for
you. The remaining lines of our first ns-3 script, first.cc, do just that:
Simulator::Destroy ();
1. Implement three nodes point – to – point network with duplex links between them. Set the queue
size, vary the bandwidth and find the number of packets dropped.
Network topology
10.1.1.0 10.1.2.0
n0 -------------- n1..........n2
point-to-point
In this program we have created 3 point to point nodes n0, n1, n2. Node
n0 has IP address 10.1.1.1 and n3 has 10.1.2.2. Node n1 has 2
interfaces(10.1.1.2 and 10.1.2.1). OnOffHelper application is used to
generate the traffic at source node n0. Packets move from n0 to n2 via
n1. Acknowledgment is sent from n2 to n0 via n1. Details of the
flow(Number of packets sent, received and dropped) can be verified by
using tracemetrics(lab1.tr file).
Program
#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/traffic-control-module.h"
NS_LOG_COMPONENT_DEFINE ("Lab-Program-1");
CommandLine cmd;
cmd.Parse (argc, argv);
NodeContainer nodes;
nodes.Create (3); //3 point-to-point nodes are created
InternetStackHelper stack;
stack.Install (nodes); //TCP-IP layer functionality configured on all nodes
//Bandwidth and delay set for the point-to-point channel. Vary these
parameters to //see the variation in number of packets sent/received/dropped.
PointToPointHelper p2p1;
p2p1.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
p2p1.SetChannelAttribute ("Delay", StringValue ("1ms"));
//Set the base address for the first network(nodes n0 and n1)
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
NetDeviceContainer devices;
devices = p2p1.Install (nodes.Get (0), nodes.Get (1));
Ipv4InterfaceContainer interfaces = address.Assign (devices);
//Set the base address for the second network(nodes n1 and n2)
devices = p2p1.Install (nodes.Get (1), nodes.Get (2));
address.SetBase ("10.1.2.0", "255.255.255.0");
interfaces = address.Assign (devices);
uint16_t port = 7;
//Install receiver (for packetsink) on node 2
Address localAddress1 (InetSocketAddress (Ipv4Address::GetAny (), port));
PacketSinkHelper packetSinkHelper1 (socketType, localAddress1);
ApplicationContainer sinkApp1 = packetSinkHelper1.Install (nodes.Get (2));
sinkApp1.Start (Seconds (0.0));
sinkApp1.Stop (Seconds (10));
AsciiTraceHelper ascii;
p2p1.EnableAsciiAll (ascii.CreateFileStream ("lab1.tr"));
Output
Network topology
n0 n1 n2 n3 n4 n5
| | | | | |
===========================
CSMA channel with base IP 10.1.1.0
In this program we have created 6 CSMA nodes n0, n1, n2, n3, n4 and n5
with IP addresses 10.1.1.1, 10.1.1.2, 10.1.1.3, 10.1.1.4, 10.1.1.5 and
10.1.1.6 respectively.
Nodes n0 and n1 ping node n2, we can visualize the ping messages
transferred between the nodes. Data transfer is also simulated between
the nodes n0 and n2 using UdpSocketFactory to generate traffic.
Program
#include <iostream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/applications-module.h"
#include "ns3/internet-apps-module.h"
#include "ns3/internet-module.h"
NS_LOG_COMPONENT_DEFINE ("Lab-Program-2");
c.Create (6);
// assign ip addresses
NS_LOG_INFO ("Assign ip addresses.");
Ipv4AddressHelper ip;
ip.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer addresses = ip.Assign (devs);
// 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)
ApplicationContainer apps;
apps = ping.Install (pingers);
apps.Start (Seconds (1.0));
apps.Stop (Seconds (5.0));
AsciiTraceHelper ascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("ping1.tr"));
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
Node n1 sends ping message to n2(Broadcast message is generated) and only n2 responds to n1
Node n0 sends ping message to n2(Broadcast message is generated) and only n2 responds to n0
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
window for different source / destination.
Network topology
n0 n1 n2 n3
| | | |
===================== CSMA channel with base IP 10.1.1.0
Source node – n0 sink node - n1
In this program we have created 4 CSMA nodes n0, n1, n2 and n3 with IP
addresses 10.1.1.1, 10.1.1.2, 10.1.1.3 and 10.1.1.4 respectively. Data
transmission is simulated between nodes n0 and n1. Once the cwnd values
are generated, they are exported to .dat file and congestion graph is
plot using gnuplot.
Program
#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 <iostream>
#include "ns3/csma-module.h"
MyApp ();
virtual ~MyApp();
private:
virtual void StartApplication (void);
virtual void StopApplication (void);
Ptr<Socket> m_socket;
Address m_peer;
uint32_t m_packetSize;
uint32_t m_nPackets;
DataRate m_dataRate;
EventId m_sendEvent;
bool m_running;
uint32_t m_packetsSent;
};
MyApp::MyApp () // constructor
: m_socket (0),
m_peer (),
m_packetSize (0),
m_nPackets (0),
m_dataRate (0),
m_sendEvent (),
m_running (false),
m_packetsSent (0)
{
}
MyApp::~MyApp() // destructor
{
m_socket = 0;
}
//The next bit of code explains to the Application how to stop creating simulation
//events.
m_socket->Send (packet);
CsmaHelper csma;
csma.SetChannelAttribute ("DataRate", StringValue ("5Mbps"));
csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (0.0001)));
NetDeviceContainer devices;
devices = csma.Install (nodes);
InternetStackHelper stack;
stack.Install (nodes);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer interfaces = address.Assign (devices);
//next two lines of code will create the socket and connect the trace source.
//tell the Application what Socket to use, what address to connect to, how much //data
to send at each send event, how many send events to generate and the rate at //which
to produce data from those events.
return 0;
}
./waf - - run scratch/Program3 - -vis
Output
C
w
n
d
V
a
l
u
e
s
i
n
b
i
t
s
Time in seconds
4. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and determine
the performance with respect to transmission of packets.
Program
#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/mobility-module.h"
#include "ns3/internet-module.h"
NS_LOG_COMPONENT_DEFINE ("ThirdScriptExample");
CommandLine cmd;
cmd.AddValue ("nWifi", "Number of wifi STA devices", nWifi);
cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose);
cmd.Parse (argc,argv);
if (verbose)
{
LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO);
LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO);
}
NodeContainer p2pNodes;
p2pNodes.Create (2); // 2 nodes are n0,n1 are created
PointToPointHelper pointToPoint;
NetDeviceContainer p2pDevices;
p2pDevices = pointToPoint.Install (p2pNodes);
NodeContainer wifiStaNodes;
wifiStaNodes.Create (nWifi);
NodeContainer wifiApNode = p2pNodes.Get (0);// 1st node of p2p is also access point
WifiHelper wifi;
wifi.SetRemoteStationManager ("ns3::AarfWifiManager");//AARF= rate control
algorithm
WifiMacHelper mac;
Ssid ssid = Ssid ("ns-3-ssid");// ssid=service set identifier in 802.11
mac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid),
"ActiveProbing", BooleanValue (false));
NetDeviceContainer staDevices;
staDevices = wifi.Install (phy, mac, wifiStaNodes);
NetDeviceContainer apDevices;
apDevices = wifi.Install (phy, mac, wifiApNode);
MobilityHelper mobility;
mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel",
"Bounds",RectangleValue (Rectangle (-50, 50, -50, 50)));
mobility.Install (wifiStaNodes);
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (wifiApNode);
InternetStackHelper stack;
stack.Install (p2pNodes.Get(1));// stack installed on n1 of p2p
stack.Install (wifiApNode); //stack installed on access point
stack.Install (wifiStaNodes); //stack installed on mobile nodes
Ipv4AddressHelper address;
ApplicationContainer clientApps =
echoClient.Install (wifiStaNodes.Get (nWifi - 1));
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (10.0));
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
Output
5. Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or equivalent
environment.
#include "ns3/lte-helper.h"
#include "ns3/epc-helper.h"
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/lte-module.h"
#include "ns3/applications-module.h"
#include "ns3/point-to-point-helper.h"
#include "ns3/config-store.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("EpcFirstExample");
int
main (int argc, char *argv[])
{
uint16_t numberOfNodes = 2;
double simTime = 1.1;
double distance = 60.0;
double interPacketInterval = 100;
CommandLine cmd;
cmd.Parse(argc, argv);
Ipv4StaticRoutingHelper ipv4RoutingHelper;
Ptr<Ipv4StaticRouting> remoteHostStaticRouting =
ipv4RoutingHelper.GetStaticRouting (remoteHost->GetObject<Ipv4> ());
remoteHostStaticRouting->AddNetworkRouteTo (Ipv4Address ("7.0.0.0"), Ipv4Mask
("255.0.0.0"), 1);
NodeContainer ueNodes;
NodeContainer enbNodes;
enbNodes.Create(numberOfNodes);
ueNodes.Create(numberOfNodes);
++ulPort;
++otherPort;
PacketSinkHelper dlPacketSinkHelper ("ns3::UdpSocketFactory",
InetSocketAddress (Ipv4Address::GetAny (), dlPort));
PacketSinkHelper ulPacketSinkHelper ("ns3::UdpSocketFactory",
InetSocketAddress (Ipv4Address::GetAny (), ulPort));
PacketSinkHelper packetSinkHelper ("ns3::UdpSocketFactory",
InetSocketAddress (Ipv4Address::GetAny (), otherPort));
serverApps.Add (dlPacketSinkHelper.Install (ueNodes.Get(u)));
serverApps.Add (ulPacketSinkHelper.Install (remoteHost));
serverApps.Add (packetSinkHelper.Install (ueNodes.Get(u)));
AsciiTraceHelper ascii;
p2ph.EnableAsciiAll(ascii.CreateFileStream("cdma.tr"));
Simulator::Stop(Seconds(simTime));
Simulator::Run();
/*GtkConfigStore config;
config.ConfigureAttributes();*/
Simulator::Destroy();
return 0;
Output
PART-b
7. Write a program for error detecting code using CRC-CCITT (16- bits).
import java.io.*;
class crc
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
int data_bits, divisor_bits, tot_length;
tot_length=data_bits+divisor_bits-1;
div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];
/*------------------ CRC GENERATION-----------------------*/
for(int i=0;i<data.length;i++)
div[i]=data[i];
/*-------------------ERROR DETECTION---------------------*/
System.out.println();
System.out.println("Enter CRC code of "+tot_length+" bits : ");
for(int i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.readLine());
if((rem.length-cur)<divisor.length)
break;
}
return rem;
}
}
OUTPUT :
Enter number of data bits :
7
Enter data bits :
1
0
1
1
0
0
1
Enter number of bits in divisor :
3
Enter Divisor bits :
1
0
1
Data bits are : 1011001
divisor bits are : 101
Dividend (after appending 0's) are : 101100100
CRC code :
101100111
CRC code :
101100111
Enter CRC code of 9 bits :
1
1
1
1
0
0
1
0
1
No Error
THANK YOU.... :)
8. Write a program to find the shortest path between vertices using bellman-ford algorithm.
package bellmanford;
import java.util.*;
public class Bellmanford {
static int n, dest;
static double[] prevDistanceVector, distanceVector;
static double[][] adjacencyMatrix;
public static void main(String[] args) {
// TODO code application logic here
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of nodes");
n = scanner.nextInt();
adjacencyMatrix = new double[n][n];
System.out.println("Enter Adjacency Matrix (Use 'Infinity' for No Link)");
for (int i = 0; i< n; i++)
for (int j = 0; j < n; j++)
adjacencyMatrix[i][j] = scanner.nextDouble();
System.out.println("Enter destination vertex");
dest = scanner.nextInt();
distanceVector = new double[n];
for (int i = 0; i< n; i++)
distanceVector[i] = Double.POSITIVE_INFINITY;
distanceVector[dest - 1] = 0;
bellmanFordAlgorithm();
System.out.println("Distance Vector");
for (int i = 0; i< n; i++) {
if (i == dest - 1) {
continue;
}
System.out.println("Distance from " + (i + 1) + " is " + distanceVector[i]);
}
System.out.println();
}
9. Using TCP/IP sockets, write a client – server program to make the client send the file
name and to make the server send back the contents of the requested file if present.
Server
package org.tcp;
import java.net.*;
import java.io.*;
Client
package org.tcp;
import java.net.*;
import java.io.*;
k.close();
client.close();
sendToServer.close();
i.close();
}
catch(Exception ex) {}
}
}
OUTPUT
Server Console
Server waiting
Connection established
Client Console
Enter file location:
F:\test.txt
Testing TCP socket
10. Write a program on datagram socket for client/server to display the messages on client side,
typed at the server side.
package labcn;
import java.net.*;
import java.util.*;
while(true)
{
byte[] buffer = new byte[1000];
DatagramPacket request = new DatagramPacket(buffer,
buffer.length);
server.receive(request);
server.close();
scan.close();
}
}
catch(Exception ex) {}
}
package labcn;
import java.net.*;
public class udpcli {
client.close();
}
catch(Exception ex) {}
}
OUTPUT
Sever console
Enter server message:
Hello udp client
Client console
Client received:
Hello udp client
11. Write a program for simple RSA algorithm to encrypt and decrypt the data.
package rsa4;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Scanner;
p = BigInteger.probablePrime(bitLength, secureRandom);
q = BigInteger.probablePrime(bitLength, secureRandom);
n = p.multiply(q);
phi_n = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitLength / 2, secureRandom);
while (e.gcd(phi_n).compareTo(BigInteger.ONE) != 0 &&e.compareTo(phi_n) < 0) {
e = e.add(BigInteger.ONE);
}
d = e.modInverse(phi_n);
}
}
OUTPUT
P assigned as: 13330063847181728989
Q assigned as: 10448652783677772539
N assigned as: 139281208723457810526403094838284433071
PHI_N assigned as: 139281208723457810502624378207424931544
Enter Message
5432101
Encrypted Message: 60742093698753105772915807270189084958
Decrypted Message: 5432101
12. Write a program for congestion control using leaky bucket algorithm.
package lb;
import java.util.*;
public class Lb{
public static void main(String[] args) {
System.out.println("enter the number of time intervals");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int t[]=new int[n];
System.out.println("enter the time intervals");
for(int i=0;i<n;i++)
t[i]=sc.nextInt();
System.out.println("enter i and l");
int i=sc.nextInt();
int l=sc.nextInt();
int lct=t[0];
int x=0,y=0;
for(int j=0;j<n;j++)
{
y=x-(t[j]-lct);
if(y>l)
{
System.out.println("nonconforming packet"+t[j]);
}
else
x=y+i;
lct=t[j];
System.out.println("conforming packet"+t[j]);
}
}
}
OUTPUT
enter the number of time intervals
11
enter the time intervals
1 2 3 5 6 8 11 12 13 15 19
enter i and l
4
4
conforming packet1
conforming packet2
nonconforming packet3
conforming packet3
nonconforming packet5
conforming packet5
nonconforming packet6
conforming packet6
nonconforming packet8
conforming packet8
conforming packet11
nonconforming packet12
conforming packet12
nonconforming packet13
conforming packet13
nonconforming packet15
conforming packet15
conforming packet19