CN Lab Manual 18CSL57 2020
CN Lab Manual 18CSL57 2020
RNSInstituteofTechnology
Dr. Vishnuvardana Road, Channasandra
Bengaluru – 560098
DEPARTMENT
of
COMPUTER SCIENCE & ENGINEERING
LABORATORY MANUAL
V Semester
Course objectives: This course will enable students to achieve the following:
• Demonstrate operation of network and its managementcommands
• Simulate and demonstrate the performance of GSM andCDMA
• Implement data link layer and transport layerprotocols.
Course outcomes: At the end of the course the students should be able to:
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 2 3 1 2 - - - - - 2 1 2
CO2 2 2 1 2 - - - - - 2 1 2
CO3 2 2 1 - - - - - - 2 1 2
CO4 2 2 1 2 - - - 1 2 1 2
CO5 2 2 1 2 - - - - - 2 1 2
CO6 2 1 - - 2 - - - - 1 - 1
CO-PSO MAPPING MATRIX
CO1 2 1 1 -
CO2 2 1 1 -
CO3 2 1 1 -
CO4 2 1 1 1
CO5 1 1 1 1
CO6 1 1 - -
SubjectCode:18CSL57 IA Marks:40
Hours/Week : 01I+02P Exam Marks:60
TotalHours:40 Exam Hours:03
Lab Experiments:
PART A
Implement the following using NS2/NS3
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.
2. Implement transmission of ping messages/trace route over a network topology
consisting of 6 nodes and find the number of packets dropped due to
congestion.
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodesand
plot congestion window for different source/destination.
4. Implement simple ESS and with transmitting nodes in wire-less LAN by
simulation and determine the performance with respect to transmissionofpackets.
5. Implement and study the performance of GSM on NS2/NS3 (UsingMAC
layer)or equivalent environment.
6. Implement and study the performance of CDMA on NS2/NS3 (Using stack
called Call net) or equivalentenvironment.
PART B
Implement the following in Java:
7. Write a program for error detecting code using CRC-CCITT(16-bits).
8. Write a program to find the shortest path between vertices using bellman-
fordalgorithm.
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
ifpresent.
10. Write a program on datagram socket for client/server to display the messageson
client side, typed at the serverside.
11. Write a program for simple RSA algorithm to encrypt and decryptthedata.
12. Write a program for congestion control using leaky bucketalgorithm.
Good Average
a. Write up Write the program neatly Moderate understanding of
(3 marks) demonstrating good knowledge of algorithms(2)
concepts and algorithms in
java/NS3 (3)
b. Execution Program handles all possible Average conditions defined
(3 marks) conditions (3) (2)
c. Result All results including Acceptable documentation
(2 marks) topology/graphs are correctly shown(1)
demonstrated(2)
Good Average
Conceptual Explain the complete program with explanation provided
understanding the related concepts (2) adequately (1)
(2 marks)
Execution plan
WEEK # NAME OF THE EXPERIMENT EXPERIMENT CO REMARKS
#
1 Program for error detecting code 7 1
using CRC-CCITT (16- bits).
2 Bellman-ford algorithm 8 2,6
Simple NS3 program – first.cc
3 Implement three nodes point – to 1 6
– point network with duplex links
between them
4 Congestion control using leaky 11 & 12 4,5
bucket algorithm
RSA algorithm
5 Lab Internal-I
6 Implement transmission of ping 2 6
messages/trace route
7 Implement Ethernet LAN using n 3 6
nodes and set multiple traffic
nodes and plot congestion window
8 Implement simple ESS and with 4 6
transmitting nodes in wire-less
LAN
9 Socket programming(TCP & 9 & 10 3
UDP)
10 Implement and study the 5 6
performance of GSM on NS2/NS3
11 Implement and study the 6 6
performance of CDMA on
NS2/NS3
12 Lab Internal-II
INDEX
SL EXPERIMENT DATE OF
NAME OF THE EXPERIMENT MARKS
NO NO EXECUTION
1
10
11
12
Avg:
FINAL IA MARKS
Max marks Marks obtained
Average of Daily execution 10
TEST-1 5
TEST-2 5
TOTAL 20
Staff signature:
PART-A
INTRODUCTION TO NS3
Features
• It it a discrete eventsimulator
• Modular design / Opensource
• Actively developed (ContrastNS-2)
• Developed in C++. Python bindingavailable.
• Livevisualizer
• Logging facility fordebugging
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. ModuleIncludes
#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 directorysrc/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. NS3Namespace
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 thename.
5. Createnodes
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
twonodes.
PointToPointHelperpointToPoint;
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 subsequentlycreates.
NetDeviceContainerdevices;
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 devicecontainer.
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
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 thenetwork
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 theway).
10. Setuprouting
UdpEchoServerHelperechoServer (9);
ApplicationContainerserverApps = echoServer.Install (nodes.Get (1));
The first line of code in the above snippet declares the UdpEchoServerHelper. As usual, this isn’t the
application itself, it is an object used to help us create the actual applications. One of our conventions is to
place required Attributes in the helper constructor. In this case, the helper can’t do anything useful unless it
is provided with a port number that the client also knows about. Rather than just picking one and hoping it
all works out, we require the port number as a parameter to the constructor. The constructor, in turn, simply
does a SetAttribute with the passed value. If you want, you can set the “Port” Attribute to another value
later usingSetAttribute.
Similar to many other helper objects, the UdpEchoServerHelper object has an Install method. It is the
execution of this method that actually causes the underlying echo server application to be instantiated and
attached to a node. Interestingly, the Install method takes a NodeContainter as a parameter just as the other
Install methods we have seen. This is actually what is passed to the method even though it doesn’t look so
First it will run the event at 1.0 seconds, which will enable the echo server application (this event may, in
turn, schedule many other events). Then it will run the event scheduled for t=2.0 seconds which will start
the 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 theserver.
13. Runsimulation
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 thencomplete.
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 packetsdropped.
Overview:
Point-to-point network topology is a simple topology that displays the network of exactly two hosts
(computers, servers, switches or routers) connected with a cable. Point-to-point topology is widely used in the
computer networking and computer architecture. It is also used in the telecommunications systems when we speak
about the communication connection of two nodes or endpoints.
• Add 3 nodes
• Establish link between the nodes using TCP/UDP
• Show the number of packets dropped in pyviz and trace route.
Networktopology
10.1.1.0 10.1.2.0
n0--------------n1 ........... n2
point-to-point
Inthisprogramwehavecreated3pointtopointnodesn0,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.2and10.1.2.1). OnOffHelper application is used to
generatethetrafficatsourcenoden0.Packetsmovefromn0ton2via 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.trfile).
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");
CommandLinecmd;
cmd.Parse (argc, argv);
NodeContainernodes;
nodes.Create(3); //3 point-to-point nodes arecreated
InternetStackHelperstack;
stack.Install(nodes); //TCP-IP layer functionality configured on allnodes
//Bandwidth and delay set for the point-to-point channel. Vary these
parametersto //seethevariationinnumberofpacketssent/received/dropped.
PointToPointHelperp2p1;
p2p1.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
p2p1.SetChannelAttribute ("Delay", StringValue ("1ms"));
NetDeviceContainerdevices;
devices = p2p1.Install (nodes.Get (0), nodes.Get (1));
Ipv4InterfaceContainerinterfaces=address.Assign(devices);
//Setthebaseaddressforthesecondnetwork(nodesn1andn2) 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
AddresslocalAddress1(InetSocketAddress(Ipv4Address::GetAny(),port));
PacketSinkHelper packetSinkHelper1 (socketType, localAddress1);
ApplicationContainersinkApp1=packetSinkHelper1.Install(nodes.Get(2));
sinkApp1.Start (Seconds(0.0));
sinkApp1.Stop (Seconds (10));
Simulator::Stop (Seconds(10));
AsciiTraceHelper ascii;
p2p1.EnableAsciiAll (ascii.CreateFileStream ("lab1.tr"));
Output
Overview:
Topology
Networktopology
n0 n1 n2 n3 n4 n5
| | | | | |
===========================
CSMA channel with base IP 10.1.1.0
Inthisprogramwehavecreated6CSMAnodesn0,n1,n2,n3,n4andn5
withIPaddresses10.1.1.1,10.1.1.2,10.1.1.3,10.1.1.4,10.1.1.5and
10.1.1.6 respectively.
Nodes n0 and n1 ping node n2, we can visualize the ping messages
transferredbetweenthenodes.Datatransferisalsosimulatedbetween
thenodesn0andn2usingUdpSocketFactorytogeneratetraffic.
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");
// assign ip addresses
//CreateanOnOffapplicationtosendUDPdatagramsfromnodezerotonode1. NS_LOG_INFO
("CreateApplications.");
uint16_t port=9; // Discard port (RFC863)
OnOffHelperonoff("ns3::UdpSocketFactory",
Address (InetSocketAddress (addresses.GetAddress (2), port)));
onoff.SetConstantRate (DataRate ("500Mb/s"));
ApplicationContainerapps;
apps = ping.Install(pingers);
apps.Start (Seconds (1.0));
apps.Stop (Seconds (5.0));
NS_LOG_INFO ("RunSimulation.");
AsciiTraceHelperascii;
csma.EnableAsciiAll (ascii.CreateFileStream ("ping1.tr"));
Simulator::Run ();
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
Noden1sendspingmessageton2(Broadcastmessageisgenerated)andonlyn2respondston1
Noden0sendspingmessageton2(Broadcastmessageisgenerated)andonlyn2respondston0
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
window for different source /destination.
OVERVIEW
Network congestion in data networking is the reduced quality of service that occurs when a network node or link
is carrying more data than it can handle. Typical effects include queuing delay, packet loss or the blocking of new
connections.
TCP Slow Start is part of the congestion control algorithms put in place by TCP to help control the amount of data
flowing through to a network. This helps regulate the case where too much data is sent to a network and the
network is incapable of processing that amount of data, thus resulting in network congestion.
When transmission of data from sender to receiver begins in a network, there may be unknown conditions as to
what the network can handle. Slow Start helps to mitigate the pitfalls of this unknown by implementing the
following functionality.
1. A sender begins transmissions to a receiver by slowly probing the network with a packet that contains its
initial congestion window (cwnd).
2. The client receives the packet and replies with its maximum buffer size, also known as the receiver’s
advertised window (rwnd).
3. If the sender receives an acknowledgement (ACK) from the client, it then doubles the amount of packets to
send to the client.
4. Step 3 is repeated until the sender no longer receives ACK from the receiver which means either congestion is
detected, or the client’s window limit has been reached.
Networktopology
n0 n1 n2 n3
| | | |
===================== CSMA channel with base IP10.1.1.0
Source node–n0 sink node -n1
Inthisprogramwehavecreated4CSMAnodesn0,n1,n2andn3withIP
addresses10.1.1.1,10.1.1.2,10.1.1.3and10.1.1.4respectively.Data
transmissionissimulatedbetweennodesn0andn1.Oncethecwndvalues are
generated, they are exported to .dat file and congestion graph is plot
usinggnuplot.
Program
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include"ns3/applications-module.h"
#include <iostream>
#include "ns3/csma-module.h"
#include "ns3/network-application-helper.h"
using namespacens3;
using namespacens3;
int
main (int argc, char *argv[])
{
CommandLinecmd;
cmd.Parse (argc,argv);
NS_LOG_INFO ("Createnodes.");
NodeContainernodes;
nodes.Create (4); //4 csma nodes are created
CsmaHelpercsma;
csma.SetChannelAttribute ("DataRate", StringValue ("5Mbps"));
csma.SetChannelAttribute("Delay",TimeValue(MilliSeconds(0.0001)));
NetDeviceContainer devices;
devices = csma.Install(nodes);
InternetStackHelperstack;
stack.Install (nodes);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainerinterfaces=address.Assign(devices);
AddresssinkAddress(InetSocketAddress(interfaces.GetAddress(1),
sinkPort));
PacketSinkHelperpacketSinkHelper("ns3::TcpSocketFactory",
InetSocketAddress (Ipv4Address::GetAny (), sinkPort));
ApplicationContainersinkApps=packetSinkHelper.Install(nodes.Get(1));
sinkApps.Start (Seconds(0.));
sinkApps.Stop (Seconds(20.));
//next two lines of code will create the socket and connect the trace source.
Ptr<Socket>ns3TcpSocket=Socket::CreateSocket(nodes.Get(0),
TcpSocketFactory::GetTypeId());
ns3TcpSocket->TraceConnectWithoutContext("CongestionWindow",MakeCallback
(&CwndChange));
//Next statement tells 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 thoseevents.
app->Setup(ns3TcpSocket,sinkAddress,1040,1000,DataRate("50Mbps"));
nodes.Get (0)->AddApplication(app);
app->SetStartTime (Seconds(1.));
app->SetStopTime (Seconds(20.));
AsciiTraceHelperascii;
csma.EnableAsciiAll(ascii.CreateFileStream("3lan.tr"));
csma.EnablePcapAll (std::string ("3lan"), true);
Simulator::Stop (Seconds(20));
Simulator::Run ();
Simulator::Destroy ();
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
CN LAB MANUAL 2018
4. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and determine
the performance with respect to transmission ofpackets.
OVERVIEW
An extended service set (ESS) is one or more interconnected basic service sets (BSSs) and their associated
LANs. Each BSS consists of a single access point (AP) together with all wireless client devices (stations, also called
STAs) creating a local or enterprise 802.11 wireless LAN (WLAN).
The most basic BSS consists of one AP and one STA. An extended service set, consisting of a set of BSSs, must have a
common service set identifier (SSID). The BSSs can all work on the same or different channels.
This helps to boost the signal throughout the wireless network.
A single service set consists of all STAs receiving signals from a given AP and creates an 802.11 wireless LAN
(WLAN). Each STA may receive a signal from several APs within their range. Depending on its configuration each
STA can, manually or automatically, select the network with which to associate. And multiple APs may share the same
SSID as part of an extended service set.
Topology
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");
CommandLinecmd;
cmd.AddValue ("nWifi", "Number of wifi STA devices", nWifi);
cmd.AddValue("verbose","Tellechoapplicationstologiftrue",verbose);
cmd.Parse(argc,argv);
if (verbose)
{
LogComponentEnable("UdpEchoClientApplication",LOG_LEVEL_INFO);
LogComponentEnable("UdpEchoServerApplication",LOG_LEVEL_INFO);
}
NodeContainerp2pNodes;
p2pNodes.Create (2); // 2 nodes are n0,n1 are created
PointToPointHelperpointToPoint;
NetDeviceContainerp2pDevices;
p2pDevices = pointToPoint.Install (p2pNodes);
NodeContainerwifiStaNodes;
wifiStaNodes.Create(nWifi);
NodeContainerwifiApNode = p2pNodes.Get (0);// 1st node of p2p is also access point
WifiHelperwifi;
wifi.SetRemoteStationManager("ns3::AarfWifiManager");//AARF=ratecontrol
algorithm
WifiMacHelpermac;
Ssidssid= Ssid ("ns-3-ssid");// ssid=service set identifier in802.11
mac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid),
"ActiveProbing", BooleanValue(false));
NetDeviceContainerstaDevices;
Dept. of CSE, RNSIT, BANGALORE Page 25
CN LAB MANUAL 2018
staDevices= wifi.Install (phy, mac, wifiStaNodes);
mac.SetType("ns3::ApWifiMac","Ssid",SsidValue(ssid));
NetDeviceContainerapDevices;
apDevices=wifi.Install(phy,mac,wifiApNode);
MobilityHelpermobility;
//2dimensionalgridtoinitiallyplacesta(stationarynodes)
mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
"MinX", DoubleValue(10.0),
"MinY", DoubleValue(-10.0),
"DeltaX", DoubleValue(7.0),
"DeltaY", DoubleValue (12.0),
"GridWidth", UintegerValue (3),
"LayoutType", StringValue("RowFirst"));
mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel",
"Bounds",RectangleValue (Rectangle (-50, 50, -50, 50)));
mobility.Install (wifiStaNodes);
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (wifiApNode);
InternetStackHelperstack;
stack.Install(p2pNodes.Get(1));//stackinstalledonn1ofp2p
stack.Install (wifiApNode); //stack installed on access point
stack.Install(wifiStaNodes);//stackinstalledonmobilenodes
Ipv4AddressHelper address;
ApplicationContainerclientApps=
echoClient.Install(wifiStaNodes.Get(nWifi-1));
clientApps.Start (Seconds(2.0));
clientApps.Stop (Seconds (10.0));
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
Simulator::Stop (Seconds(10.0));
AsciiTraceHelper ascii;
Dept. of CSE, RNSIT, BANGALORE Page 26
CN LAB MANUAL 2018
pointToPoint.EnableAsciiAll(ascii.CreateFileStream("Tracefilewifides.tr"));
phy.EnableAsciiAll (ascii.CreateFileStream ("Tracefilewifisrc.tr"));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
Output
5. Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or equivalent
environment.
OVERWIEW:
GSM stands for Global System for Mobile Communication. It is a digital cellular technology used for
transmitting mobile voice and data services. GSM is the most widely accepted standard in telecommunications and
it is implemented globally. GSM is a circuit-switched system that divides each 200 kHz channel into eight 25 kHz
time-slots. GSM operates on the mobile communication bands 900 MHz and 1800 MHz in most parts of the world.
In the US, GSM operates in the bands 850 MHz and 1900 MHz.
A GSM network comprises of many functional units. These functions and interfaces are explained in this chapter.
The GSM network can be broadly divided into:
• The Mobile Station (MS)
• The Base Station Subsystem (BSS)
• The Network Switching Subsystem (NSS)
• The Operation Support Subsystem (OSS)
The following diagram shows the GSM network along with the added elements:
mobileApplicatonHelper.SetupApplications(serverApps, clientApps,
remoteHost, remoteHostAddr, ulPort, dlPort, otherPort,
interPacketInterval);
serverApps.Start(Seconds(0.01));
clientApps.Start(Seconds(0.01));
lteHelper->EnableTraces();
// Uncomment to enable PCAP tracing
p2ph.EnablePcapAll("lena-epc-first");
AsciiTraceHelperascii;
p2ph.EnableAsciiAll(ascii.CreateFileStream("cdma.tr"));
Simulator::Stop(Seconds(simTime));
Simulator::Run();
/*GtkConfigStoreconfig;
config.ConfigureAttributes();*/
Simulator::Destroy();
return 0;
}
./waf - - run scratch/Program5 - -vis
Output
PART-B
Overview:
The accurate implementations (long-hand and programmed) of the 16-bit CRC-CCITT specification, is as
follows:
• Width = 16 bits
• Truncated polynomial = 0x1021
• Initial value = 0xFFFF
• Input data is NOT reflected
• Output CRC is NOT reflected
• No XOR is performed on the output CRC
Theoretical Concepts:
o Important features of a standard CRC are that it:
o Can be used to validate data
o Is reproducible by others
The first feature above is easy to realize in a closed system if corruption of data is infrequent (but substantial when it
occurs). The term "closed system" refers to a situation where the CRC need not be communicated to others. A
correct implementation of a 16-bit CRC will detect a change in a single bit in a message of over 8000 bytes. An
erroneous CRC implementation may not be able to detect such subtle errors. If errors are usually both rare and large
(affecting several bits), then a faulty 16-bit CRC implementation may still be adequate in a closed system.
The second feature above -- that the CRC is reproducible by others -- is crucial in an open system; that is, when the
CRC must be communicated to others. If the integrity of data passed between two applications is to be verified using
a CRC defined by a particular standard, then the implementation of that standard must produce the same result in
both applications -- otherwise, valid data will be reported as corrupt.
Reproducibility may be satisfied by even a botched implementation of a standard CRC in most cases -- if everyone
uses the same erroneous implementation of the standard. But this approach:
• Modifies the standard in ways that are both unofficial and undocumented.
• Creates confusion when communicating with others who have not adopted the botched implementation as
the implied standard.
The CRC value for the 9-byte reference string, "123456789" is 0xE5CC.
The need to focus on the 16-bit CRC-CCITT (polynomial 0x1021) and not CRC-16 (polynomial 0x8005),are as
follows :
• Is a straightforward 16-bit CRC implementation in that it doesn't involve:
• reflection of data
• reflection of the final CRC value
● Starts with a non-zero initial value -- leading zero bits can't affect the CRC16 used by LHA, ARC, etc.,
Theory
It does error checking via polynomial division. In general, a bit string bn-1bn- 2bn-3…b2b1b0
Asbn-1Xn- 1 + bn-2 Xn-2 + bn-3 Xn-3 + …b2 X2 + b1 X1 + b0
Ex: -
10010101110 As
X10 + X7 + X5 + X3 + X2 + X1
All computations are done in modulo 2
tot_length=data_bits+divisor_bits-1;
div=newint[tot_length];
rem=newint[tot_length];
crc=newint[tot_length];
/*------------------CRCGENERATION ------------------------ */
for(int i=0;i<data.length;i++)
div[i]=data[i];
/*-------------------ERRORDETECTION --------------------- */
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());
while(rem[cur]==0 &&cur!=rem.length-1)
cur++;
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
THANKYOU ...... )
8. Write a program to find theshortest path between vertices using bellman-ford algorithm.
Theory
Routing algorithm is a part of network layer software which is responsible for deciding which output line an
incoming packet should be transmitted on. If the subnet uses datagram internally, this decision must be made anew
for every arriving data packet since the best route may have changed since last time. If the subnet uses virtual
circuits internally, routing decisions are made only when a new established route is being set up. The latter case is
sometimes called session routing, because a rout remains in force for an entire user session (e.g., login session at a
terminal or a file).
Routing algorithms can be grouped into two major classes: adaptive and nonadaptive. Nonadaptive algorithms do
not base their routing decisions on measurement or estimates of current traffic and topology. Instead, the choice of
route to use to get from I to J (for all I and J) is compute in advance, offline, and downloaded to the routers when the
network ids booted. This procedure is sometime called static routing.
Adaptive algorithms, in contrast, change their routing decisions to reflect changes in the topology, and usually the
traffic as well. Adaptive algorithms differ in where they get information (e.g., locally, from adjacent routers, or from
all routers), when they change the routes (e.g., every ΔT sec, when the load changes, or when the topology changes),
and what metric is used for optimization (e.g., distance, number of hops, or estimated transit time).
Two algorithms in particular, distance vector routing and link state routing are the most popular. Distance vector
routing algorithms operate by having each router maintain a table (i.e., vector) giving the best known distance to
each destination and which line to get there. These tables are updated by exchanging information with the neighbors.
The distance vector routing algorithm is sometimes called by other names, including the distributed Bellman-Ford
routing algorithm and the Ford-Fulkerson algorithm, after the researchers who developed it (Bellman, 1957; and
Ford and Fulkerson, 1962). It was the original ARPANET routing algorithm and was also used in the Internet under
the RIP and in early versions of DECnet and Novell’s IPX. AppleTalk and Cisco routers use improved distance
vector protocols.
In distance vector routing, each router maintains a routing table indexed by, and containing one entry for, each router
in subnet. This entry contains two parts: the preferred out going line to use for that destination, and an estimate of
the time or distance to that destination. The metric used might be number of hops, time delay in milliseconds, total
number of packets queued along the path, or something similar.
The router is assumed to know the “distance” to each of its neighbor. If the metric is hops, the distance is just one
hop. If the metric is queue length, the router simply examines each queue. If the metric is delay, the router can
measure it directly with special ECHO packets hat the receiver just time stamps and sends back as fast as possible.
packagebellmanford;
importjava.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 destinationvertex");
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.pr
intln("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
nameandtomaketheserversendbackthecontentsoftherequestedfileifpresent.
OVERVIEW
Unix sockets is just like two way FIFO's. All data communication will take place through the socket's interface, instead
of through the file interface. Although unixsocket's are a special file in the file system(just like FIFO's), there's usage of
socket(), bind(), recv(),etc and not open(), read().
When programming with socket's, usually there's creation of server and client programs. The server will sit listening
for incoming connections from clients and handling. This is similar to the situation that exists with internet sockets but
with fine differences.
For instance, when describing which unix socket that has to be used(i.e the path to the special file that is the socket).
The structure “structsockaddr_un” has the following fields:
structsockaddr_un{
unsigned short sa_family; // Address family,AF_XXXX
charsa_data; // 14 bytes of protocol address
};
This is the structure you will be passing to the bind() function, which associates a socket descriptor(a file
descriptor) with a certain file(the name for which is in the sun_path field).
The structure “structsockaddr_in” is used when we need IP address and Port number to be binded to the Sockets. It has
following fields:
structsockaddr_in {
shortintsin_family; // Address family
unsigned short intsin_port; // Port number
structin_addrsin_addr; // Internetaddress
unsigned char sin_zero[8] // Same size as structsockaddr
};
// Internet adress
structin_addr {
unsigned long s_addr; // 32 bits or 4 bytes long
};
The steps involved in establishing a socket on the server side are as follows-
1. Create a socket with the socket() system call.
2. Bind the socket to an address using the bind() system call. For a server socket on the internet,an address
consists of a port number on the host machine.
3. Listen for connections with the listen() system call.
4. Acept a connection with the accept() system call. This call typically blocks until a client connects with the
server.
5. Send and receive the data.
Socket Types:
When a socket is created, the program has to specify the address domain and the socket type. Two processes can
communicate with each other only if their sockets are of the same type and in the same domain, in which two processes
running on any two hosts on the Internet communicate. Each of these has it's own address format.
The address of a socket in the Unix domain is a character string which is basically an entry in the file system.
The address of a socket in the Internet domain consists of the Internet address of the host machine (every computer on
the Internet has a unique 32 bit address, often referred to as it's IP address). In addition, each socket needs a port
number on that host. Port numbers are 16 bit unsigned integers. The lower numbers are reserved in Unix for standard
services. For eg, the port number for the FTP server is 21.
There are two widely used socket types, stream sockets , and datagram sockets. Stream sockets treat
communications as a continuous stream of characters, while datagram sockets have to read entire messages at once.
Each uses it's own communications protocol. Stream sockets use TCP , which is a reliable , stream oriented protocol,
and datagram sockets use UDP, which is unreliable and message oriented.
Server
package labcn;
import java.net.*;
import java.io.*;
try
{
ServerSocket se = new ServerSocket(1537);
System.out.println("Server waiting");
}
}
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 serverside.
Using User Datagram Protocol, Applications can send data/message to the other hosts without prior
communications or channel or path. This means even if the destination host is not available, application can send
data. There is no guarantee that the data is received in the other side. Hence it's not a reliable service.
A datagram socket is the one for sending or receiving point for a packet delivery service. Each packet sent or
received on a datagram socket is individually addressed and routed. Multiple packets sent from one machine to
another may be routed differently, and may arrive in any order.
UDP is appropriate in places where delivery of data doesn't matters during data transition.
UDP Server
package labcn;
import java.net.*;
import java.util.*;
while(true)
{
byte[] buffer = new byte[1000];
DatagramPacket request = new DatagramPacket(buffer, buffer.length);
Dept. of CSE, RNSIT, BANGALORE Page 40
CN LAB MANUAL 2020
server.receive(request);
server.close();
scan.close();
}
}
catch(Exception ex) {}
}
}
UDP Client
package labcn;
import java.net.*;
public class udpcli {
client.close();
}
catch(Exception ex) {}
}
OUTPUT
Sever console
Enter servermessage:
Hello udpclient
Client console
Clientreceived:
Hello udpclient
11. Write a program for simple RSA algorithm to encrypt and decrypt thedata.
The RSA Public key algorithm was invented in 1977 by Ron Rivest, Adi Shamir and Leonard Adleman (RSA). The
algorithm Supports Encryption and Digital Signatures. It is the most widely used public key algorithm. RSA gets its
security from the integer factorization problem. The algorithm is relatively easy to understand and implement. It
has been patent free since 2000. RSA is used in security protocols such as IPSEC/IKE -IP data security,TLS/SSL -
transport data security (web), PGP -email security,SSH -terminal connection security,SILC -conferencing service
security.
Theoretical Concepts:
RSA gets its security from the factorization problem. The difficulty of factoring large numbers is the basis of
security of RSA.
The Integer factorization problem (finding a number's prime factors):
For a positive integer n, find its prime factors:
n = p1 p2 ... pi where pi is positive distinct prime number
Example: 257603 = 41 * 61 * 103
Factorization algorithms can be used to factor faster than brute forcing. Some of them are Trial division, Pollard's
rho, Pollard's p-1, Quadratic sieve, elliptic curve factorization, Random square factoring, Number field sieve, etc.
A Prime number is a positive integer and is divisible only by itself and 1. Prime numbers are found withprimality
testing; an algorithm which tests a probable prime for primality. If primalitytesting returns false prime numbers the
cryptographic algorithm may be insecure (or will not function correctly).
RSA depends on prime numbers in key generation. It also uses strong primes, numbers whose factors of the prime
are also primes.
The RSA algorithm:
Key generation:
package rsa4;
import java.math.BigInteger;
importjava.security.SecureRandom;
importjava.util.Scanner;
secureRandom = newSecureRandom();
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) {
Dept. of CSE, RNSIT, BANGALORE Page 43
CN LAB MANUAL 2020
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
The leaky-bucket implementation is used to control the rate at which traffic is sent to the network. A leaky bucket
provides a mechanism by which bursty traffic can be shaped to present a steady stream of traffic to the network, as opposed
to traffic with erratic bursts of low-volume and high-volume flows.
Traffic analogy An appropriate analogy for the leaky bucket is a scenario in which four lanes of automobile traffic
converge into a single lane. A regulated admission interval into the single lane of traffic flow helps the traffic move. The
benefit of this approach is that traffic flow into the major arteries (the network) is predictable and controlled. The major
liability is that when the volume of traffic is vastly greater than the bucket size, in conjunction with the drainage-time
interval, traffic backs up in the bucket beyond bucket capacity and is discarded.
The size b of the bucket is limited by the available memory of the system.
Sometimes the leaky bucket and token algorithms are lumped together under the same name.
package lb;
import java.util.*;
public class Lb{
public static void main(String[] args) {
System.out.println("enter the number of timeintervals");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int t[]=new int[n];
System.out.println("enter the timeintervals");
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