0% found this document useful (0 votes)
41 views57 pages

CN Manual

The document provides an overview of the Computer Networks laboratory which covers implementing and simulating networking concepts using NS2. The first part deals with network simulation using NS2 to develop, test, and evaluate network protocols. The second part deals with implementing interprocess communication techniques, security algorithms, routing algorithms, and more. It then provides details on starting NS2 simulations using Tcl scripts, defining nodes and links, and initializing and terminating simulations.

Uploaded by

wavovaf945
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views57 pages

CN Manual

The document provides an overview of the Computer Networks laboratory which covers implementing and simulating networking concepts using NS2. The first part deals with network simulation using NS2 to develop, test, and evaluate network protocols. The second part deals with implementing interprocess communication techniques, security algorithms, routing algorithms, and more. It then provides details on starting NS2 simulations using Tcl scripts, defining nodes and links, and initializing and terminating simulations.

Uploaded by

wavovaf945
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

CN Lab Manual

Preface:

Computer Networks laboratory covers the implementation of basic networking concepts and
simulation of advanced concepts. The prerequisite for this laboratory is the understanding of
fundamentals of computer networks. There are two parts in this laboratory. The first part deals
with simulation of networking concepts. The second part deals with how to implement the
message transfer among the systems using inter process communication (IPC) techniques,
security algorithms, routing algorithms, error detection and flow and congestion control
techniques.

Network Simulation Using NS2:

Network simulation is an important tool in developing, testing and evaluating network protocols.
Simulation can be used without the target physical hardware, making it economical and practical
for almost any scale of network topology and setup. It is possible to simulate a link of any
bandwidth and delay, even if such a link is currently impossible in the real world. With
simulation, it is possible to set each simulated node to use any desired software. Most network
simulators use abstractions of network protocols, rather than the real thing, making their results
less convincing. S.Y. Wang reports that the simulator OPNET uses a simplified finite state
machine to model complex TCP protocol processing. NS-2 uses a model based on TCP, it is
implemented as a set of classes using inheritance.

Wang states that “Simulation results are not as convincing as those produced by real hardware
and software equipment.” This statement is followed by an explanation of the fact that most
existing network simulators can only simulate real life network protocol implementations with
limited details, which can lead to incorrect results. Another paper includes a similar statement,
“running the actual TCP code is preferred to running an abstract specification of the protocol.”
Brakmo and Peterson go on to discuss how the BSD implementations of TCP are quite important
with respect to timers. Simulators often use more accurate round trip time measurements than
those used in the BSD implementation, making results differ.

Starting ns

You start ns with the command 'ns <tclscript>' (assuming that you are in the directory with the ns
executable, or that your path points to that directory), where '<tclscript>' is the name of a Tcl
(Tool Command Language) script file which defines the simulation scenario (i.e. the topology
and the events). You can also just start ns without any arguments and enter the Tcl commands in
the Tcl shell, but that is definitely less comfortable. Starting nam (Network Animator): You can
either start nam with the command 'nam <nam-file>' where '<nam-file>' is the name of a nam
trace file that was generated by ns, or you can execute it directly out of the Tcl simulation script
for the simulation which you want to visualize.
Introduction to NS-2

ACSCE Page 1
CN Lab Manual

 Widely known as NS2, is simply an event driven simulation tool.


 Useful in studying the dynamic nature of communication networks.
 Simulation of wired as well as wireless network functions and protocols (e.g., routing
algorithms, TCP, UDP) can be done using NS2.
 In general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviours.

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, 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 }

ACSCE Page 2
CN Lab Manual

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 event scheduler


 Open new files & turn on the tracing
 Create the nodes
 Setup the links
 Configure the traffic type (e.g., TCP, UDP, etc)
 Set the time of traffic generation (e.g., CBR, FTP)
 Terminate the simulation

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.

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 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:

#Open the Trace file:


set tracefile1 [open out.tr w]

$ns trace-all $tracefile1

ACSCE Page 3
CN Lab Manual

#Open the NAM trace file:


set namfile [open out.nam w]

$ns namtrace-all $namfile

The above creates a 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 tracefile 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.

#Define a finish procedure

Proc finish { } {
global ns tracefile1
namfile
$ns flush-trace
Close $tracefile1
Close $namfile
Exec nam out.nam &
Exit 0
}

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,
$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

ACSCE Page 4
CN Lab Manual

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]


The node is created which 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


$ns queue-limit $n0 $n2 20

Agents and Applications

We need to define routing (sources, destinations) the agents (protocols) the application that use
them.

FTP over TCP

TCP is a dynamic reliable congestion control protocol. It uses Acknowledgements created by the
destination to know whether packets are well received.
There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno,

ACSCE Page 5
CN Lab Manual

Vegas. The type of agent appears in the first line:

set tcp [new Agent/TCP]


The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command
set sink [new Agent /TCPSink]
Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.

#Setup a UDP connection


set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n5 $null
$ns connect $udp $null
$udp set fid_2

#setup a CBR over UDP connection


set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set packetsize_ 100
$cbr set rate_ 0.01Mb
$cbr set random_ false

Above shows the definition of a CBR application using a UDP agent


The command $ns attach-agent $n4 $sink defines the destination node. The command $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.

CBR over UDP

A UDP source and destination is defined in a similar way as in the case of TCP.
Instead of defining the rate in the command $cbr set rate_ 0.01Mb, one can define the time
interval between transmission of packets using the command.
$cbr set interval_ 0.005
The packet size can be set to some value using

ACSCE Page 6
CN Lab Manual

$cbr set packetSize_ <packet size>

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”
$ns at 1.0 “ $ftp start”
$ns at 124.0 “$ftp stop”
$ns at 124.5 “$cbr stop”

Structure of Trace Files

When tracing into an output ASCII file, the trace is organized in 12 fields as follows in fig
shown below, The meaning of the fields are:
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 event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (eg CBR or TCP)
6. Gives the packet size
7. Some flags
8. 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.
9. This is the source address given in the form of “node.port”.
10. This is the destination address, given in the same form.
11. 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
packet sequence number for analysis purposes.
12. The last field shows the Unique id of the packet.

ACSCE Page 7
CN Lab Manual

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.
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.

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
ACSCE Page 8
CN Lab Manual

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:
$ awk –F”|” „$3 == “director” && $6 > 6700 {
kount =kount+1
printf “ %3f %20s %-12s %d\n”, kount,$2,$3,$6 }’ empn.lst
THE –f OPTION: STORING awk PROGRAMS IN A 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

THE BEGIN AND END SECTIONS

Awk statements are usually applied to all lines selected by the address, and if there are no
addresses, then they are applied to every line of input. But, if you have to print something before
processing the first line, for example, a heading, then the BEGIN section can be used gainfully.
Similarly, the end section useful in printing some totals after processing is over.

The BEGIN and END sections are optional and take the form
BEGIN {action}
END {action}
These two sections, when present, are delimited by the body of the awk program. You can use
them to print a suitable heading at the beginning and the average salary at the end.

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

ACSCE Page 9
CN Lab Manual

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:
$awk ‘BEGIN {FS = “|”}
NF! =6 {
Print “Record No “, NR, “has”, “fields”}’ empx.lst

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:
‘$6<4000 {print FILENAME, $0 }’
With FILENAME, you can device logic that does different things depending on the file that is
processed.

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.

NS-2 installation steps in Linux

 Go to Computer File System now paste the zip file “ns-allinone-2.34.tar.gz” into opt
folder.
 Now unzip the file by typing the following command
[root@localhost opt] # tar -xzvf ns-allinone-2.34.tar.gz
 After the files get extracted, we get ns-allinone-2.34 folder as well as zip file nsallinone-
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.

ACSCE Page 10
CN Lab Manual

 First minimize the terminal where installation is done and open a new terminal and
open the file “.bash_profile”
[root@localhost ~] # vi .bash_profile
 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-allinone2.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”15
 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 “export LD_LIBRARY_PATH”
 In the next line type “export TCL_LIBRARY”
 The next two lines are already present the file “export PATH” and
“unsetUSERNAME”
 Save the program ( ESC + shift : wq and press enter )
 Now in the terminal where we have opened .bash_profile file, type the following
command to check if path is updated correctly or not
[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 installed ns[root@localhost ns-
allinone-2.33] #
 Here we need to configure three packages “ns-2.33”, “nam-1.13” and “xgraph-12.1”
 First, configure “ns-2.33” package as shown below
[root@localhost ns-allinone-2.33] # cd ns-2.33
[root@localhost ns-2.33] # ./configure
[root@localhost ns-2.33] # make clean
[root@localhost ns-2.33] # make
[root@localhost ns-2.33] # make install
[root@localhost ns-2.33] # ns
%
 If we get “%” symbol it indicates that ns-2.33 configuration was successful.
 Second, configure “nam-1.13” package as shown below
[root@localhost ns-2.33] # cd . .
ACSCE Page 11
CN Lab Manual

[root@localhost ns-allinone-2.33] # cd nam-1.13


[root@localhost nam-1.13] # ./configure
[root@localhost nam-1.13] # make clean
[root@localhost nam-1.13] # make
[root@localhost nam-1.13] # make install
[root@localhost nam-1.13] # ns
%
 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.

ACSCE Page 12
CN Lab Manual

#Create Simulator
set ns [new Simulator]

#Open Trace file and NAM file set ntrace [open prog1.tr w]
$ns trace-all $ntrace
set namfile [open prog1.nam w]
$ns namtrace-all $namfile

#Finish Procedure proc Finish {} {


global ns ntrace namfile

#Dump all the trace data and close the files


$ns flush-trace close $ntrace close $namfile

#Execute the nam animation file exec nam prog1.nam &

#Show the number of packets dropped


exec echo "The number of packet drops is " & exec grep -c "^d" prog1.tr &
exit 0
}

#Create 3 nodes set n0 [$ns node] set n1 [$ns node] set n2 [$ns node]

#Label the nodes


$n0 label "TCP Source"
$n2 label "Sink"

#Set the color


$ns color 1 blue

#Create Links between nodes


#You need to modify the bandwidth to observe the variation in packet drop
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail

#Make the Link Orientation


$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n1 $n2 orient right

#Set Queue Size


#You can modify the queue length as well to observe the variation in packet drop
ACSCE Page 13
CN Lab Manual

$ns queue-limit $n0 $n1 10


$ns queue-limit $n1 $n2 10

#Set up a Transport layer connection. set tcp0 [new Agent/TCP]


$ns attach-agent $n0 $tcp0
set sink0 [new Agent/TCPSink]
$ ns attach-agent $n2 $sink0
$ns connect $tcp0 $sink0

#Set up an Application layer Traffic


set cbr0 [new Application/Traffic/CBR]
$cbr0 set type_ CBR
$cbr0 set packetSize_ 100
$cbr0 set rate_ 1Mb
$cbr0 set random_ false
$cbr0 attach-agent $tcp0
$tcp0 set class_ 1

#Schedule Events
$ns at 0.0 "$cbr0 start"
$ns at 5.0 "Finish"

#Run the Simulation


$ns run

Output:

2. Implement transmission of ping messages/trace route over a network topology consisting


of 6 nodes and find the number of packets dropped due to congestion.

#Create Simulator
set ns [new Simulator]

ACSCE Page 14
CN Lab Manual

#Use colors to differentiate the traffic


$ns color 1 Blue
$ns color 2 Red

#Open trace and NAM trace file set ntrace [open prog3.tr w]
$ns trace-all $ntrace
set namfile [open prog3.nam w]
$ns namtrace-all $namfile

#Finish Procedure proc Finish {} {


global ns ntrace namfile

#Dump all trace data and close the file


$ns flush-trace close $ntrace close $namfile

#Execute the nam animation file exec nam prog3.nam &

#Find the number of ping packets dropped


puts "The number of ping packets dropped are "
exec grep "^d" prog3.tr | cut -d " " -f 5 | grep -c "ping" & exit 0
}

#Create six nodes


for {set i 0} {$i < 6} {incr i} {
set n($i) [$ns node]
}
#Connect the nodes
for {set j 0} {$j < 5} {incr j} {
$ns duplex-link $n($j) $n([expr ($j+1)]) 0.1Mb 10ms DropTail
}

#Define the recv function for the class 'Agent/Ping'


Agent/Ping instproc recv {from rtt} {
$self instvar node_
puts "node [$node_ id] received ping answer from $from with round trip time $rtt ms"
}

#Create two ping agents and attach them to n(0) and n(5)
set p0 [new Agent/Ping]
$p0 set class_ 1
ACSCE Page 15
CN Lab Manual

$ns attach-agent $n(0) $p0

set p1 [new Agent/Ping]


$p1 set class_ 1
$ns attach-agent $n(5) $p1
$ns connect $p0 $p1

#Set queue size and monitor the queue


#Queue size is set to 2 to observe the drop in ping packets
$ns queue-limit $n(2) $n(3) 2
$ns duplex-link-op $n(2) $n(3) queuePos 0.5

#Create Congestion
#Generate a Huge CBR traffic between n(2) and n(4)
set tcp0 [new Agent/TCP]
$tcp0 set class_ 2
$ns attach-agent $n(2) $tcp0 set sink0 [new Agent/TCPSink]
$ns attach-agent $n(4) $sink0
$ns connect $tcp0 $sink0

#Apply CBR traffic over TCP


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set rate_ 1Mb
$cbr0 attach-agent $tcp0

#Schedule events
$ns at 0.2 "$p0 send"
$ns at 0.4 "$p1 send"
$ns at 0.4 "$cbr0 start"
$ns at 0.8 "$p0 send"
$ns at 1.0 "$p1 send"
$ns at 1.2 "$cbr0 stop"
$ns at 1.4 "$p0 send"
$ns at 1.6 "$p1 send"
$ns at 1.8 "Finish"

#Run the Simulation


$ns run

Output:

ACSCE Page 16
CN Lab Manual

3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.

#Create Simulator
set ns [new Simulator]

#Use colors to differentiate the traffics


$ns color 1 Blue

ACSCE Page 17
CN Lab Manual

$ns color 2 Red

#Open trace and NAM trace file set ntrace [open prog5.tr w]
$ns trace-all $ntrace
set namfile [open prog5.nam w]
$ns namtrace-all $namfile

#Use some flat file to create congestion graph windows set winFile0 [open WinFile0 w]
set winFile1 [open WinFile1 w]

#Finish Procedure proc Finish {} {


#Dump all trace data and Close the files global ns ntrace namfile
$ns flush-trace close $ntrace close $namfile

#Execute the NAM animation file exec nam prog5.nam &

#Plot the Congestion Window graph using xgraph exec xgraph WinFile0 WinFile1 &
exit 0
}

#Plot Window Procedure


proc PlotWindow {tcpSource file} { global ns
set time 0.1
set now [$ns now]

set cwnd [$tcpSource set cwnd_] puts $file "$now $cwnd"


$ns at [expr $now+$time] "PlotWindow $tcpSource $file"
}

#Create 6 nodes
for {set i 0} {$i<6} {incr i} { set n($i) [$ns node]
}

#Create duplex links between the nodes


$ns duplex-link $n(0) $n(2) 2Mb 10ms DropTail
$ns duplex-link $n(1) $n(2) 2Mb 10ms DropTail
$ns duplex-link $n(2) $n(3) 0.6Mb 100ms DropTail

#Nodes n(3) , n(4) and n(5) are considered in a LAN


set lan [$ns newLan "$n(3) $n(4) $n(5)" 0.5Mb 40ms LL Queue/DropTail MAC/802_3 Channel]

ACSCE Page 18
CN Lab Manual

#Orientation to the nodes


$ns duplex-link-op $n(0) $n(2) orient right-down
$ns duplex-link-op $n(1) $n(2) orient right-up
$ns duplex-link-op $n(2) $n(3) orient right

#Setup queue between n(2) and n(3) and monitor the queue
$ns queue-limit $n(2) $n(3) 20
$ns duplex-link-op $n(2) $n(3) queuePos 0.5

#Set error model on link n(2) to n(3) set loss_module [new ErrorModel]
$loss_module ranvar [new RandomVariable/Uniform]
$loss_module drop-target [new Agent/Null]
$ns lossmodel $loss_module $n(2) $n(3)

#Set up the TCP connection between n(0) and n(4) set tcp0 [new Agent/TCP/Newreno]
$tcp0 set fid_ 1
$tcp0 set window_ 8000
$tcp0 set packetSize_ 552
$ns attach-agent $n(0) $tcp0
set sink0 [new Agent/TCPSink/DelAck]
$ns attach-agent $n(4) $sink0
$ns connect $tcp0 $sink0

#Apply FTP Application over TCP set ftp0 [new Application/FTP]


$ftp0 attach-agent $tcp0

$ftp0 set type_ FTP

#Set up another TCP connection between n(5) and n(1) set tcp1 [new Agent/TCP/Newreno]
$tcp1 set fid_ 2
$tcp1 set window_ 8000
$tcp1 set packetSize_ 552
$ns attach-agent $n(5) $tcp1
set sink1 [new Agent/TCPSink/DelAck]
$ns attach-agent $n(1) $sink1
$ns connect $tcp1 $sink1

#Apply FTP application over TCP set ftp1 [new Application/FTP]


$ftp1 attach-agent $tcp1
$ftp1 set type_ FTP

ACSCE Page 19
CN Lab Manual

#Schedule Events
$ns at 0.1 "$ftp0 start"
$ns at 0.1 "PlotWindow $tcp0 $winFile0"
$ns at 0.5 "$ftp1 start"
$ns at 0.5 "PlotWindow $tcp1 $winFile1"
$ns at 25.0 "$ftp0 stop"
$ns at 25.1 "$ftp1 stop"
$ns at 25.2 "Finish"

#Run the simulation


$ns run

Output:

ACSCE Page 20
CN Lab Manual

4. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and
determine the performance with respect to transmission of packets.

#Code to be saved as .tcl

#Create a ns simulator
set ns [new Simulator]

#Setup topography object


set topo [new Topography]
$topo load_flatgrid 1500 1500

#Open the NS trace file


set tracefile [open p4.tr w]
$ns trace-all $tracefile

#Open the NAM trace file

ACSCE Page 21
CN Lab Manual

set namfile [open p4.nam w]


$ns namtrace-all $namfile
$ns namtrace-all-wireless $namfile 1500 1500

#Mobile node parameter setup


$ns node-config -adhocRouting DSDV \
-llType LL \
-macType Mac/802_11 \
-ifqType Queue/DropTail \
-ifqLen 20 \
-phyType Phy/WirelessPhy \
-channelType Channel/WirelessChannel \
-propType Propagation/TwoRayGround \
-antType Antenna/OmniAntenna \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON
#===================================
#Nodes Definition
#===================================
create-god 6
#Create 6 nodes
set n0 [$ns node]
$n0 set X_ 630
$n0 set Y_ 501
$n0 set Z_ 0.0
$ns initial_node_pos $n0 20
set n1 [$ns node]
$n1 set X_ 454
$n1 set Y_ 340
$n1 set Z_ 0.0
$ns initial_node_pos $n1 20
set n2 [$ns node]
$n2 set X_ 785
$n2 set Y_ 326
$n2 set Z_ 0.0
$ns initial_node_pos $n2 20
set n3 [$ns node]
$n3 set X_ 270
$n3 set Y_ 190
$n3 set Z_ 0.0
ACSCE Page 22
CN Lab Manual

$ns initial_node_pos $n3 20


set n4 [$ns node]
$n4 set X_ 539
$n4 set Y_ 131
$n4 set Z_ 0.0
$ns initial_node_pos $n4 20
set n5 [$ns node]
$n5 set X_ 964
$n5 set Y_ 177
$n5 set Z_ 0.0
$ns initial_node_pos $n5 20
#===================================
#Agents Definition
#===================================
#Setup a UDP connection
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
set null1 [new Agent/Null]
$ns attach-agent $n4 $null1
$ns connect $udp0 $null1
$udp0 set packetSize_ 1500

#Setup a TCP connection


set tcp0 [new Agent/TCP]
$ns attach-agent $n3 $tcp0
set sink1 [new Agent/TCPSink]
$ns attach-agent $n5 $sink1
$ns connect $tcp0 $sink1

#===================================
#Applications Definition
#===================================
#Setup a CBR Application over UDP connection
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
$cbr0 set packetSize_ 1000
$cbr0 set rate_ 1.0Mb
$cbr0 set random_ null

#Setup a FTP Application over TCP connection


set ftp0 [new Application/FTP]
ACSCE Page 23
CN Lab Manual

$ftp0 attach-agent $tcp0

#===================================
#Termination
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile

exec nam p4.nam &


exec echo "Number of packets dropped is:" &
exec grep -c "^D" p4.tr &
exit 0

$ns at 1.0 "$cbr0 start"


$ns at 2.0 "$ftp0 start"
$ns at 180.0 "$ftp0 stop"
$ns at 200.0 "$cbr0 stop"
$ns at 200.0 "finish"
$ns at 70 "$n4 set dest 100 60 20"
$ns at 100 "$n4 set dest 700 300 20"
$ns at 150 "$n4 set dest 900 200 20"
$ns run
#===================================
#CODE TO BE SAVED AS .awk FILE
#===================================
BEGIN{
count1=0
count2=0
pack1=0
pack2=0
time1=0
time2=0
}
{
if($1=="r"&&$3=="_1_"&&$4=="RTR")
ACSCE Page 24
CN Lab Manual

{
count1++
pack1=pack1+$8
time1=$2
}
if($1=="r"&&$3=="_2_"&&$4=="RTR")
{
count2++
pack2=pack2+$8
time2=$2
}
}
END{
printf("The Throughput from n0 to n1: %fMbps\n",((count1*pack1*8)/(time1*1000000)));
printf("The Throughput from n1 to n2: %fMbps\n",((count2*pack2*8)/(time2*1000000)));
}

Output:

ACSCE Page 25
CN Lab Manual

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:

ACSCE Page 26
CN Lab Manual

#set Parameters
set stop 100 ;# Stop time.

# Topology
set type gsm ;#type of link:

# AQM parameters
set minth 30
set maxth 0
set adaptive 1 ;# 1 for Adaptive RED, 0 for plain RED

# Traffic generation.
set flows 0 ;# number of long-lived TCP flows
set window 30 ;# window for long-lived traffic

# Plotting statistics.
set opt(wrap) 100 ; # wrap plots?
set opt(srcTrace) is ;# where to plot traffic
set opt(dstTrace) bs2 ;# where to plot traffic

#default downlink bandwidth in bps


set bwDL(gsm) 9600

#default downlink propagation delay in seconds


set propDL(gsm) .500

set ns [new Simulator]

set tf [open Mlab5.tr w]


$ns trace-all $tf

ACSCE Page 27
CN Lab Manual

set nodes(is) [$ns node]


set nodes(ms) [$ns node]
set nodes(bs1) [$ns node]
set nodes(bs2) [$ns node]
set nodes(lp) [$ns node]

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 "GSM Cell Topology"
}

proc set_link_params {t} {

global ns nodes bwDL propDL


$ns bandwidth $nodes(bs1) $nodes(ms) $bwDL($t) duplex
$ns bandwidth $nodes(bs2) $nodes(ms) $bwDL($t) duplex

$ns delay $nodes(bs1) $nodes(ms) $propDL($t) duplex


$ns delay $nodes(bs2) $nodes(ms) $propDL($t) duplex

$ns queue-limit $nodes(bs1) $nodes(ms) 10


$ns queue-limit $nodes(bs2) $nodes(ms) 10
}

# RED and TCP parameter


Queue/RED set adaptive_ $adaptive
Queue/RED set thresh_ $minth
Queue/RED set maxthresh_ $maxth
Agent/TCP set window_ $window

#Create topology
switch $type {
gsm {cell_topo}
}

ACSCE Page 28
CN Lab Manual

set_link_params $type
$ns insert-delayer $nodes(ms) $nodes(bs1) [new Delayer]
$ns insert-delayer $nodes(ms) $nodes(bs2) [new Delayer]

# Set up forward TCP connection


if {$flows == 0} {
set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 nodes(lp) 0]
set ftp1 [[set tcp1] attach-app FTP]
$ns at 0.8 "[set ftp1] start"
}

proc stop {} {
global nodes opt tf
set wrap $opt(wrap)
set sid [$nodes($opt(srcTrace)) id]
set did [$nodes($opt(dstTrace)) id]

set a "Mlab5.tr"

set GETRC "/var/cn/ns-allinone-2.35/ns-2.35/bin/getrc"


set RAW2XG "/var/cn/ns-allinone-2.35/ns-2.35/bin/raw2xg"

exec $GETRC -s $sid -d $did -f 0 Mlab5.tr | \


$RAW2XG -s 0.01 -m $wrap -r > plot.xgr

exec $GETRC -s $did -d $sid -f 0 Mlab5.tr | \


$RAW2XG -a -s 0.01 -m $wrap >> plot.xgr

exec xgraph -x time -y packets plot.xgr &


exit 0
}
$ns at $stop "stop"
$ns run

Output:

ACSCE Page 29
CN Lab Manual

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 cdma One, 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

ACSCE Page 30
CN Lab Manual

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:

#set parameters
set stop 100 ;# Stop time.

# Topology
set type umts ;#type of link

# AQM parameters
set minth 30
set maxth 0
set adaptive 1 ;# 1 for Adaptive RED, 0 for plain RED

# Traffic generation.
set flows 0 ;# number of long-lived TCP flows
set window 30 ;# window for long-lived traffic

# Plotting statics.
set opt(wrap) 100 ;# wrap plots?
set opt(srcTrace) is ;# where to plot traffic
set opt(dstTrace) bs2 ;# where to plot traffic

ACSCE Page 31
CN Lab Manual

#default downlink bandwidth in bps


set bwDL(umts) 384000

#default downlink propagation delay in seconds


set propDL(umts) .150

set ns [new Simulator]

set tf [open Mlab6.tr w]


$ns trace-all $tf

set nodes(is) [$ns node]


set nodes(ms) [$ns node]
set nodes(bs1) [$ns node]
set nodes(bs2) [$ns node]
set nodes(lp) [$ns node]

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 " umts Cell Topology"
}

proc set_link_para {t} {


global ns nodes bwDL propDL
$ns bandwidth $nodes(bs1) $nodes(ms) $bwDL($t) duplex
$ns bandwidth $nodes(bs2) $nodes(ms) $bwDL($t) duplex

$ns delay $nodes(bs1) $nodes(ms) $propDL($t) duplex


$ns delay $nodes(bs2) $nodes(ms) $propDL($t) duplex

$ns queue-limit $nodes(bs1) $nodes(ms) 20


$ns queue-limit $nodes(bs2) $nodes(ms) 20
}

ACSCE Page 32
CN Lab Manual

# RED and TCP parameters


Queue/RED set adaptive_ $adaptive
Queue/RED set thresh_ $minth
Queue/RED set maxthresh_ $maxth
Agent/TCP set window_ $window

#Create topology
switch $type {
umts {cell_topo}
}

set_link_para $type
$ns insert-delayer $nodes(ms) $nodes(bs1) [new Delayer]
$ns insert-delayer $nodes(ms) $nodes(bs2) [new Delayer]

# Set up forward TCP connection


if {$flows == 0} {
set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0]
set ftp1 [[set tcp1] attach-app FTP]
$ns at 0.8 "[set ftp1] start"
}

proc stop {} {
global nodes opt tf
set wrap $opt(wrap)
set sid [$nodes($opt(srcTrace)) id]
set did [$nodes($opt(dstTrace)) id]

set a "Mlab6.tr"

set GETRC "/var/cn/ns-allinone-2.35/ns-2.35/bin/getrc"


set RAW2XG "/var/cn/ns-allinone-2.35/ns-2.35/bin/raw2xg"

exec $GETRC -s $sid -d $did -f 0 Mlab6.tr | \


$RAW2XG -s 0.01 -m $wrap -r > plot6.xgr

exec $GETRC -s $did -d $sid -f 0 Mlab6.tr | \


$RAW2XG -a -s 0.01 -m $wrap >> plot6.xgr
ACSCE Page 33
CN Lab Manual

exec xgraph -x time -y packets plot6.xgr &


exit 0
}
$ns at $stop "stop"
$ns run

Output:

PART B (Implement the following in Java)

7. Write a program for error detecting code using CRC-CCITT (16- bits).

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.

ACSCE Page 34
CN Lab Manual

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 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 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.
Table 1: International Standard CRC Polynomials
CRC-CCITT CRC-16 CRC-32
Checksum 16 bits 16 bits 32 bits
Width

ACSCE Page 35
CN Lab Manual

Generator 10001000000100001 11000000000000101 100000100110000010001110110110111


Polynomial

Error detection with CRC


Consider a message represented by the polynomial M(x)
Consider a generating polynomial G(x)
This is used to generate a CRC = C(x) to be appended to M(x).
Note this G(x) is prime.
Steps:
1. Multiply M(x) by highest power in G(x). i.e. Add So much zeros to M(x).
2. Divide the result by G(x). The remainder = C(x).
Special case: This won't work if bitstring =all zeros. We don't allow such an
M(x).But M(x) bitstring = 1 will work, for example. Can divide 1101 into 1000.
3. If: x div y gives remainder c
that means: x = n y + c
Hence (x-c) = n y
(x-c) div y gives remainder 0
Here (x-c) = (x+c)
Hence (x+c) div y gives remainder 0
4. Transmit: T(x) = M(x) + C(x)
5. Receiver end: Receive T(x). Divide by G(x), should have remainder 0.
Note if G(x) has order n - highest power is xn,
then G(x) will cover (n+1) bits
and the remainder will cover n bits.
i.e. Add n bits (Zeros) to message.
Some CRC polynomials that are actually used
Some CRC polynomials
 CRC-8:
x8+x2+x+1
o Used in: 802.16 (along with error correction).
 CRC-CCITT:
x16+x12+x5+1

ACSCE Page 36
CN Lab Manual

o Used in: HDLC, SDLC, PPP default


 IBM-CRC-16 (ANSI):
x16+x15+x2+1
 802.3:
x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1
o Used in: Ethernet, PPP rootion

Source Code:

import java.util.Scanner;
import java.io.*;
public class CRC1 {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

//Input Data Stream


System.out.print("Enter message bits: ");
String message = sc.nextLine();
System.out.print("Enter generator: ");
String generator = sc.nextLine();
int data[] = new int[message.length() + generator.length() - 1];
int divisor[] = new int[generator.length()];
for(int i=0;i<message.length();i++)
data[i] = Integer.parseInt(message.charAt(i)+"");
for(int i=0;i<generator.length();i++)
divisor[i] = Integer.parseInt(generator.charAt(i)+"");

//Calculation of CRC
for(int i=0;i<message.length();i++)
{
if(data[i]==1)
for(int j=0;j<divisor.length;j++)
data[i+j] ^= divisor[j];
}

//Display CRC

ACSCE Page 37
CN Lab Manual

System.out.print("The checksum code is: ");


for(int i=0;i<message.length();i++)
data[i] = Integer.parseInt(message.charAt(i)+"");
for(int i=0;i<data.length;i++)
System.out.print(data[i]);
System.out.println();

//Check for input CRC code


System.out.print("Enter checksum code: ");
message = sc.nextLine();
System.out.print("Enter generator: ");
generator = sc.nextLine();
data = new int[message.length() + generator.length() - 1];
divisor = new int[generator.length()];
for(int i=0;i<message.length();i++)
data[i] = Integer.parseInt(message.charAt(i)+"");
for(int i=0;i<generator.length();i++)
divisor[i] = Integer.parseInt(generator.charAt(i)+"");

//Calculation of remainder
for(int i=0;i<message.length();i++) {
if(data[i]==1)
for(int j=0;j<divisor.length;j++)
data[i+j] ^= divisor[j];
}

//Display validity of data


boolean valid = true;
for(int i=0;i<data.length;i++)
if(data[i]==1){
valid = false;
break;
}

if(valid==true)
System.out.println("Data stream is valid");
else
System.out.println("Data stream is invalid. CRC error occurred.");
}

}
ACSCE Page 38
CN Lab Manual

Output:

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 upd 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

ACSCE Page 39
CN Lab Manual

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

Implementation Algorithm:

1. send my routing table to all my neighbors whenever my link table changes


2. when I get a routing table from a neighbor on port P with link metric M:
a. add L to each of the neighbor's metrics
b. for each entry (D, P', M') in the updated neighbor's table:
i. if I do not have an entry for D, add (D, P, M') to my routing table
ii. if I have an entry for D with metric M", add (D, P, M') to my routing table
if M' < M"
3. if my routing table has changed, send all the new entries to all my neighbors.

Source Code:

import java.util.Scanner;
public class ford
{
private int D[];
private int num_ver;
public static final int MAX_VALUE = 999;
public ford(int num_ver)
{
this.num_ver = num_ver;
D = new int[num_ver + 1];
}

public void BellmanFordEvaluation(int source, int A[][])


{

ACSCE Page 40
CN Lab Manual

for (int node = 1; node <= num_ver; node++)


{
D[node] = MAX_VALUE;
}

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]);
}
}

public static void main(String[ ] args)


{
ACSCE Page 41
CN Lab Manual

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();
ford b = new ford (num_ver);
b.BellmanFordEvaluation(source, A);
scanner.close();
}
}

Output:

ACSCE Page 42
CN Lab Manual

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. Using
TCP/IP Sockets, write a client-server program to make client sending the file name and the
server to 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

ACSCE Page 43
CN Lab Manual

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:

// TCP Server

import java.net.*;
import java.io.*;
public class TCPS
{
public static void main(String[] args) throws Exception
{
ServerSocket sersock=new ServerSocket(4000);
System.out.println("Server ready for connection");
Socket sock=sersock.accept();
System.out.println("Connection Is successful and waiting for chatting");
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();
}
}
TCP Client
import java.net.*;
import java.io.*;
public class TCPC

ACSCE Page 44
CN Lab Manual

{
public static void main(String[] args) throws Exception
{
Socket sock=new Socket("127.0.01",4000);
System.out.println("Enter the filename");
BufferedReader keyRead=new BufferedReader(new InputStreamReader(System.in));
String fname=keyRead.readLine();
OutputStream ostream=sock.getOutputStream();
PrintWriter pwrite=new PrintWriter(ostream,true);
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);
}
pwrite.close();
socketRead.close();
keyRead.close();
}
}

Output:

ACSCE Page 45
CN Lab Manual

10. Write a program on datagram socket for client/server to display the messages on client
side, typed at the server side.

ACSCE Page 46
CN Lab Manual

A datagram socket is the one for sending or receiving point for a packet delivery service.
Each packet sent or received on a datagram socket is individually addressed and routed. Multiple
packets sent from one machine to another may be routed differently, and may arrive in any order.
//UDP Sever
import java.net.*;
import java.net.InetAddress;
class UDPServer
{
public static void main(String args[])throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData=new byte[1024];
byte[] sendData=new byte[1024];
while(true)
{
System.out.println("Server is Up");
DatagramPacket receivePacket=new DatagramPacket(receiveData,receiveData.length);
serverSocket.receive(receivePacket);
String sentence=new String(receivePacket.getData());
System.out.println("RECEIVED:"+sentence);
InetAddress IPAddress=receivePacket.getAddress();
int port=receivePacket.getPort();
String capitalizedSentence=sentence.toUpperCase();
sendData=capitalizedSentence.getBytes();
DatagramPacket sendPacket=new
DatagramPacket(sendData,sendData.length,IPAddress,port);
serverSocket.send(sendPacket);
}
}
}

//UDP Client

import java.io.*;
import java.net.*;
import java.net.InetAddress;
class UDPClient
{
public static void main(String[] args)throws Exception
{

ACSCE Page 47
CN Lab Manual

BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));


DatagramSocket clientSocket=new DatagramSocket();
InetAddress IPAddress=InetAddress.getByName("localhost");
byte[] sendData=new byte[1024];
byte[] receiveData=new byte[1024];
System.out.println("Enter the sting to be converted in to Upper case");
String sentence=inFromUser.readLine();
sendData=sentence.getBytes();
DatagramPacket sendPacket=new
DatagramPacket(sendData,sendData.length,IPAddress,9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket=new DatagramPacket(receiveData,receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence=new String(receivePacket.getData());
System.out.println("FROM SERVER:"+modifiedSentence);
clientSocket.close();
}
}

Output:

11. Write a program for simple RSA algorithm to encrypt and decrypt the data.

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

ACSCE Page 48
CN Lab Manual

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.

A very simple example of RSA encryption.


This is an extremely simple example using numbers you can work out on a pocket calculator
(those of you over the age of 35 can probably even do it by hand on paper).
1. Select primes p = 11, q = 3.
2. n = pq = 11.3 = 33
phi = (p-1)(q-1) = 10.2 = 20
3. Choose e=3
Check gcd(e, p-1) = gcd(3, 10) = 1 (i.e. 3 and 10 have no common factors except 1), and
check gcd(e, q-1) = gcd(3, 2) = 1
therefore gcd(e, phi) = gcd(e, (p-1)(q-1)) = gcd(3, 20) = 1
4. Compute d such that ed ≡ 1 (mod phi)
i.e. compute d = e^-1 mod phi = 3^-1 mod 20
i.e. find a value for d such that phi divides (ed-1)
i.e. find d such that 20 divides 3d-1.
Simple testing (d = 1, 2, ...) gives d = 7
Check: ed-1 = 3.7 - 1 = 20, which is divisible by phi.
5. Public key = (n, e) = (33, 3) Private key = (n, d) = (33, 7). This is actually the smallest
possible value for the modulus n for which the RSA algorithm works.
Now say we want to encrypt the message m = 7,
c = m^e mod n = 7^3 mod 33 = 343 mod 33 = 13.
Hence the ciphertext c = 13.
To check decryption we compute
m' = c^d mod n = 13^7 mod 33 = 7.
Note that we don't have to calculate the full value of 13 to the power 7 here. We can make use of
the fact that a = bc mod n = (b mod n).(c mod n) mod n so we can break down a potentially large

ACSCE Page 49
CN Lab Manual

number into its components and combine the results of easier, smaller calculations to calculate
the final value.
One way of calculating m' is as follows:-
m' = 13^7 mod 33 = 13^(3+3+1) mod 33 = 13^3.13^3.13 mod 33
= (13^3 mod 33).(13^3 mod 33).(13 mod 33) mod 33
= (2197 mod 33).(2197 mod 33).(13 mod 33) mod 33
= 19.19.13 mod 33 = 4693 mod 33
= 7.
Now if we calculate the cipher text c for all the possible values of m (0 to 32), we get
m 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
c 0 1 8 27 31 26 18 13 17 3 10 11 12 19 5 9 4

m 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
c 29 24 28 14 21 22 23 30 16 20 15 7 2 6 25 32
Note that all 33 values of m (0 to 32) map to a unique code c in the same range in a sort
of random manner. In this case we have nine values of m that map to the same value of c - these
are known as unconcealed messages. m = 0 and 1 will always do this for any N, no matter how
large. But in practice, higher values shouldn't be a problem when we use large values for N.
If we wanted to use this system to keep secrets, we could let A=2, B=3, ..., Z=27. (We
specifically avoid 0 and 1 here for the reason given above). Thus the plaintext message
"HELLOWORLD" would be represented by the set of integers m1, m2, ...
{9,6,13,13,16,24,16,19,13,5}
Using our table above, we obtain ciphertext integers c1, c2, ...
{3,18,19,19,4,30,4,28,19,26}
Note that this example is no more secure than using a simple Caesar substitution
cipher, but it serves to illustrate a simple example of the mechanics of RSA encryption.
Remember that calculating m^e mod n is easy, but calculating the inverse c^-e mod n
is very difficult, well, for large n's anyway. However, if we can factor n into its prime factors
p and q, the solution becomes easy again, even for large n's. Obviously, if we can get hold of
the secret exponent d, the solution is easy, too.

Key Generation Algorithm


ACSCE Page 50
CN Lab Manual

1. Generate two large random primes, p and q, of approximately equal size such that their
product n = pq is of the required bit length, e.g. 1024 bits. [See note 1].
2. Compute n = pq and (φ) phi = (p-1)(q-1).
3. Choose an integer e, 1 < e < phi, such that gcd(e, phi) = 1. [See note 2].
4. Compute the secret exponent d, 1 < d < phi, such that
ed ≡ 1 (mod phi). [See note 3].
5. The public key is (n, e) and the private key is (n, d). The values of p, q, and phi should
also be kept secret.
 n is known as the modulus.
 e is known as the public exponent or encryption exponent.
 d is known as the secret exponent or decryption exponent.

Encryption

Sender A does the following:-


1. Obtains the recipient B's public key (n, e).
2. Represents the plaintext message as a positive integer m [see note 4].
3. Computes the ciphertext c = m^e mod n.
4. Sends the ciphertext c to B.

Decryption

Recipient B does the following:-


1. Uses his private key (n, d) to compute m = c^d mod n.
2. Extracts the plaintext from the integer representative m.

Source Code:
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
public class RSA
{
private BigInteger p,q,N,phi,e,d;

ACSCE Page 51
CN Lab Manual

private int bitlength=1024;


private Random r;
public RSA()
{
r=new Random();
p=BigInteger.probablePrime(bitlength,r);
q=BigInteger.probablePrime(bitlength,r);
System.out.println("Prime number p is"+p);
System.out.println("prime number q is"+q);
N=p.multiply(q);
phi=p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e=BigInteger.probablePrime(bitlength/2,r);
while(phi.gcd(e).compareTo(BigInteger.ONE)>0&&e.compareTo(phi)<0)
{
e.add(BigInteger.ONE);
}
System.out.println("Public key is"+e);
d=e.modInverse(phi);
System.out.println("Private key is"+d);
}
public RSA(BigInteger e,BigInteger d,BigInteger N)
{
this.e=e;
this.d=d;
this.N=N;
}
public static void main(String[] args)throws IOException
{
RSA rsa=new RSA();
DataInputStream in=new DataInputStream(System.in);
String testString;
System.out.println("Enter the plain text:");
testString=in.readLine();
System.out.println("Encrypting string:"+testString);
System.out.println("string in bytes:"+bytesToString(testString.getBytes()));
byte[] encrypted=rsa.encrypt(testString.getBytes());
byte[] decrypted=rsa.decrypt(encrypted);
System.out.println("Dcrypting Bytes:"+bytesToString(decrypted));
System.out.println("Dcrypted string:"+new String(decrypted));
}
private static String bytesToString(byte[] encrypted)
ACSCE Page 52
CN Lab Manual

{
String test=" ";
for(byte b:encrypted)
{
test+=Byte.toString(b);
}
return test;
}
public byte[]encrypt(byte[]message)
{
return(new BigInteger(message)).modPow(e,N).toByteArray();
}
public byte[]decrypt(byte[]message)
{
return(new BigInteger(message)).modPow(d,N).toByteArray();
}
}

Output:

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.

ACSCE Page 53
CN Lab Manual

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)).

Figure 2.4 - The leaky bucket traffic shaping algorithm

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.

Implementation Algorithm:

Steps:

1. Read The Data For Packets

2. Read The Queue Size

ACSCE Page 54
CN Lab Manual

3. Divide the Data into Packets

4. Assign the random Propagation delays for each packets to input into the bucket
(input_packet).

5. wlile((Clock++<5*total_packets)and (out_packets< total_paclets))

a. if (clock == input_packet)

i. insert into Queue

b. if (clock % 5 == 0 )

i. Remove packet from Queue

6. End
Source Code:
import java.util.Scanner;
import java.lang.*;
public class lab7 {
public static void main(String[] args)
{
int i;
int a[]=new int[20];
int buck_rem=0,buck_cap=4,rate=3,sent,recv;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of packets");
int n = in.nextInt();
System.out.println("Enter the packets");
for(i=1;i<=n;i++)
a[i]= in.nextInt();
System.out.println("Clock \t packet size \t accept \t sent \t remaining");
for(i=1;i<=n;i++)
{
if(a[i]!=0)
{
if(buck_rem+a[i]>buck_cap)
recv=-1;
else
ACSCE Page 55
CN Lab Manual

{
recv=a[i];
buck_rem+=a[i];
}
}
else
recv=0;
if(buck_rem!=0)
{
if(buck_rem<rate)
{sent=buck_rem;
buck_rem=0;
}
else
{
sent=rate;
buck_rem=buck_rem-rate;
}
}
else
sent=0;
if(recv==-1)
System.out.println(+i+ "\t\t" +a[i]+ "\t dropped \t" + sent +"\t" +buck_rem);
else
System.out.println(+i+ "\t\t" +a[i] +"\t\t" +recv +"\t" +sent + "\t" +buck_rem);
}
}
}

Output:

ACSCE Page 56
CN Lab Manual

ACSCE Page 57

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy