4.Cn Lab Manual 2020
4.Cn Lab Manual 2020
PART-A
INTRODUCTION TO NS3
Features
• It it a discrete event simulator
• Modular design / Open source
• Actively developed (ContrastNS-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 Node Container 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 Node Container which
we call nodes. The second line calls the Create method on the nodes object and asks the container to create two
nodes.
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 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 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).
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 in
this case. There is a C++ implicit conversion at work here that takes the result of nodes.Get (1) (which returns
a smart pointer to a node object — Ptr<Node>) and uses that in a constructor for an unnamed NodeContainer
that is then passed to Install. If you are ever at a loss to find a particular method signature in C++ code that
compiles and runs just fine, look for these kinds ofimplicit conversions.
serverApps.Start (Seconds (1.0));
serverApps.Stop (Seconds (10.0));
Above lines cause the echo server application to Start (enable itself) at one second into the simulation and to
Stop (disable itself) at ten seconds into the simulation. By virtue of the fact that we have declared a simulation
event (the application stop event) to be executed at ten seconds, the simulation will last at least tenseconds.
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 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.
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.
10.1.2.0
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 are created
InternetStackHelperstack;
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. 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
2. 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
------------------------ |----------------------------
10.1.1.0
point-to-point
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 15
CN LAB MANUAL 2023
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 16
CN LAB MANUAL 2023
pointToPoint.EnableAsciiAll(ascii.CreateFileStream("Tracefilewifides.tr"));
phy.EnableAsciiAll (ascii.CreateFileStream ("Tracefilewifisrc.tr"));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
Output
3. 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.
Overview:
Topology
n0 n1 n2 n3 n4 n5
| | | | | |
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");
NodeContainerc;
c.Create (6);
// add an ip stack to
allnodes. NS_LOG_INFO
("Add ip stack.");
InternetStackHelperipStac
k; ipStack.Install (c);
// assign ip addresses
NS_LOG_INFO ("Assign
ipaddresses.");
Ipv4AddressHelper ip;
ip.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer addresses = ip.Assign
//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"));
ApplicationContainerapp
s; 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.");
}
Noden1 sends ping message to n2 (Broadcast message is generated) and only n2 responds to n1
Noden0 sends ping message to n2 (Broadcast message is generated) and only n2 responds to n0
4. 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.
n0 n1 n2 n3
| | | |
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 PART B
PART-B
CN LAB MANUAL 2020
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., because
CN LAB MANUAL 2020
its initial value is zero.
● It requires no additional XOR operation after everything else is done. The CRC32 implementation used by
Ethernet, Pkzip, etc., requires this operation; less common 16-bit CRCs may require it as well.
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
CN LAB MANUAL 2020
Algorithm:-
1. Given a bit string, append 0S to the end of it (the number of 0s is the same as the degree of the generator
polynomial) let B(x) be the polynomial corresponding to B.
2. Divide B(x) by some agreed on polynomial G(x) (generator polynomial) and determine the remainder R(x). This
division is to be done using Modulo 2 Division.
3. Define T(x) = B(x) –R(x)
(T(x)/G(x) => remainder 0)
4. Transmit T, the bit string corresponding to T(x).
5. Let T’ represent the bit stream the receiver gets and T’(x) the associated polynomial. The receiver divides T1(x) by
G(x). If there is a 0 remainder, the receiver concludes T = T’ and no error occurred otherwise, the receiver concludes
an error occurred and requires a retransmission.
Division in CRC encoder
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
CN LAB MANUAL 2020
CRC code :
101100111
Enter CRC code of 9 bits
:1
1
1
1
0
0
1
0
1
No Error
THANKYOU ..... )
2. Write a program to find the shortest 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.
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();
}
prevDistanceVector = distanceVector.clone();
for (int j = 0; j < n; j++) {
double min = Double.POSITIVE_INFINITY; for (int
k = 0; k < n; k++) {
if (min >adjacencyMatrix[j][k] + prevDistanceVector[k]){
min = adjacencyMatrix[j][k] + prevDistanceVector[k];
}
}
distanceVector[j] = min;
}
}
}
}
OUTPUT
run:
Enter number of nodes
6
Enter Adjacency Matrix (Use 'Infinity' for NoLink)
0 3 2 5 9999
3 0 99 1 499
2 99 0 2 991
5 1 2 0 3 99
99 4 99 3 0 2
99 99 1 99 2 0
LEAKY BUCKETALGORITHM
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