CN Lab Manual FINAL 2018
CN Lab Manual FINAL 2018
CN Lab Manual FINAL 2018
A
MANUAL FOR
COMPUTER NETWORKS LAB
(15CSL57)
V SEMESTER
Prepared By:
Mrs. Mala B A & Mrs. R Amutha
A.P, Dept., of ISE, AMCEC
COMPUTER NETWORK LABORATORY 15CSL57
Program Outcomes(Pos)
Engineering Graduates will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
COURSE OUTCOMES
The students should be :
CO1: Able to Analyze the working of networking protocols using modern tool NS2.
CO2: Able to Develop wired and wireless topology using XGraph, NAM in NS2.
CO3: Able to Simulate and demonstrate the performance of GSM and CDMA.
CO4: Able to Apply and develop the algorithms in data link layer, Network layer and application
layer.
CO5: Able to Design client-server applications using TCP and UDP socket IPC.
PART A
For the experiments below modify the topology and parameters set for the experiment and take
multiple rounds of reading and analyze the results available in log files. Plot necessary graphs
and conclude. Use 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.
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and 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 transmission of packets.
5. Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or equivalent
environment.
6. Implement and study the performance of CDMA on NS2/NS3 (Using stack called Call net) or
equivalent environment
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-ford
Algorithm.
9. Using TCP/IP sockets, write a client – server program to make the client send the file name
and to make the server send back the contents of the requested file if present.
10. Write a program on datagram socket for client/server to display the messages on client side,
typed at the server side.
11. Write a program for simple RSA algorithm to encrypt and decrypt the data.
12. Write a program for congestion control using leaky bucket algorithm
TABLE OF CONTENTS
1. LAB SYLLABUS 5
2. PROGRAM NO 1 19
3. PROGRAM NO 2 22
4. PROGRAM NO 3 26
5. PROGRAM NO 4 29
6. PROGRAM NO 5 33
7. PROGRAM NO 6 38
8. PROGRAM NO 7 43
9. PROGRAM NO 8 47
10. PROGRAM NO 9 50
11. PROGRAM NO 10 52
12. PROGRAM NO 11 54
13. PROGRAM NO 12 56
Introduction to NS-2
Tcl scripting
• Tcl is a general purpose scripting language. [Interpreter]
• Tcl runs on most of the platforms such as Unix, Windows, and Mac.
• The strength of Tcl is its simplicity.
• It is not necessary to declare a data type for variable prior to the usage.
Basics of TCL
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello, World!}
Hello, World!
Variables Command Substitution
set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]
Simple Arithmetic
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} {
... ...
} }
NS Simulator Preliminaries.
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.
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 because it 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 word new.
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”.
The termination of the program is done using a “finish” procedure.
$ns flush-trace
Close $tracefile1
Close $namfile
The word proc declares a procedure in this case called finish and without arguments. The
word global is used to tell that we} are using variables declared outside the procedure. The simulator
method “flush-trace” will dump the traces on the respective files. The tcl command “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 status to the system. Zero is the default for
}
a clean exit. Other values can be used to say that is a exit because something fails.
At the end of ns program we should call the procedure “finish” and specify at what time the
termination should occur. For example,
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
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. Many
alternative options exist, such as the RED (Random Early Discard) 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-robin scheduler).
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
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
Defines the behaviour of the destination node of TCP and assigns to it a pointer called sink.
$ns connect $tcp $sink finally makes the TCP connection between the source and destination nodes.
TCP has many parameters with initial fixed defaults values that can be changed if mentioned
explicitly. For example, the default TCP packet size has a size of 1000bytes.This can be changed to
another value, say 552bytes, using the command $tcp set packetSize_ 552.
When we have several flows, we may wish to distinguish them so that we can identify them with
different colors in the visualization part. This is done by the command $tcp set fid_ 1 that assigns
to the TCP connection a flow identification of “1”.We shall later give the flow identification of
“2” to the UDP connection.
Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event should occur.
The initializing command set ns [new Simulator] creates an event scheduler, and events are then
scheduled using the format: $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
$ns at 0.1 “$cbr start”
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. Gives the packet type (eg CBR or TCP)
3. Gives the packet size
4. Some flags
5. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script one can
further use this field for analysis purposes; it is also used when specifying stream color for the
NAM display.
6. This is the source address given in the form of “node.port”.
7. This is the destination address, given in the same form.
8. This is the network layer protocol’s packet sequence number. Even though UDP
implementations in a real network do not use sequence number, ns keeps track of UDP
XGRAPH
The xgraph program draws a graph on an x-display given data read from either data file or
from standard input if no files are specified. It can display upto 64 independent data sets using
different colors and line styles for each set. It annotates the graph with a title, axis labels, grid lines or
tick marks, grid labels and a legend.
/-fg<color> (Foreground)
This specifies the foreground color of the xgraph window.
Awk- An Advanced
awk is a programmable, pattern-matching, and processing tool available in UNIX. It works
equally well with text and numbers.
awk is not just a command, but a programming language too. In other words, awk utility is a
pattern scanning and processing language. It searches one or more files to see if they contain lines that
match specified patterns and then perform associated actions, such as writing the line to the standard
output or incrementing a counter each time it finds a match.
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
Awk allows the user to use variables of there choice. You can now print a serial number, using
the variable kount, and apply it those directors drawing a salary exceeding 6700:
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:
BUILT-IN VARIABLES
Awk has several built-in variables. They are all assigned automatically, though it is also
possible for a user to reassign some of them. You have already used NR, which signifies the record
number of the current line. We’ll now have a brief look at some of the other variable. The FS
Variable: as stated elsewhere, awk uses a contiguous string of spaces as the default field delimiter.
FS redefines this field separator, which in the sample database happens to be the |. When used at all,
it must occur in the BEGIN section so that the body of the program knows its value before it starts
processing:
BEGIN {FS=”|”}
This is an alternative to the –F option which does the same thing.
The OFS Variable: when you used the print statement with comma-separated arguments, each
argument was separated from the other by a space. This is awk’s default output field separator, and
can reassigned using the variable OFS in the BEGIN section:
BEGIN { OFS=”~” }
When you reassign this variable with a ~ (tilde), awk will use this character for delimiting the print
arguments. This is a useful variable for creating lines with delimited fields.
The NF variable: NF comes in quite handy for cleaning up a database of lines that don’t
contain the right number of fields. By using it on a file, say emp.lst, you can locate those lines not
having 6 fields, and which have crept in due to faulty data entry:
The FILENAME Variable: FILENAME stores the name of the current file being processed. Like
grep and sed, awk can also handle multiple filenames in the command line. By default, awk doesn’t
print the filename, but you can instruct it to do so:
NS2 Installation
• NS2 is a free simulation tool.
• It runs on various platforms including UNIX (or Linux), Windows, and Mac systems.
• NS2 source codes are distributed in two forms: the all-in-one suite and the component- wise.
• ‘all-in-one’ package provides an “install” script which configures the NS2 environment and
creates NS2 executable file using the “make” utility.
➢ When we open this file, we get a line in that file which is shown below
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”.
“/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”
%
➢ If we get “%” symbol it indicates that nam-1.13 configuration was successful.
➢ Third, configure “xgraph-12.1” package as shown below
[root@localhost nam-1.13] # cd . .
[root@localhost ns-allinone-2.33] # cd xgraph-12.1
[root@localhost xgraph-12.1] # ./configure
[root@localhost xgraph-12.1] # make clean
[root@localhost xgraph-12.1] # make [root@localhost
xgraph-12.1] # make install [root@localhost xgraph-
12.1] # ns
%
This completes the installation process of “NS-2” simulator
PART-A
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.
proc finish { } { /* provide space b/w proc and finish and all are in small case */
global ns nf tf
$ns flush-trace /* clears trace file contents */
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 run
AWK file (Open a new editor using “gedit command” and write awk file and save with “.awk”
extension)
/*immediately after BEGIN should open braces ‘{‘
BEGIN{
drop=0;
}
{
if($1=="d" )
{
drop++;
printf("%s\t%s\n",$5,$11);
}
}
END{
printf("Total number of %s packets dropped due to congestion =%d\n",$5,drop);
}
1. Set the queue size fixed from n0 to n2 as 10, n1-n2 to 10 and from n2-n3 as 5.
Syntax: To set the queue size
$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 node 2
Trace file contains 12 columns:-
Event type, Event time, From Node, Source Node, Packet Type, Packet Size, Flags
(indicated by --------), Flow ID, Source address, Destination address, Sequence ID,
Packet ID
TOPOLOGY:
Output:
amc@amc-p2-1274il:~/Desktop/NS2/day1$ awk -f lab1.awk lab1.tr
cbr 139
cbr 126
cbr 127
cbr 130
cbr 151
cbr 154
cbr 136
cbr 159
cbr 141
cbr 142
cbr 145
cbr 171
cbr 174
cbr 151
cbr 154
cbr 157
cbr 187
cbr 161
cbr 163
cbr 195
cbr 201
cbr 173
cbr 175
cbr 209
Total number of cbr packets dropped due to congestion =24
amc@amc-p2-1274il:~/Desktop/NS2/day1$
# please provide space between $node_ and id. No space between $ and from. No
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab2.nam &
exit 0
}
$ns run
AWK file (Open a new editor using “gedit 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);
}
amc@amc-p2-1274il:~/Desktop/NS2/day1$ ns 2.tcl
TOPOLOGY:
OUTPUT:
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 0 received answer from 5 with round trip time 404.9 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 0 received answer from 5 with round trip time 704.9 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 0 received answer from 5 with round trip time 804.9 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 0 received answer from 5 with round trip time 804.9 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 0 received answer from 5 with round trip time 804.9 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 0 received answer from 5 with round trip time 804.9 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 2 received answer from 3 with round trip time 5.3 msec
node 0 received answer from 5 with round trip time 804.9 msec
node 2 received answer from 3 with round trip time 5.3 msec
amc@amc-p2-1274il:~/Desktop/NS2/day1$
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
window for different source / destination.
$ns make-lan "$n0 $n1 $n2 $n3 $n4" 50Mb 100ms LL Queue/DropTail Mac/802_3
proc finish { } {
global ns nf tf
$ns flush-trace
close $tf
close $nf
exec nam lab3.nam &
exit 0
}
$ns run
AWK file (Open a new editor using “gedit command” and write awk file and save with “.awk”
extension)
cwnd:- means congestion window
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 {
}
amc@amc-p2-1274il:~/Desktop/NS2/day1$ ns 3.tcl
TOPOLOGY:
amc@amc-p2-1274il:~/Desktop/NS2/day1$ xgraph a1 a2
OUTPUT:
amc@amc-p2-1274il:~/Desktop/NS2/day1$
4. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and
determine the performance with respect to transmission of packets.
-agentTrace ON \
-routerTrace ON
create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$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
proc finish { } {
global ns nf tf
$ns flush-trace
exec nam lab4.nam &
close $tf
exit 0
}
AWK file (Open a new editor using “gedit 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)));
}
amc@amc-p2-1274il:~/Desktop/NS2/day1$ ns 4.tcl
OUTPUT:
amc@amc-p2-1274il:~/Desktop/NS2/day1$ awk -f lab4.awk lab4.tr
amc@amc-p2-1274il:~/Desktop/NS2/day1$
TOPOLOGY:
TRACE FILE:
5. Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or equivalent
environment.
Second Generation (2G) technology is based on the technology known as global system for mobile
communication (GSM). This technology enabled various networks to provide services like text
messages, picture messages and MMS. The technologies used in 2G are either 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 physical
channel.
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 full duplex 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:
# 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"
}
proc set_link_params {t} {
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 {} {
global nodes opt nf
set wrap $opt(wrap)
set sid [$nodes($opt(srcTrace)) id]
set did [$nodes($opt(dstTrace)) id]
if {$opt(srcTrace) == "is"} {
set a "-a out.tr"
} else {
set a "out.tr"
}
set GETRC "../../../bin/getrc"
set RAW2XG "../../../bin/raw2xg"
amc@amc-p2-1274il:~/ns-allinone-2.35/ns-2.35/tcl/ex/wireless-scripts$ ns mtp-gsm.tcl
Cell Topology
amc@amc-p2-1274il:~/ns-allinone-2.35/ns-2.35/tcl/ex/wireless-scripts$
OUTPUT:
6. Implement and study the performance of CDMA on NS2/NS3 (Using stack called Call net) or
equivalent environment.
3G networks developed as a replacement for second generation (2G) GSM standard network with full
duplex voice telephony. CDMA is used as the access method in many mobile phone standards. IS-95,
also called cdmaOne, and its 3G evolution CDMA2000, are often simply referred to as CDMA, but
UMTS(The Universal Mobile Telecommunications System is a third generation mobile cellular
system for networks based on the GSM standard.), the 3G standard used by GSM carriers, also uses
wideband CDMA. Long-Term Evolution (LTE) is a standard for high-speed wireless communication
which uses CDMA network technology.
3G technology generally refers to the standard of accessibility and speed of mobile devices. The
standards of the technology were set by the International Telecommunication Union (ITU). This
technology enables use of various services like GPS (Global Positioning System), mobile television
and video conferencing. It not only enables them to be used worldwide, but also provides with better
bandwidth and increased speed. The main aim of this technology is to allow much better coverage and
growth with minimum investment.
CDMA can be implemented on all the versions of NS2 (Since year 2004: ns-2.27, and later versions
of NS2).
Design:
# 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
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"
}
proc set_link_params {t} {
global ns nodes bwUL bwDL propUL propDL buf
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]
proc stop {} {
global nodes opt nf
set wrap $opt(wrap)
set sid [$nodes($opt(srcTrace)) id]
set did [$nodes($opt(dstTrace)) id]
if {$opt(srcTrace) == "is"} {
set a "-a out.tr"
} else {
set a "out.tr"
}
set GETRC "../../../bin/getrc"
set RAW2XG "../../../bin/raw2xg"
amc@amc-p2-1274il:~/ns-allinone-2.35/ns-2.35/tcl/ex/wireless-scripts$ ns mtp-umts.tcl
Cell Topology
Output:
PART-B
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 overcome 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.
The idea behind CRC calculation is to look at the data as one large binary number. This
number is divided by a certain value and the remainder of the calculation is called the CRC.
Dividing in the CRC calculation at first looks to cost a lot of computing power, but it can be
performed very quickly if we use a method similar to the one learned at school. We will as an
example calculate the remainder for the character 'm'—which is 1101101 in binary notation— by
dividing it by 19 or 10011. Please note that 19 is an odd number. This is necessary as we will see
further on. Please refer to your schoolbooks as the binary calculation method here is not very
different from the decimal method you learned when you were young. It might only look a little bit
strange. Also notations differ between countries, but the method is similar.
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 easilyincrease 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 with 56 binary 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:
package crc;
import java.util.*;
import java.io.*;
public class CRC
{
char t[]=new char[200];
char cs[]=new char[200];
char g[]=new char[200];
int a,e,c;
void xor()
{
for(int i=1;i<17;i++)
cs[i]=((cs[i]==g[i])?'0':'1');
}
void crc()
{
for(e=0;e<17;e++)
cs[e]=t[e];
do
{
if(cs[0]=='1')
xor();
for(c=0;c<16;c++)
cs[c]=cs[c+1];
cs[c]=t[e++];
}while(e<=a+16);
}
void operation()
{
a=msg.length();
for(e=a;e<a+16;e++)
t[e]='0';
System.out.print(" \n Modified message is=");
for(int i=0;i<msg.length()+16;i++)
System.out.print(t[i]);
crc();
for(int i=0;i<a+16;i++)
System.out.print(t[i]);
System.out.println("\nTest error detection 0(yes)/1(no):");
e=read.nextInt();
if(e==0)
{
System.out.println("\nenter the position where error is to be inserted:");
e=read.nextInt();
t[e]=(t[e]=='0')?'1':'0';
System.out.println("errornous data:") ;
for(int i=0;i<a+16;i++)
System.out.print(t[i]);
}
crc();
for(e=0;(e<16)&&(cs[e]!='1');e++);
if(e<16)
System.out.println("error detected");
else
System.out.println("no error detected");
}
public static void main(String[] args)
{
CRC ob=new CRC();
ob.operation();
}
Output:
Run1:
enter the polynomial
1011101
Run2:
enter the polynomial
1011101
8. 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 up date 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:
package bellmanford;
import java.util.Scanner;
public class BellmanFord
{
private final int D[];
private final int num_ver;
public static final int MAX_VALUE = 999;
public BellmanFord(int num_ver)
{
this.num_ver = num_ver;
D = new int[num_ver + 1];
}
int num_ver = 0;
int source;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of vertices");
num_ver = scanner.nextInt();
int A[][] = new int[num_ver + 1][num_ver + 1];
System.out.println("Enter the adjacency matrix");
for (int sn = 1; sn <=num_ver; sn++)
{
for (int dn = 1; dn <= num_ver; dn++)
{
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();
}
}
Output:
Run1:
5
A B
3
4
C D
Enter the number of vertices 2
4
Enter the adjacency matrix
0500
5034
0302
0420
Enter the source vertex
2
distance of source 2 to 1 is 5
distance of source 2 to 2 is 0
distance of source 2 to 3 is 3
distance of source 2 to 4 is 4
Run2:
Enter the number of vertices
4
Enter the adjacency matrix
0500
5 0 -2 4
0 -3 0 -5
0420
Enter the source vertex
2
The Graph contains negative egde cycle
The Graph contains negative egde cycle
The Graph contains negative egde cycle
The Graph contains negative egde cycle
distance of source 2 to 1 is -5
distance of source 2 to 2 is -15
distance of source 2 to 3 is -15
distance of source 2 to 4 is -17
9. Using TCP/IP sockets, write a client – server program to make the client send the file name
and to make the server send back the contents of the requested file if present.
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 a
socket object on its end of the communication. The client and the server can now communicate by
writing to and reading from the socket.
Source Code: Server
import java.net.*;
import java.io.*;
public class tcps
{
public static void main(String args[]) throws IOException
{
ServerSocket sersock=new ServerSocket(5000);
System.out.println("server ready for connection");
Socket sock=sersock.accept();
System.out.println("connection is successful");
InputStream istream=sock.getInputStream();
BufferedReader fileRead=new BufferedReader(new InputStreamReader(istream));
String fname=fileRead.readLine();
BufferedReader contentRead=new BufferedReader(new FileReader(fname));
OutputStream ostream=sock.getOutputStream();
PrintWriter pwrite=new PrintWriter(ostream,true);
String str;
while((str=contentRead.readLine())!=null)
{
pwrite.println(str);
}
sock.close();
sersock.close();
pwrite.close();
fileRead.close();
contentRead.close();
}
}
Source Code: Client
import java.net.*;
import java.io.*;
public class tcpc
{
public static void main(String args[]) throws IOException
{
Socket sock=new Socket("127.0.0.1",5000);
System.out.println("Enter the File Name");
BufferedReader keyRead=new BufferedReader(new InputStreamReader(System.in));
String fname=keyRead.readLine();
OutputStream ostream=sock.getOutputStream();
PrintWriter pwrite=new PrintWriter(ostream,true);
System.out.println();
pwrite.println(fname);
InputStream istream=sock.getInputStream();
BufferedReader socketRead=new BufferedReader(new InputStreamReader(istream));
String str;
while((str=socketRead.readLine())!=null)
{
System.out.println(str);
}
sock.close();
pwrite.close();
keyRead.close();
socketRead.close();
}
}
output:
serverside
amc@amc-p2-1274il:~$ gedit abc.txt
amc@amc-p2-1274il:~$ gedit tcps.java
amc@amc-p2-1274il:~$ javac tcps.java
amc@amc-p2-1274il:~$ java tcps
server ready for connection
connection is successful
amc@amc-p2-1274il:~$
clientside
amc@amc-p2-1274il:~$ javac tcpc.java
amc@amc-p2-1274il:~$ java tcpc
Enter the File Name
abc.txt
computer network lab
Information Science and Engg
amc@amc-p2-1274il:~$
10. Write a program on datagram socket for client/server to display the messages on client
side, typed at the server side.
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.
Source Code: Server
import java.io.*;
import java.net.*;
public class UDPS
{
public static void main(String[] args)
{
DatagramSocket skt=null;
try
{
skt=new DatagramSocket(6789);
byte[] buffer = new byte[1000];
while(true)
{
DatagramPacket request = new DatagramPacket(buffer,buffer.length);
skt.receive(request);
String[] message = (new String(request.getData())).split(" ");
byte[] sendMsg= (message[1]+ " server processed").getBytes();
DatagramPacket reply = new
DatagramPacket(sendMsg,sendMsg.length,request.getAddress (),request.getPort());
skt.send(reply);
}
}
catch(Exception ex)
{
}
}
}
import java.io.*;
import java.net.*;
public class UDPC
{
public static void main(String[] args)
{
DatagramSocket skt; try
{
skt=new DatagramSocket();
String msg= "network lab ";
byte[] b = msg.getBytes();
InetAddress host=InetAddress.getByName("127.0.0.1");
int serverSocket=6789;
DatagramPacket request =new DatagramPacket (b,b.length,host,serverSocket);
skt.send(request);
byte[] buffer =new byte[1000];
DatagramPacket reply= new DatagramPacket(buffer,buffer.length);
skt.receive(reply);
System.out.println("client received:" +new String(reply.getData()));
skt.close();
}
catch(Exception ex)
{
}
}
}
Output:
serverside
clientside
11. Write a program for simple RSA algorithm to encrypt and decrypt the data.
RSA is an example of public key cryptography. It was developed by Rivest, Shamir and Adelman.
The RSA algorithm can be used for both public key encryption and digital signatures. Its security is
based on the difficulty of factoring large integers.
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:-
1. Using the public key (e,n)
2. Represents the plaintext message as a positive integer M
3. Computes the cipher text C = M^e mod n.
4. Sends the cipher text C to B (Receiver).
Decryption
Recipient B does the following:-
1. Uses his private key (d, n) to compute M = C^d mod n.
2. Extracts the plaintext from the integer representative m.
package rsa;
import java.util.*;
import java.io.*;
Output:
enter the message to encrypt:
AMCEC
12. Write a program for congestion control using leaky bucket algorithm.
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 spillover. 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.
package bucket;
import java.util.*;
public class Bucket
{
static void solution(int pktsize, int output)
{
int buketsize=512;
if(pktsize>buketsize)
{
System.out.println("Bucket overflow");
}
else
{
while(pktsize>output)
{
System.out.println(output+"bytes outputed");
pktsize=pktsize-output;
}
if(pktsize>0)
{
System.out.println( pktsize+"bytes outputed");
}
}
}
Output:
Enter output rate
50
Enter the number of packets
5
packetno:1packetsize=417
50bytes outputed
50bytes outputed
50bytes outputed
50bytes outputed
50bytes outputed
50bytes outputed
50bytes outputed
50bytes outputed
17bytes outputed
packetno:2packetsize=917
Bucket overflow
packetno:3packetsize=866
Bucket overflow
packetno:4packetsize=721
Bucket overflow
packetno:5packetsize=20
20bytes outputed
VIVA QUESTIONS
1) What is a Link?
A link refers to the connectivity between two devices. It includes the type of cables and protocols used
in order for one device to be able to communicate with the other.
4) What is a LAN?
LAN is short for Local Area Network. It refers to the connection between computers and other
network devices that are located within a small physical location.
5) What is a node?
A node refers to a point or joint where a connection takes place. It can be computer or device that is
part of a network. Two or more nodes are needed in order to form a network connection.
11) How does a network topology affect your decision in setting up a network?
Network topology dictates what media you must use to interconnect devices. It also serves as basis on
what materials, connector and terminations that is applicable for the setup.
computers. Make sure firewalls are setup and configured properly. User authentication will also help a
lot. All of these combined would make a highly secured network.
Encryption is the process of translating information into a code that is unreadable by the user. It is
then translated back or decrypted back to its normal readable format using a secret key or password.
Encryption help ensure that information that is intercepted halfway would remain unreadable because
the user has to have the correct password or key for it.
28) What is OSI and what role does it play in computer networks?
OSI (Open Systems Interconnect) serves as a reference model for data communication. It is
made up of 7 layers, with each layer defining a particular aspect on how network devices connect and
communicate with one another. One layer may deal with the physical media used, while another layer
dictates how data is actually transmitted across the network.
30) What is the equivalent layer or layers of the TCP/IP Application layer in terms of OSI
reference model?
The TCP/IP Application layer actually has three counterparts on the OSI model: the Session
layer, Presentation Layer and Application Layer.
Hamming Code. Hamming code is a set of error-correction codes that can be used to detect
and correct the errors that can occur when the data is moved or stored from the sender to the
receiver. It is technique developed by R.W. Hammingfor error correction
The key to the Hamming Code is the use of extra parity bits to allow the identification of a single
error. Create the code word as follows:
1. Mark all bit positions that are powers of two as parity bits. (positions 1, 2, 4, 8, 16, 32, 64, etc.)
2. All other bit positions are for the data to be encoded. (positions 3, 5, 6, 7, 9, 10, 11, 12, 13, 14,
15, 17, etc.)
3. Each parity bit calculates the parity for some of the bits in the code word. The position of the
parity bit determines the sequence of bits that it alternately checks and skips.
Position 1: check 1 bit, skip 1 bit, check 1 bit, skip 1 bit, etc. (1,3,5,7,9,11,13,15,...)
Position 2: check 2 bits, skip 2 bits, check 2 bits, skip 2 bits, etc. (2,3,6,7,10,11,14,15,...)
Position 4: check 4 bits, skip 4 bits, check 4 bits, skip 4 bits, etc.
(4,5,6,7,12,13,14,15,20,21,22,23,...)
Position 8: check 8 bits, skip 8 bits, check 8 bits, skip 8 bits, etc. (8-15,24-31,40-47,...)
Position 16: check 16 bits, skip 16 bits, check 16 bits, skip 16 bits, etc. (16-31,48-63,80-95,...)
Position 32: check 32 bits, skip 32 bits, check 32 bits, skip 32 bits, etc. (32-63,96-127,160-
191,...)
etc.
4. Set a parity bit to 1 if the total number of ones in the positions it checks is odd. Set a parity bit
to 0 if the total number of ones in the positions it checks is even.
Here is an example:
import java.util.*;
class Hamming {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of bits for the Hamming data:");
int n = scan.nextInt();
int a[] = new int[n];
System.out.println("You entered:");
for(int i=0 ; i < n ; i++) {
System.out.print(a[n-i-1]);
}
System.out.println();
int power;
a[error_location-1] = (a[error_location-1]+1)%2;
System.out.println("Corrected code is:");
for(int i=0 ; i < a.length ; i++) {
System.out.print(a[a.length-i-1]);
}
System.out.println();
}
else {
System.out.println("There is no error in the received data.");
}
System.out.println("Original data sent was:");
power = parity_count-1;
for(int i=a.length ; i > 0 ; i--) {
if(Math.pow(2, power) != i) {
System.out.print(a[i-1]);
}
else {
power--;
}
}
System.out.println();
}
}
Output:
Enter the number of bits for the Hamming data:
7
Enter bit no. 7:
1
Enter bit no. 6:
0
Enter bit no. 5:
1
Enter bit no. 4:
0
Enter bit no. 3:
1
Enter bit no. 2:
0
Enter bit no. 1:
1
You entered:
1010101
Generated code is:
10100101111
Enter position of a bit to alter to check for error detection at the receiver end (0 for no error):
5
Sent code is:
10100111111
Error is at location 5.
Corrected code is:
10100101111
Original data sent was:
1010101
Diffie-Hellman is a way of generating a shared secret between two people in such a way that the
secret can’t be seen by observing the communication.That’s an important distinction: You’re
not sharing information during the key exchange, you’re creating a key together.
Algorithm
Step 1 : Choose two prime numbers g(primitive root of p) and p.
Step 2 : Alice selects a secret no(a) and computes ga mod p , let’s call it A. Alice sends A to Bob.
Step 3 : Bob selects a secret no(b) and computes gb mod p, let’s call it B. Bob sends B to Alice.
Step 4 : Alice computes S_A = Ba mod p
Step 5 : Bob computes S_B = Ab mod p
Step 6 : If S_A=S_B then Alice and Bob can agree for future communication.
Program:
import java.util.*;
class Diffie_Hellman
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter modulo(p)");
int p=sc.nextInt();
System.out.println("Enter primitive root of "+p);
int g=sc.nextInt();
System.out.println("Choose 1st secret no(Alice)");
int a=sc.nextInt();
System.out.println("Choose 2nd secret no(BOB)");
int b=sc.nextInt();
int A = (int)Math.pow(g,a)%p;
int B = (int)Math.pow(g,b)%p;
if(S_A==S_B)
{
System.out.println("ALice and Bob can communicate with each other!!!");
System.out.println("They share a secret no = "+S_A);
}
else
{
System.out.println("ALice and Bob cannot communicate with each other!!!");
}
}
}
Output:
Enter modulo(p)
7
Enter primitive root of 7
17
Choose 1st secret no(Alice)
8
Choose 2nd secret no(BOB)
4
ALice and Bob can communicate with each other!!!
They share a secret no =1