Computer Network Lab Manual
Computer Network Lab Manual
Introduction to
NS-2
• Widely known as NS2, is simply an event driven simulationtool.
• Useful in studying the dynamic nature of communicationnetworks.
• Simulation of wired as well as wireless network functions and protocols (e.g., routing
algorithms, TCP, UDP) can be done usingNS2.
• Ingeneral,NS2providesuserswithawayofspecifyingsuchnetworkprotocolsandsimulating
their correspondingbehaviours.
Basic Architecture of NS2
Tcl scripting
• Tcl is a general purpose scripting language.[Interpreter]
• Tcl runs on most of the platforms such as Unix, Windows, andMac.
• The strength of Tcl is itssimplicity.
• It is not necessary to declare a data type for variable prior to theusage.
Basics of TCL
Syntax:command arg1 arg2 arg3
Hello World!
puts stdout{Hello,
World!} Hello, World!
Variables CommandSubstitution
seta5 set len [string lengthfoobar]
setb$a set len [expr [string length foobar] +9]
SimpleArithmetic
expr 7.2 / 4
Procedures
proc Diag {a b} {
set c [expr sqrt($a * $a + $b *
$b)] return $c }
puts “Diagonal of a 3, 4 right triangle is [Diag 3
4]” Output: Diagonal of a 3, 4 right triangle is 5.0
Loops
while{$i <$n} { for {set i 0} {$i < $n} {incr i}{
... ...
} }
Wired TCL Script Components
Create the eventscheduler
Open new files & turn on thetracing
Create thenodes
Setup thelinks
Configure the traffic type (e.g., TCP, UDP,etc)
Set the time of traffic generation (e.g., CBR,FTP)
Terminate thesimulation
NS Simulator Preliminaries.
1. Initialization and termination aspects of the nssimulator.
2. Definition of network nodes, links, queues andtopology.
3. Definition of agents and ofapplications.
4. The nam visualizationtool.
5. Tracing and randomvariables.
Initialization and Termination of TCL Script in NS-2
An ns simulation starts with the command
set ns [new Simulator]
Which is thus the first line in the tcl script? This line declares a new variable as using the set
command, you can call this variable as you wish, In general people declares it as ns becauseit
is an instance of the Simulator class, so an object the code[new Simulator] is indeed the
installation of the class Simulator using the reserved wordnew.
In order to have output files with data on the simulation (trace files) or files used for
visualization (nam files), we need to create the files using “open” command:
The above creates a data trace file called “out.tr” and a nam visualization trace file
called “out.nam”. Within the tcl script, these files are not called explicitly by their names, but
instead by pointers that are declared above and called “tracefile1” and “namfile” respectively.
Remark that they begins with a # symbol. The second line open the file “out.tr” to be used for
writing, declared with the letter “w”. The third line uses a simulator method called trace-all
that have as parameter the name of the file where the traces will go.
The last line tells the simulator to record all simulation traces in NAM input format. It
also gives the file name that the trace will be written to later by the command $ns flush-trace.
In our case, this will be the file pointed at by the pointer “$namfile”,i.e the file “out.tr”.
$ns flush-trace
Close $tracefile1
Close $namfile
Exit 0
The word proc declares a procedure in this case called finish and without arguments.
Thewordglobalisusedtotellthatweareusingvariablesdeclaredoutsidetheprocedure.The
simulator method “flush-trace” will dump the traces on the respective files. The tclcommand
“close” closes the trace files defined before and exec executes the nam program for
visualization. The command exit will ends the application and return the number 0 as statusto
the system. Zero is the default for a clean exit. Other values can be used to say that is a exit
because somethingfails.
Attheendofnsprogramweshouldcalltheprocedure“finish”andspecifyatwhattime the
termination should occur. Forexample,
$ns at 125.0 “finish”
will be used to call “finish” at time 125sec.Indeed, the at method of the simulator allows us to
schedule events explicitly.
The simulation can then begin using the command
$ns run
Definition of a network of links and nodes
The way to define a node is
set n0 [$ns node]
We created a node that is printed by the variable n0. When we shall refer to that node in the
script we shall thus write $n0.
Once we define several nodes, we can define the links that connect them. An example
of a definition of a link is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms
of propagation delay and a capacity of 10Mb per sec for each direction.
To define a directional link instead of a bi-directional one, we should replace “duplex-
link” by “simplex-link”.
In NS, an output queue of a node is implemented as a part of each link whose input is
that node. The definition of the link then includes the way to handle overflow at that queue.In
our case, if the buffer capacity of the output queue is exceeded then the last packet to arrive is
dropped.Manyalternativeoptionsexist,suchastheRED(RandomEarlyDiscard)mechanism, the
FQ (Fair Queuing), the DRR (Deficit Round Robin), the stochastic Fair Queuing (SFQ) and
the CBQ (which including a priority and a round-robinscheduler).
In ns, an output queue of a node is implemented as a part of each link whose input is
that node. We should also define the buffer capacity of the queue related to each link. An
example would be:
#set Queue Size of link (n0-n2) to 20
Defines the behaviour of the destination node of TCP and assigns to it a pointer called sink.
#Setup a UDP connection
set udp [new Agent/UDP]
Scheduling Events
NSisadiscreteeventbasedsimulation.Thetcpscriptdefineswheneventshouldoccur. The
initializing command set ns [new Simulator] creates an event scheduler, and events are then
scheduled using theformat: $ns at <time><event>
The scheduler is started when running ns that is through the command $ns run.
The beginning and end of the FTP and CBR application can be done through the following
command
Event Time From To PKT PKT Flags Fid Src Dest Seq Pkt
Node Node Type Size Addr Addr Num id
1. The first field is the event type. It is given by one of four possible symbols r, +, -, d which
correspond respectively to receive (at the output of the link), enqueued, dequeued and
dropped.
2. The second field gives the time at which the eventoccurs.
3. Gives the input node of the link at which the eventoccurs.
4. Gives the output node of the link at which the eventoccurs.
Dept of CSE, RRCE. Page 5
COMPUTER NETWORKS LABORATORY 2019 - 20
XGRAPH
Thexgraphprogramdrawsagraphonanx-displaygivendatareadfromeitherdatafile or
from standard input if no files are specified. It can display upto 64 independent data sets
usingdifferentcolorsandlinestylesforeachset.Itannotatesthegraphwithatitle,axislabels, grid
lines or tick marks, grid labels and alegend.
Syntax:
Xgraph [options] file-name
Options are listed here
/-bd <color> (Border)
This specifies the border color of the xgraph window.
/-bg <color> (Background)
This specifies the background color of the xgraph window.
/-fg<color> (Foreground)
This specifies the foreground color of the xgraph window.
/-lf <fontname> (LabelFont)
All axis labels and grid labels are drawn using this font.
/-t<string> (Title Text)
This string is centered at the top of the graph.
/-x <unit name> (XunitText)
This is the unit name for the x-axis. Its default is “X”.
/-y <unit name> (YunitText)
This is the unit name for the y-axis. Its default is “Y”.
Awk- An Advanced
awk is a programmable, pattern-matching, and processing tool available in UNIX. It
works equally well with text and numbers.
awkisnotjustacommand,butaprogramminglanguagetoo.Inotherwords,awkutility
isapatternscanningandprocessinglanguage.Itsearchesoneormorefilestoseeiftheycontain
linesthatmatchspecifiedpatternsandthenperformassociatedactions,suchaswritingtheline to the
standard output or incrementing a counter each time it finds amatch.
Syntax: awk option ‘selection_criteria {action}’ file(s)
Here, selection_criteria filters input and select lines for the action component to act
upon. The selection_criteria is enclosed within single quotes and the action within the curly
braces. Both the selection_criteria and action forms an awk program.
Example: $ awk ‘/manager/ {print}’ emp.lst
Variables
Awkallowstheusertousevariablesoftherechoice.Youcannowprintaserialnumber, using
Dept of CSE, RRCE. Page 6
COMPUTER NETWORKS LABORATORY 2019 - 20
the variable kount, and apply it those directors drawing a salary exceeding6700:
$ awk –F”|” ‘$3 == “director” && $6 > 6700 {
count =count+1
printf “ %3f %20s %-12s %d\n”, count,$2,$3,$6 }’ empn.lst
THE –f OPTION: STORING awk PROGRAMS INA FILE
You should holds large awk programs in separate file and provide them with the awk
extension for easier identification. Let’s first store the previous program in the file
empawk.awk:
$ cat empawk.awk
Observe that this time we haven’t used quotes to enclose the awk program. You can
now use awk with the –f filename option to obtain the same output:
Awk –F”|” –f empawk.awk empn.lst
With FILENAME, you can device logic that does different things depending on the file that is
processed.
NS2 Installation
• NS2 is a free simulationtool.
• It runs on various platforms including UNIX (or Linux), Windows, and Macsystems.
• NS2 source codes are distributed in two forms: the all-in-one suite and the component-
wise.
• ‘all-in-one’packageprovidesan“install”scriptwhichconfigurestheNS2environmentand
creates NS2 executable file using the “make”utility.
NS-2 installation steps in Linux
➢ Go to Computer File System now paste the zip file “ns-allinone-2.34.tar.gz” into
optfolder.
➢ Now unzip the file by typing the followingcommand
[root@localhost opt] # tar -xzvfns-allinone-2.34.tar.gz
➢ After the files get extracted, we get ns-allinone-2.34 folder as well as zip file ns-allinone-
2.34.tar.gz
[root@localhost opt]#ns-allinone-2.34 ns-allinone-2.34.tar.gz
➢ Now go to ns-allinone-2.33 folder and install
it [root@localhost opt] # cd ns-allinone-2.34
[root@localhost ns-allinone-2.33] #./install
➢ Once the installation is completed successfully we get certain pathnames in that terminal
which must be pasted in “.bash_profile”file.
➢ Firstminimizetheterminalwhereinstallationisdoneandopenanewterminalandopen the
file“.bash_profile”
[root@localhost ~] # vi.bash_profile
➢ When we open this file, we get a line in that file which is shownbelow
PATH=$PATH:$HOME/bin
To this line we must paste the path which is present in the previous terminal where ns was
installed. First put “:” then paste the path in-front of bin. That path is shown below.
“:/opt/ns-allinone-2.33/bin:/opt/ns-allinone-2.33/tcl8.4.18/unix:/opt/ns-allinone-
2.33/tk8.4.18/unix”.
➢ In the next line type “LD_LIBRARY_PATH=$LD_LIBRARY_PATH:” and paste the
two paths separated by “:” which are present in the previous terminal i.e Important notices
section(1)
“/opt/ns-allinone-2.33/otcl-1.13:/opt/ns-allinone-2.33/lib”
➢ In the next line type “TCL_LIBRARY=$TCL_LIBRARY:” and paste the path which is
present in previous terminal i.e Important Notices section(2)
“/opt/ns-allinone-2.33/tcl8.4.18/library”
➢ In the next line type “exportLD_LIBRARY_PATH”
➢ In the next line type “exportTCL_LIBRARY”
➢ The next two lines are already present the file “export PATH” and “unsetUSERNAME”
➢ Save the program ( ESC + shift : wq and press enter)
➢ Nowintheterminalwherewehaveopened.bash_profilefile,typethefollowingcommand to
check if path is updated correctly ornot
[root@localhost ~] # vi.bash_profile
[root@localhost ~] # source.bash_profile
➢ If path is updated properly, then we will get the prompt as shown
below [root@localhost ~]#
➢ Now open the previous terminal where you have installedns
[root@localhost ns-allinone-2.33] #
➢ Here we need to configure three packages “ns-2.33”, “nam-1.13” and“xgraph-12.1”
Dept of CSE, RRCE. Page 8
COMPUTER NETWORKS LABORATORY 2019 - 20
PART-A
1. Implementthreenodespoint–to–pointnetworkwithduplexlinksbetweenthem.Set the
queue size, vary the bandwidth and find the number of packetsdropped.
proc finish {} { /* provide space b/w proc and finish and all are in smallcase*/
global ns nftf
$nsflush-trace /* clears trace filecontents*/
close$nf
close $tf
exec nam lab1.nam &
exit 0
}
$ns duplex-link $n0 $n2 200Mb 10ms DropTail /*Letter M is capital Mb*/
$ns duplex-link $n1 $n2 100Mb 5ms DropTail /*D and T are capital*/
$ns duplex-link $n2 $n3 1Mb 1000ms DropTail
$ns run
AWK file (Open a new editor using “vi command” and write awk file and save with
“.awk” extension)
/*immediately after BEGIN should open braces ‘{‘
BEGIN {
c=0;
}
{
If ($1= ="d")
{
c++;
printf("%s\t%s\n",$5,$11);
}
}
/*immediately after END should open braces ‘{‘
END{
printf("The number of packets dropped =%d\n",c);
}
[root@localhost~]# vi lab1.tr
Output
Note:
1. Set the queue size fixed from n0 to n2 as 10, n1-n2 to 10 and from n2-n3 as5.
Syntax: To set the queuesize
$ns set queue-limit <from><to><size> Eg:
$ns set queue-limit $n0 $n2 10
2. Go on varying the bandwidth from 10, 20 30 . . and find the number of packets
dropped at the node2
AWK file (Open a new editor using “vi command” and write awk file and save
with “.awk” extension)
BEGIN{
drop=0;
}
{
if($1= ="d" )
{
drop++;
}
}
END{
printf("Total number of %s packets dropped due to congestion =%d\n",$5,drop);
}
Steps for execution
1) Open vi editor and type program. Program name should have the extension “ .tcl”
[root@localhost ~]# vi lab2.tcl
2) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enterkey.
3) Open vi editor and type awk program. Program name should have the extension
“.awk”
[root@localhost ~]# vi lab2.awk
4) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enterkey.
5) Run the simulationprogram
[root@localhost~]# ns lab2.tcl
i) Here “ns” indicates network simulator. We get the topology shown in the
snapshot.
ii) Now press the play button in the simulation window and the simulation will
begins.
6) After simulation is completed run awk file to see the output,
[root@localhost~]# awk –f lab2.awklab2.tr
7) To see the trace file contents open the file as,
[root@localhost~]# vi lab2.tr
Topology
Output
Note:
Vary the bandwidth and queue size between the nodes n0-n2 , n2-n4. n6-n2 and n2- n5
and see the number of packets dropped at the nodes.
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source /destination.
set ns [new Simulator]
set tf [open lab3.tr w]
$ns trace-all $tf
set nf [open lab3.nam w]
$ns namtrace-all $nf
$ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/DropTail Mac/802_3
/* should come in single line */
$ns duplex-link $n4 $n5 1Mb 1ms DropTail
$tcp0 trace cwnd_ /* must put underscore ( _ ) after cwnd and no space between
them*/
$tcp2 trace cwnd_
proc finish { } {
global ns nf tf
$ns flush-trace
close $tf
close $nf
exec nam lab3.nam &
exit 0
}
$ns at 0.1 "$ftp0 start"
$ns at 5 "$ftp0 stop"
$ns at 7 "$ftp0 start"
$ns at 0.2 "$ftp2 start"
$ns at 8 "$ftp2 stop"
$ns at 14 "$ftp0 stop"
$ns at 10 "$ftp2 start"
$ns at 15 "$ftp2 stop"
$ns at 16 "finish"
$ns run
AWK file (Open a new editor using “vi command” and write awk file and save with
“.awk” extension)
BEGIN {
}
{
if($6= ="cwnd_") /* don’t leave space after writing cwnd_ */
printf("%f\t%f\t\n",$1,$7); /* you must put \n in printf */
}
END {
}
Steps for execution
1) Open vi editor and type program. Program name should have the extension “ .tcl”
[root@localhost ~]# vi lab3.tcl
2) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enterkey.
3) Open vi editor and type awk program. Program name should have the extension
“.awk”
[root@localhost ~]# vi lab3.awk
4) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
Dept of CSE, RRCE. Page 20
COMPUTER NETWORKS LABORATORY 2019 - 20
Output
4. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation
and determine the performance with respect to transmission ofpackets.
set ns [new Simulator]
set tf [open lab4.tr w]
$ns trace-all $tf
set topo [new Topography]
$topo load_flatgrid 1000 1000
set nf [open lab4.nam w]
$ns namtrace-all-wireless $nf 1000 1000
$ns node-config -adhocRouting DSDV \
-llType LL \
-macType Mac/802_11 \
-ifqType Queue/DropTail \
-ifqLen 50 \
-phyType Phy/WirelessPhy \
-channelType Channel/WirelessChannel \
-propType Propagation/TwoRayGround \
-antType Antenna/OmniAntenna \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON
create-god 3
set n0 [$ns node]
$n0 set X_ 50
$n0 set Y_ 50
$n0 set Z_ 0
$n1 set X_ 100
$n1 set Y_ 100
$n1 set Z_ 0
$n2 set X_ 600
$n2 set Y_ 600
$n2 set Z_ 0
$ns at 0.1 "$n0 setdest 50 50 15"
$ns at 0.1 "$n1 setdest 100 100 25"
$ns at 0.1 "$n2 setdest 600 600 25"
AWK file (Open a new editor using “vi command” and write awk file and save with
“.awk” extension)
BEGIN{
count1=0
count2=0
pack1=0
pack2=0
time1=0
time2=0
}
{
if($1= ="r"&& $3= ="_1_" && $4= ="AGT")
{
count1++
pack1=pack1+$8
time1=$2
}
if($1= ="r" && $3= ="_2_" && $4= ="AGT")
{
count2++
pack2=pack2+$8
time2=$2
}
}
END{
printf("The Throughput from n0 to n1: %f Mbps \n”, ((count1*pack1*8)/(time1*1000000)));
printf("The Throughput from n1 to n2: %f Mbps", ((count2*pack2*8)/(time2*1000000)));
}
Steps for execution
1) Open vi editor and type program. Program name should have the extension “ .tcl”
[root@localhost ~]# vi lab4.tcl
2) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enterkey.
3) Open vi editor and type awk program. Program name should have the extension
“.awk”
[root@localhost ~]# vi lab4.awk
4) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enterkey.
5) Run the simulationprogram
[root@localhost~]# ns lab4.tcl
i) Here “ns” indicates network simulator. We get the topology shown in the
snapshot.
ii) Now press the play button in the simulation window and the simulation
willbegins.
6) After simulation is completed run awk file to see the output,
[root@localhost~]# awk –f lab4.awklab4.tr
7) To see the trace file contents open the file as,
[root@localhost~]# vi lab4.tr
Dept of CSE, RRCE. Page 24
COMPUTER NETWORKS LABORATORY 2019 - 20
Topology
Trace file
Here “M” indicates mobile nodes, “AGT” indicates Agent Trace, “RTR” indicates Router
Trace
Output
5. Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or
equivalentenvironment.
SecondGeneration(2G)technologyisbasedonthetechnologyknownasglobalsystem for
mobile communication (GSM). This technology enabled various networks to provide
servicesliketextmessages,picturemessagesandMMS.Thetechnologiesusedin2Gareeither
TDMA (Time Division Multiple Access) which divides signal into different time slots
or CDMA (Code Division Multiple Access) which allocates a special code to each user so as
to communicate over a multiplex physicalchannel.
GSM uses a variation of time division multiple access (TDMA). 2G networks
developed as a replacement for first generation (1G) analog cellular networks, and the GSM
standard originally described as a digital, circuit-switched network optimized for fullduplex
voice telephony. This expanded over time to include data communications, first by circuit-
switched transport, then by packet data transport via GPRS (General Packet Radio Services).
GSM can be implemented on all the versions of NS2 (Since year 2004: ns-2.27, and later
versions of NS2)
Design:
Source Code:
# General Parameters
set opt(title) zero ;
set opt(stop) 100 ;# Stop time.
set opt(ecn) 0 ;
# Topology
set opt(type) gsm ;#type of link:
set opt(secondDelay) 55 ;# average delay of access links in ms
# AQM parameters
set opt(minth) 30 ;
set opt(maxth) 0 ;
set opt(adaptive) 1 ;# 1 for Adaptive RED, 0 for plain RED
# Traffic generation.
set opt(flows) 0 ;# number of long-lived TCP flows
set opt(window) 30 ;# window for long-lived traffic
set opt(web) 2 ;# number of web sessions
# Plotting statistics.
set opt(quiet) 0 ;# popup anything
set opt(wrap) 100 ;# wrap plots
set opt(srcTrace) is ;# where to plot traffic
set opt(dstTrace) bs2 ;# where to plot traffic
set opt(gsmbuf) 10 ; # buffer size for gsm
proc cell_topo {} {
global ns nodes
$ns duplex-link $nodes(lp) $nodes(bs1) 3Mbps 10ms DropTail
$ns duplex-link $nodes(bs1) $nodes(ms) 1 1 RED
$ns duplex-link $nodes(ms) $nodes(bs2) 1 1 RED
$ns duplex-link $nodes(bs2) $nodes(is) 3Mbps 50ms DropTail
puts "Cell Topology"
}
}
# RED and TCP parameters
Queue/RED set summarystats_ true
Queue/DropTail set summarystats_ true
Queue/RED set adaptive_ $opt(adaptive)
Queue/RED set q_weight_ 0.0
Queue/RED set thresh_ $opt(minth)
Queue/RED set maxthresh_ $opt(maxth)
Queue/DropTail set shrink_drops_ true
Agent/TCP set ecn_ $opt(ecn)
Agent/TCP set window_ $opt(window)
DelayLink set avoidReordering_ true
source web.tcl
#Create topology
switch $opt(type) {
gsm -
gprs -
umts {cell_topo}
}
set_link_params $opt(type)
$ns insert-delayer $nodes(ms) $nodes(bs1) [new Delayer]
$ns insert-delayer $nodes(bs1) $nodes(ms) [new Delayer]
$ns insert-delayer $nodes(ms) $nodes(bs2) [new Delayer]
$ns insert-delayer $nodes(bs2) $nodes(ms) [new Delayer]
proc stop {} {
Output:
6. ImplementandstudytheperformanceofCDMAonNS2/NS3(UsingstackcalledCall net)
or equivalentenvironment.
CDMA can be implemented on all the versions of NS2 (Since year 2004: ns-2.27, and later
versions of NS2)
Design:
Source Code:
# General Parameters
set opt(title) zero ;
set opt(stop) 100 ;# Stop time.
set opt(ecn) 0 ;
# Topology
set opt(type) umts ;#type of link:
set opt(secondDelay) 55 ;# average delay of access links in ms
# AQM parameters
set opt(minth) 30 ;
set opt(maxth) 0 ;
set opt(adaptive) 1 ;# 1 for Adaptive RED, 0 for plain RED
# Traffic generation.
set opt(flows) 0 ;# number of long-lived TCP flows
set opt(window) 30 ;# window for long-lived traffic
set opt(web) 2 ;# number of web sessions
# Plotting statistics.
set opt(quiet) 0 ;# popup anything
set opt(wrap) 100 ;# wrap plots
set opt(srcTrace) is ;# where to plot traffic
set opt(dstTrace) bs2 ;# where to plot traffic
set opt(umtsbuf) 10 ; # buffer size for umts
#default downlink bandwidth in bps
set bwDL(umts) 384000
#default uplink bandwidth in bps
set bwUL(umts) 64000
#default downlink propagation delay in seconds
set propDL(umts) .150
#default uplink propagation delay in seconds
set propUL(umts) .150
#default buffer size in packets
set buf(umts) 20
proc cell_topo {} {
global ns nodes
$ns duplex-link $nodes(lp) $nodes(bs1) 3Mbps 10ms DropTail
$ns duplex-link $nodes(bs1) $nodes(ms) 1 1 RED
$ns duplex-link $nodes(ms) $nodes(bs2) 1 1 RED
$ns duplex-link $nodes(bs2) $nodes(is) 3Mbps 50ms DropTail
puts "Cell Topology"
}
Dept of CSE, RRCE. Page 33
COMPUTER NETWORKS LABORATORY 2019 - 20
source web.tcl
#Create topology
switch $opt(type) {
umts {cell_topo}
}
set_link_params $opt(type)
$ns insert-delayer $nodes(ms) $nodes(bs1) [new Delayer]
$ns insert-delayer $nodes(bs1) $nodes(ms) [new Delayer]
$ns insert-delayer $nodes(ms) $nodes(bs2) [new Delayer]
$ns insert-delayer $nodes(bs2) $nodes(ms) [new Delayer]
Output:
PART-B
Java is a general-purpose computer programming languagethat is simple,
concurrent,class-based,object-oriented language. The compiled Java code can run on all
platforms that support Java without the need for recompilation hence Java is called as
"writeonce, run anywhere" (WORA).The Java compiled intermediate output called “byte-
code” that can run on any Java virtual machine (JVM) regardless of computer architecture.
The language derives much of its syntax from C and C++, but it has fewer low-level facilities
than either of them.
In Linux operating system Java libraries are preinstalled. It’s very easy and convenient
to compile and run Java programs in Linux environment. To compile and run Java Program
is a two-step process:
The Java compiler (Javac) compiles java program and generates a byte-code with the
same file name and .class extension.
2. Run Java program from CommandPrompt
[root@host ~]# java Filename
The java interpreter (Java) runs the byte-code and gives the respective output. It is
important to note that in above command we have omitted the .class suffix of thebyte-
code(Filename.class).
Whenever digital data is stored or interfaced, data corruption might occur. Since the
beginning of computer science, developers have been thinking of ways to deal with this type
of problem. For serial data they came up with the solution to attach a parity bit to each sent
byte. This simple detection mechanism works if an odd number of bits in a byte changes, but
an even number of false bits in one byte will not be detected by the parity check .To over
come this problem developers have searched for mathematical sound mechanisms to detect
multiple false bits. The CRC calculation or cyclic redundancy check was the result of this.
Nowadays CRC calculations are used in all types of communications. All packets sent over a
network connection are checked with a CRC. Also each data block on your hard disk has a
CRC value attached to it. Modern computer world cannot do without these CRC calculations.
So let's see why they are so widely used. The answer is simple; they are powerful, detect
many types of errors and are extremely fast to calculate especially when dedicated hardware
chips are used.
With decimal calculations you can quickly check that 109 divided by 19 gives a quotient of 5
with 14 as the remainder. But what we also see in the scheme is that every bit extra to check
only costs one binary comparison and in 50% of the cases one binary subtraction. You can
easily increase the number of bits of the test data string—for example to 56 bits if we use our
example value "Lammert"—and the result can be calculated with56binary comparisons and
an average of 28 binary subtractions. This can be implemented in hardware directly with only
very few transistors involved .Also software algorithms can be very efficient.
All of the CRC formulas you will encounter are simply checksum algorithms based
on modulo-2 binary division where we ignore carry bits and in effect the subtraction will be
equal to an exclusive or operation. Though some differences exist in the specifics across
different CRC formulas, the basic mathematical process is always the same:
The message bits are appended with c zero bits; this augmented message is the dividend
A predetermined c+1-bit binary sequence, called the generator polynomial, is the divisor
The checksum is the c-bit remainder that results from the division operation
Table 1 lists some of the most commonly used generator polynomials for 16- and 32-bit CRCs.
Remember that the width of the divisor is always one bit wider than the remainder. So, for example,
you’d use a 17-bit generator polynomial whenever a 16-bit checksum is required.
Checksum
16 bits 16 bits 32 bits
Width
Generator
10001000000100001 11000000000000101 100000100110000010001110110110111
Polynomial
Source Code:
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;
System.out.println("Enter number of data bits : ");
data_bits=Integer.parseInt(br.readLine());
data=new int[data_bits];
System.out.println("Enter data bits : ");
for(int i=0; i<data_bits; i++)
data[i]=Integer.parseInt(br.readLine());
System.out.println("Enter number of bits in divisor : ");
divisor_bits=Integer.parseInt(br.readLine());
divisor=new int[divisor_bits];
System.out.println("Enter Divisor bits : ");
for(int i=0; i<divisor_bits; i++)
divisor[i]=Integer.parseInt(br.readLine());
/* System.out.print("Data bits
are:");for(int i=0; i< data_bits;i++)
System.out.print(data[i]);
System.out.println();
System.out.print("divisor bits are : ");
for(int i=0; i< divisor_bits; i++)
System.out.print(divisor[i]);
System.out.println();
*/ tot_length=data_bits+divisor_bits-1;
div=newint[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];
/* System.out.print("crc bits
are:");for(int i=0; i< crc.length;i++)
System.out.print(crc[i]);
System.out.println();
*/
for(int j=0; j<crc.length; j++){
rem[j] = crc[j];
}
if((rem.length-cur)<divisor.length)
break;
}
return rem;
}
}
Output:
[root@localhost ~]# vi Crc.java
2. Write a program to find the shortest path between vertices using bellman-ford
algorithm.
Distance Vector Algorithm is a decentralized routing algorithm that requires that each
router simply inform its neighbors of its routing table. For each network path, the receiving
routers pick the neighbor advertising the lowest cost, then add this entry into its routing table
for re-advertisement. To find the shortest path, Distance Vector Algorithm is based on one of
two basic algorithms: the Bellman-Ford and the Dijkstra algorithms.
Routers that use this algorithm have to maintain the distance tables (which is a one-
dimension array -- "a vector"), which tell the distances and shortest path to sending packets to
each node in the network. The information in the distance table is always update by
exchanging information with the neighboring nodes. The number of data in the table equals to
that of all nodes in networks (excluded itself). The columns of table represent the directly
attached neighbors whereas the rows represent all destinations in the network. Each data
contains the path for sending packets to each destination in the network and distance/or time
to transmit on that path (we call this as "cost"). The measurements in this algorithm are the
number of hops, latency, the number of outgoing packets, etc.
The Bellman–Ford algorithm is an algorithm that computes shortest paths from a single
source vertex to all of the other vertices in a weighted digraph. It is slower than Dijkstra's
algorithm for the same problem, but more versatile, as it is capable of handling graphs in
which some of the edge weights are negative numbers. Negative edge weights are found in
various applications of graphs, hence the usefulness of this algorithm. If a graph contains a
"negative cycle"(i.e.a cycle whose edges sum to a negative value) that is reachable from the
source, then there is no cheapest path: any path that has a point on the negative cycle can be
made cheaper by one more walk around the negative cycle. In such a case, the Bellman–Ford
algorithm can detect negative cycles and report their existence
Source code:
import java.util.Scanner;
}
D[source] = 0;
for (int node = 1; node <= num_ver - 1; node++)
{
for (int sn = 1; sn <= num_ver; sn++)
{
for (int dn = 1; dn <= num_ver; dn++)
{
if (A[sn][dn] != MAX_VALUE)
{
if (D[dn] > D[sn]+ A[sn][dn])
D[dn] = D[sn] + A[sn][dn];
}
}
}
}
for (int sn = 1; sn <= num_ver; sn++)
{
for (int dn = 1; dn <= num_ver; dn++)
{
if (A[sn][dn] != MAX_VALUE)
{
if (D[dn] > D[sn]+ A[sn][dn])
System.out.println("The Graph contains negative egde cycle");
}
}
}
for (int vertex = 1; vertex <= num_ver; vertex++)
{
System.out.println("distance of source " + source + " to "+ vertex + "
is " + D[vertex]);
}
}
A[sn][dn] = scanner.nextInt();
if (sn == dn)
{
A[sn][dn] = 0;
continue;
}
if (A[sn][dn] == 0)
{
A[sn][dn] = MAX_VALUE;
}
}
}
System.out.println("Enter the source vertex");
source = scanner.nextInt();
BellmanFord b = new BellmanFord (num_ver);
b.BellmanFordEvaluation(source, A);
scanner.close();
}
}
Input graph:
5
A B
3
4
C D
2
Output:
3. 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.
Implement the above program using as message queues or FIFOs as IPC channels.
Socket is an interface which enables the client and the server to communicate and
pass on information from one another. Sockets provide the communication mechanism
between two computers using TCP. A client program creates a socket on its end of the
communication and attempts to connect that socket to a server. When the connection is
made,the server creates socket object on it send of the communication. The client and the
server can now communicate by writing to and reading from the socket.
Source Code:
TCP Client
tcpclient.java
import java.io.*;
import java.net.*;
public class tcpclient
{
public static void main( String args[ ])throws Exception
{
Socket sock = new Socket( "127.0.0.1", 8080);
if(!f.exists()||f.isDirectory())
System.exit(0);
System.out.println("Content of File");
System.out.println("---------------\n");
String str;
// reading line-by-line
while((str = socketRead.readLine()) != null)
{
System.out.println(str);
}
TCP SERVER
tcpserver.java
import java.net.*;
import java.io.*;
public class tcpserver
{
public static void main(String[] args) throws Exception
{
if(!f.exists())
System.exit(0);
String str;
while((str = contentRead.readLine()) != null)
{
pwrite.println(str);
}
System.out.println("Request closed");
sock.close();
sersock.close();
pwrite.close();
fileRead.close();
contentRead.close();
}
Note: Create two different files Client.java and Server.java. Follow the steps given:
1. Open a terminal run the server program and provide the filename to send
2. Open one more terminal run the client program and provide the IP address of the
server. We can give local host address “127.0.0.1” as it is running on same
machine or give the IP address of the machine.
3. Send any start bit to start sending file.
4. Refer https://www.tutorialspoint.com/java/java_networking.htm for all the
parameters, methods description in socket communication.
Output:
Source Code:
UDP Client
dataclient.java
import java.net.*;
public class dataclient
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}
UDP Server
dataserver.java
import java.net.*;
import java.util.Scanner;
public class dataserver
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();
System.out.println("Enter the Message");
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
ds.send(dp);
ds.close();
}
}
Note: Create two different files UDPC.java and UDPS.java. Follow the following steps:
1. Open a terminal run the server program.
2. Open one more terminal run the client program, the sent message will be
received.
OUTPUT:
5. Write a program for simple RSA algorithm to encrypt and decrypt thedata.
The RSA algorithm's efficiency requires a fast method for performing the
modular exponentiation operation. A less efficient, conventional method includes
raising a number (the input) to a power (the secret or public key of the algorithm,
denoted e and d, respectively) and taking the remainder of the division with N. A
straight-forward implementation performs these two steps of the operation
sequentially: first, raise it to the power and second, apply modulo. The RSA
algorithm comprises of three steps, which are depicted below:
Encryption
Sender A does the following:-
Decryption
Recipient B does the following:-
Source Code:
RSA Key Generation
import java.util.Scanner;
while(y!=0)
{
r=x%y;
x=y;
y=r;
}
return x;
}
public static void encrypt()
{
int i;
long c=1;
for(i=0;i<e;i++)
{
c=c*m%n;
}
System.out.println("\n \t encrypted:"+ c);
}
public static void decrypt()
{
int i;
long m=1;
for(i=0;i<d;i++)
{
m=m*c%n;
}
System.out.println("\n \t decrypted keyword:"+m);
}
for(i=2;i<phi;i++)
if(gcd(i,phi)==1)
break;
e=i;
System.out.println("\n The value of e(public key)="+e);
for(i=2;i<phi;i++)
if((i*e - 1)%phi==0)
break;
d=i;
System.out.println("\n The value of d(private key)="+ d);
System.out.println("\n Enter the plain text:");
m=sc.nextLong();
encrypt();
System.out.println("\n Enter cipher text:\t");
c=sc.nextLong();
decrypt();
sc.close();
}
}
Output:
The main concept of the leaky bucket algorithm is that the output data flow remains
constant despite the variant input traffic, such as the water flow in a bucket with a small hole
at the bottom. In case the bucket contains water (or packets) then the output flow follows a
constant rate, while if the bucket is full any additional load will be lost because of spill over.
In a similar way if the bucket is empty the output will be zero.
From network perspective, leaky bucket consists of a finite queue (bucket) where all the
incoming packets are stored in case there is space in the queue, otherwise the packets are
discarded. In order to regulate the output flow, leaky bucket transmits one packet from the
queue in a fixed time (e.g. at every clock tick).In the following figure we can notice the main
rationale of leaky bucket algorithm, for both the two approaches (e.g. leaky bucket with water
(a) and with packets(b)).
While leaky bucket eliminates completely bursty traffic by regulating the incoming
data flow its main drawback is that it drops packets if the bucket is full. Also, it doesn’t take
into account the idle process of the sender which means that if the host doesn’t transmit data
for some time the bucket becomes empty without permitting the transmission of any packet.
Source Code:
import java.util.Scanner;
import java.util.*;
public class leaky {
public static int bucketsize=512;
public static void bktinput(int pktsize, int op)throws Interrupted Exception
{
if(pktsize > bucketsize)
System.out.println("\n packet discarded");
else
{
while(pktsize>op)
{
Thread.sleep(100);
System.out.println("\n bytes outputted"+ op);
pktsize = pktsize - op;
}
if(pktsize > 0)
System.out.println("\n last"+pktsize+" bytes sent");
System.out.println("\n bucket outputted scccessful\n");
}
}
OUTPUT: