CN Lab Manual VTU
CN Lab Manual VTU
DEPARTMENT OF INFORMATION
SCIENCE & ENGINEERING
COMPUTER NETWORKS
LABORATORY MANUAL
18CSL57
V Semester - BE
Prepared by
Mr. Naitik S T/Ms. Sangeetha H
Asst. Professors
CONTENTS
PART A
Implement three nodes point – to – point network with duplex links between them. Set the queue
1
size, vary the bandwidth and find the number of packets dropped.
Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
3
window for different source / destination.
Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and determine
4
the performance with respect to transmission of packets.
Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or equivalent
5
environment.
Implement and study the performance of CDMA on NS2/NS3 (Using stack called Call net) or
6
equivalent environment.
PART B
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.
Using TCP/IP sockets, write a client – server program to make the client send the file name and to
9
make the server send back the contents of the requested file if present.
Write a program on datagram socket for client/server to display the messages on client side, typed
10
at the server side.
11 Write a program for simple RSA algorithm to encrypt and decrypt the data.
Introduction to NS-2
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. P
In general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviors.
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
o Hello World!
puts stdout{Hello, World!}
Hello, World!
o Simple Arithmetic
expr 7.2 / 4
o 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
o 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.
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 dta 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.
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”
Above script will be used to call “finish” at time 125sec.Indeed,the at method of the simulator
allows us to schedule events explicitly.
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.
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
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.
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”
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 id
Node Node Type Size Addr Addr Num
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.
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:
/-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:
$ awk –F”|” „$3 == “director” && $6 > 6700 {
kount =kount+1
printf “ %3f %20s %-12s %d\n”, kount,$2,$3,$6 }‟ empn.lst
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:
$awk „BEGIN {FS = “|”}
NF! =6 {
Print “Record No “, NR, “has”, “fields”}‟ empx.lst
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.
1.3 Pre-Requisite:
1.4 Procedure:
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
}
set n0 [$ns node] /* creates 4 nodes */
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
$ns duplex-link $n0 $n2 200Mb 10ms DropTail /*Letter M is capital Mb*/
$ns duplex-link $n1 $n2 100Mb 5ms DropTail /*D and T are capital*/
$ns duplex-link $n2 $n3 1Mb 1000ms DropTail
$ns run
AWK file
BEGIN{
c=0;
}
{
if($1=="d")
{
c++;
printf("%s\t%s\n",$5,$11);
}
}
END{
printf("The number of packets dropped =%d\n",c);
}
1. Open gedit editor and type program. Program name should have the extension “.tcl “
[root@localhost ~]# gedit lab1.tcl
2. Open gedit editor and type awk program. Program name should have the extension “.awk “
[root@localhost ~]# gedit lab1.awk
4. Here “ns” indicates network simulator. We get the topology shown in the snapshot. Now press the
play button in the simulation window and the simulation will begins.
7. Change Bandwidth, Queue limit in the TCL file. Repeat the steps
Topology:
1.5 Results:
1. What is bandwidth?
2. What is Queue size?
3. How to modify the no of packets dropped?
4. Why awk is used?
2.3 Pre-Requisite:
2.4 Procedure:
AWK file
BEGIN{
drop=0;
}
{
if($1=="d")
{
drop++;
}
}
END{
printf("Total number of %s packets dropped due to congestion =%d\n",$5,drop);
}
2. Open gedit editor and type awk program. Program name should have the extension “.awk “
[root@localhost ~]# gedit lab2.awk
4. Here “ns” indicates network simulator. We get the topology shown in the snapshot. Now press the
play button in the simulation window and the simulation will begins.
Topology:
1.5 Results:
Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.
3.3 Pre-Requisite:
Basics of Networking, NS2 ,TCL script
3.4 Procedure:
$ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/DropTail Mac/802_3
/* should come in single line */
$ns duplex-link $n4 $n5 1Mb 1ms DropTail
$tcp0 trace cwnd_ /* must put underscore ( _ ) after cwnd and no space between them*/
$tcp2 trace cwnd_
proc finish { } {
global ns nf tf
$ns flush-trace close $tf
close $nf
exec nam lab3.nam &
exit 0
AWK file
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 {
}
1. Open gedit editor and type program. Program name should have the extension “.tcl”
[root@localhost ~]# gedit lab3.tcl
2. Open gedit editor and type awk program. Program name should have the extension “.awk
“
[root@localhost ~]# gedit lab3.awk
[root@localhost~]# xgraph a1 a2
Here we are using the congestion window trace files i.e. file1.tr and file2.tr and we are
redirecting the contents of those files to new files say a1 and a2 using output redirection
operator (>).
Department of ISE, SCEM Page 26
COMPUTER NETWORK LABORATORY [18CSL57]
6. Change Bandwidth, Queue limit in the TCL file. Repeat the steps
1.5 Results:
Xgraph Result:
Implement simple ESS and with transmitting nodes in wire-less LAN by simulation
and determine the performance with respect to transmission of packets.
Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
window for different source / destination.
3.3Pre-Requisite:
Basics of Networking, NS2 ,TCL script
3.4 Procedure:
-topoInstance $topo \
-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
AWK file
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)));
}
1. Open gedit editor and type program. Program name should have the extension “.tcl “
[root@localhost ~]# gedit lab4.tcl
2. Open gedit editor and type awk program. Program name should have the extension “.awk “
[root@localhost ~]# gedit lab4.awk
4. Here “ns” indicates network simulator. We get the topology shown in the snapshot. Now press the
play button in the simulation window and the simulation will begins.
4.5 Results:
Trace file
Output:
5.3 Pre-Requisite:
Basics of Networking, NS2 ,TCL script
5.4 Procedure
5.tcl:
# This script is created by NSG2 beta1
# <http://wushoupong.googlepages.com/nsg>
#===================================
# Simulation parameters setup
#===================================
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagation model
set val(netif) Phy/WirelessPhy ;# network interface type
set val(mac) Mac/802_11 ;# MAC type
set val(ifq) Queue/DropTail/PriQueue ;# interface queue type
set val(ll) LL ;# link layer type
set val(ant) Antenna/OmniAntenna ;# antenna model
set val(ifqlen) 50 ;# max packet in ifq
set val(nn) 8 ;# number of mobilenodes
set val(rp) AODV ;# routing protocol
set val(x) 1184 ;# X dimension of topography
set val(y) 640 ;# Y dimension of topography
set val(stop) 10.0 ;# time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-channel $chan \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON \
-movementTrace ON
#===================================
# Nodes Definition
#===================================
#Create 8 nodes
set n0 [$ns node]
$n0 set X_ 149
$n0 set Y_ 219
$n0 set Z_ 0.0
$ns initial_node_pos $n0 20
set n1 [$ns node]
$n1 set X_ 321
$n1 set Y_ 321
$n1 set Z_ 0.0
$ns initial_node_pos $n1 20
set n2 [$ns node]
$n2 set X_ 474
$n2 set Y_ 426
$n2 set Z_ 0.0
5.awk
BEGIN{
count1=0;
pack1=0;
time1=0;
}
{
if($1=="r"&& $3=="_7_"&& $4=="AGT")
{
count1++;
pack1= pack1+$8;
time1=$2;
}
}
END{
printf("The throughput from n0 to n7: %f Mbps\n",((count1*pack1*8)/(time1*1000000)));
}
Execution:
student@student-OptiPlex-330:~/ns2$ java -jar nsg2.1.jar
student@student-OptiPlex-330:~/ns2$ ns 5.tcl
student@student-OptiPlex-330:~/ns2$ gedit 5.awk
student@student-OptiPlex-330:~/ns2$ awk –f 5.awk 5.tr
The throughput from n0 to n7: 5.478273 Mbps
5.5 Results:
6.3 Pre-Requisite:
Basics of Networking, NCTUNS GUI working ,commands
6.4 Procedure:
6.5 Results:
Write a program for error detecting code using CRC-CCITT (16- bits).
7.3 Pre-Requisites:
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.
101
----------------
10011 / 1 1 0 1 1 0 1
10011| |
--------- –---| |
10000|
Department of ISE, SCEM Page 45
COMPUTER NETWORK LABORATORY [18CSL57]
00000|
-------------- |
100001
10011
-----------------
1 1 1 0 = 14 remainder
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
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:
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.
7.4 Procedure:
Source Code:
import java.io.*;
import java.util.Scanner;
class crc
{
public static void main(String args[])
{
int i,j,n,g,check,flag,s,a;
int arr[]=new int[30],gen[]=new int[20],b[]=new int[20],q[]=new int[20],x[]=new int[20];
check = 0;
flag=0;
System.out.println("\t****** CYCLIC REDUNDANCY CHECK ******");
System.out.println("Transmitter side:");
System.out.println("Enter no. of data bits:");
Scanner in = new Scanner(System.in);
n= in.nextInt();
System.out.println(" Enter the data to be sent:");
for(i=0;i<n;i++)
arr[i]=in.nextInt();
System.out.println(" Enter the no. of divisor bits : ");
g = in.nextInt();
do
{
System.out.println("Enter the generator data");
for(j=0;j<g;j++)
gen[j] = in.nextInt();
}while(gen[0]!=1);
System.out.print("\t The divisor is: ");
for(j=0;j<g;j++)
System.out.print(gen[j]);
System.out.println();
a=n+(g-1);
System.out.print("\t The transmitter side data is: ");
for(i=0;i<j;i++)
arr[n+i] =0;
for(i=0;i<a;i++)
System.out.print(arr[i]);
System.out.println();
for(i=0;i<n;i++)
q[i]=arr[i];
for(i=0;i<n;i++)
{
if(arr[i]==0)
{
for(j=i;j<g;j++)
arr[j]=arr[j]^0;
}
else
{
for(int k=0;k<17;k++)
{
arr[i+k]=arr[i+k]^gen[k];
}
}
}
System.out.print("\t The CRC is:");
for(i=n;i<a;i++)
System.out.print(arr[i]);
for(i=n;i<a;i++)
q[i]=arr[i];
//for(i=0;i<a;i++)
//System.out.print(q[i]);
System.out.println();
System.out.println(" Reciever side:");
System.out.println(" Enter no. of data bits recieved:");
n=in.nextInt();
System.out.println("Enter the data recieved");
for(i=0;i<n;i++)
arr[i]=in.nextInt();
for(i=n;i<a;i++)
for(j=g-1;j<0;j--)
arr[i]=q[j];
System.out.print(" The reciever side data is: ");
for(i=0;i<a;i++)
System.out.print(arr[i]);
for(i=0;i<n;i++)
q[i]=arr[i];
for(i=0;i<n;i++)
{
if(arr[i]==0)
{
for(j=i;j<g+i;j++)
arr[j]=arr[j]^0;
}
else
{
for(int k=0;k<17;k++)
{
arr[i+k]=arr[i+k]^gen[k];
}
}
}
System.out.println();
System.out.print(" The CRC at the reciever is:");
for(i=n;i<a;i++)
System.out.print(arr[i]);
for(i=n;i<a;i++)
{
if(arr[i]==1)
{
flag=1;
break;
}
else
check=0;
}
System.out.println();
System.out.print(" Result of CRC error detection is: ");
if(flag==0 && check==0)
System.out.println(" Data is accepted successfully");
else
System.out.println(" Resend the data again");
}
}
7.5 Results:
Write a program to find the shortest path between vertices using bellman-ford algorithm
8.3 Pre-Requisite:
Distance Vector Algorithm is a decentralized routing algorithm that requires that each router simply
inform its neighbours of its routing table. For each network path, the receiving routers pick the
neighbour 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:
Bellman-Ford and 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 neighbouring 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
neighbours 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.
8.4 Procedure:
Source Code:
import java.util.Scanner;
public class BellmanFord
{
private int distances[];
private int numberofvertices;
public static final int MAX_VALUE = 999;
public BellmanFord(int numberofvertices)
{
this.numberofvertices= numberofvertices;
distances = new int[numberofvertices+1];
}
public void BellmanFordEvaluation(int source,int adjacencymatrix[][])
{
for(int node=1;node<=numberofvertices;node++)
{
distances[node]=MAX_VALUE;
}
distances[source]=0;
for(int node=1;node<=numberofvertices-1;node++)
{
for(int sourcenode=1;sourcenode<=numberofvertices;sourcenode++)
{
for(int destinationnode=1;destinationnode<=numberofvertices;
destinationnode++)
{
if(adjacencymatrix[sourcenode][destinationnode]!=MAX_VALUE)
{
if(distances[destinationnode]>distances[sourcenode] +
adjacencymatrix[sourcenode][destinationnode])
distances[destinationnode]=distances[sourcenode]+adjacencymatrix[sourcenode]
[destinationnode];
}
}
}
}
for (int sourcenode=1;sourcenode<=numberofvertices;sourcenode++)
{
for(int destinationnode=1;destinationnode<=numberofvertices;
destinationnode++)
{
if(adjacencymatrix[sourcenode][destinationnode]!=MAX_VALUE)
{
if(distances[destinationnode]>distances[sourcenode] +
adjacencymatrix[sourcenode][destinationnode])
System.out.println("The graph contains negative edge cycle");
}
}
}
for(int vertex=1;vertex<=numberofvertices;vertex++)
{
System.out.println("Distance of source "+source+" to "+vertex+" is
"+distances[vertex]);
}
}
public static void main(String args[])
{
int numberofvertices=0;
int source,destination;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of vertices");
numberofvertices=scanner.nextInt();
int adjacencymatrix[][]= new int[numberofvertices+1][numberofvertices+1];
System.out.println("Enter the adjacency matrix");
for(int sourcenode=1;sourcenode<=numberofvertices;sourcenode++)
{
for(int destinationnode=1;destinationnode<=numberofvertices;
destinationnode++)
{
adjacencymatrix[sourcenode][destinationnode]=scanner.nextInt();
if(sourcenode==destinationnode)
{
adjacencymatrix[sourcenode][destinationnode]=0;
continue;
}
if(adjacencymatrix[sourcenode][destinationnode]==0)
{
adjacencymatrix[sourcenode][destinationnode]=MAX_VALUE;
}
}
}
System.out.println("Enter the source vertex");
source=scanner.nextInt();
BellmanFord bellmanford = new BellmanFord(numberofvertices);
bellmanford.BellmanFordEvaluation(source,adjacencymatrix);
}
}
8.5 Results:
9.3 Pre-requisite:
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.
9.4 Procedure:
Source Code:
Server Program:
import java.net.*;
import java.io.*;
public class Cserver
{
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));
Client Program:
import java.io.*;
import java.net.*;
9.5 Results:
Server Side
Client Side:
10.3 Pre-requisite:
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.
10.4 Procedure:
Source Code:
import java.net.*;
class WriteServer
{
public static int serverPort = 1150;
public static int clientPort = 1160;
public static int buffer_size =1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];
public static void TheServer() throws Exception
{
int pos=0;
while(true)
{
int c = System.in.read();
switch(c)
{
case -1: System.out.println("Server Quits");
return;
case '\r':break;
case '\n':ds.send(new
DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort));
pos=0;
break;
default:buffer[pos++]=(byte) c;
}
}
}
public static void TheClient() throws Exception
{
while(true)
{
DatagramPacket p = new DatagramPacket(buffer,buffer.length);
ds.receive(p);
System.out.println(new String (p.getData(),0,p.getLength()));
}
}
public static void main(String args[]) throws Exception
{
if(args.length==1)
{
ds = new DatagramSocket(serverPort);
TheServer();
}
else
{
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}
10.5 Results:
Write a program for simple RSA algorithm to encrypt and decrypt the data.
11.3 Pre-Requisite:
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.
11.4 Procedure :
Source Code:
import java.util.*;
import java.io.*;
class rsa
{
static int mult(int x,int y,int n)
{
int k=1;
int j;
for (j=1; j<=y; j++)
k = (k * x) % n;
return ( int) k;
}
public static void main (String arg[])throws Exception
{
Scanner s=new Scanner(System.in);
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String msg1;
int pt[]=new int[100];
int ct[]=new int[100];
int a,b, n, d, e,Z, p, q, i,temp,et;
System.out.println("Enter prime No.s p,q :");
p=s.nextInt();
q=s.nextInt();
n = p*q;
Z=(p-1)*(q-1);
System.out.println("\nSelect e value:");
e=s.nextInt();
System.out.printf("Enter message : ");
msg1=br.readLine();
char msg[]=msg1.toCharArray();
for(i=0;i<msg.length;i++)
pt[i]=msg[i];
for(d=1;d<Z;++d)
if(((e*d)%Z)==1) break;
System.out.println("p="+""+p+"\tq="+q+"\tn="+n+"\tz="+Z+"\te="+e+"
\td="+d);
System.out.println("\nCipher Text = ");
for(i=0; i<msg.length; i++)
ct[i] = mult(pt[i], e,n);
for(i=0; i<msg.length; i++)
System.out.print("\t"+ct[i]);
System.out.println("\nPlain Text = ");
for(i=0; i<msg.length; i++)
pt[i] = mult(ct[i], d,n) ;
for(i=0; i<msg.length; i++)
System.out.print((char)pt[i]);
}
}
11.5 Results:
12.3 Pre-requisite:
The main concept of the leaky bucket algorithm is that the output data flow remains constant
despite the variant input traffic, such as the water flow in a bucket with a small hole at the bottom.
In case the bucket contains water (or packets) then the output flow follows a constant rate, while if
the bucket is full any additional load will be lost because of spill over. In a similar way if the bucket is
empty the output will be zero. From network perspective, leaky bucket consists of a finite queue
(bucket) where all the incoming packets are stored in case there is space in the queue, otherwise the
packets are discarded. In order to regulate the output flow, leaky bucket transmits one packet from
the queue in a fixed time (e.g. at every clock tick). In the following figure we can notice the main
rationale of leaky bucket algorithm, for both the two approaches (e.g. leaky bucket with water (a)
and with packets (b)).
While leaky bucket eliminates completely bursty traffic by regulating the incoming data flow its
main drawback is that it drops packets if the bucket is full. Also, it doesn‘t take into account the idle
process of the sender which means that if the host doesn‘t transmit data for some time the bucket
becomes empty without permitting the transmission of any packet.
12.4 Procedure:
Source Code:
import java.io.*;
import java.util.Scanner;
class Leaky
{
public static int min(int x,int y)
{
if(x<y)
return x;
else
return y;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int drop=0,mini,n,cap,count=0,i;
12.5 Results: