COMPUTER NETWORKS LAB MANUAL- BCS502
COMPUTER NETWORKS LAB MANUAL- BCS502
COMPUTER NETWORKS LAB MANUAL- BCS502
DEPARTMENT OF
INFORMATION SCIENCE AND ENGINEERING
COMPUTER NETWORKS
Outcome Based Education (OBE) and Choice Based Credit System (CBCS)
Prepared By:
Dr. Jayasheela C. S,
Assistant Professor
Dept. of ISE, BIT
Computer Networks Laboratory- BCS502
VISION
To Establish and Develop the Institute as a Center of Higher Learning ever abreast with the
Expanding horizon of knowledge in the field of Engineering and Technology, with
entrepreneurial thinking, leadership excellence for life-long success and solve societal
problems.
MISSION
Provide high quality education in the Engineering disciplines from the undergraduate through
doctoral levels with creative academic and professional programs.
Establish mutual beneficial partnership with Industry, Alumni, Local, State and Central
Governments by Public Services Assistance and Collaborative Research.
Inculcate personality development through sports, cultural and extracurricular activities and
engage in the social, economic and professional challenges.
VISION:
Empower every student to be innovative, creative and productive in the field of Information
Technology by imparting quality technical education, developing skills and inculcating human
values.
MISSION:
Course Objectives:
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.
4. Develop a program for error detecting code using CRC-CCITT (16- bits).
5. Develop a program to implement a sliding window protocol in the data link layer.
6. Develop a program to find the shortest path between vertices using the Bellman-Ford and
path vector routing algorithm.
7. 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.
8. Develop a program on a datagram socket for client/server to display the messages on
client side, typed at the server side.
9. Develop a program for a simple RSA algorithm to encrypt and decrypt the data.
10. Develop a program for congestion control using a leaky bucket algorithm.
RUBRIC SHEET
Analysis
Write-Up & Results &
Sl. & Record Total
Experiment Name Implementation Tabulation
No Execution 5 Marks 15 Marks
3 Marks 3 Marks
4 Marks
Write a program for error
1 detecting code using CRC-
CCITT (16- bits).
Develop a program to
2 implement a sliding window
protocol in the data link layer.
Develop a program to find the
shortest path between vertices
3
using the Bellman-Ford and
path vector routing algorithm.
Using TCP/IP sockets, write a
client – server program to
make the client send the file
4
name and to make the server
send back the contents of the
requested file if present.
Implement three nodes point –
to – point network with duplex
links between them. Set the
5
queue size, vary the bandwidth,
and find the number of packets
dropped.
Develop a program on a
datagram socket for
6 client/server to display the
messages on client side, typed
at the server side.
Develop a program for a
7 simple RSA algorithm to
encrypt and decrypt the data.
Develop a program for
8 congestion control using a
leaky bucket algorithm
Implement transmission of
ping messages/trace route over
a network topology consisting
9
of 6 nodes and find the number
of packets dropped due to
congestion.
Implement an Ethernet LAN
using n nodes and set multiple
10 traffic nodes and plot
congestion window for
different source / destination.
Test-1
Test-2
1) Open vi editor and type program. Program name should have theextension “
.tcl ”
[root@localhost ~]# gedit lab1.tcl/vi lab1.tcl
2) Open vi editor and type awk program. Program name should have the
extension “.awk ”
[root@localhost ~]# gdit lab1.awk/vi lab1.awk
i) Here “ns” indicates network simulator. We get the topology shown inthe
snapshot.
ii) Now press the play button in the simulation window and thesimulation
will begins.
4) After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab1.awk lab1.tr
Introduction to NS-2:
Tcl scripting
Basics of TCL
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello,
World!}Hello,
World!
Procedures
proc Diag {a b} {
set c [expr sqrt($a * $a +
$b * $b)]return $c }
puts ―Diagonal of a 3, 4 right triangle
triangle is 5.0
NS Simulator Preliminaries.
Initialization and termination aspects of the ns simulator.
Definition of network nodes, links, queues and topology
Definition of agents and of applications
The nam visualization tool
Tracing and random variables
Initialization and Termination of TCL Script in NS-2
An ns simulation starts with the command
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 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 parameterthe 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.
Proc finish { } {
global ns tracefile1 namfile
$ns flush-trace
Close $tracefile1
Close $namfile
The word proc declares a procedure in this case finish is called 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 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 run
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:
Which means that $n0 and $n2 are connected using a bi-directional link that has
10ms ofpropagation 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. 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
There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno, Vegas.
Thetype of agent appears in the first line:
The command $ns attach-agent $n0 $tcp defines the source node of the tcp
connection. Thecommand.
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
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 setfid_ 1 that assigns
to the TCP connection a flow identification of ―1.We shall later give the flow identification of
2 to the UDP connection.
Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event should occur.
The initializing command set ns [new Simulator] creates an event scheduler, and events are then
scheduled using the format:
$ns at <time><event>
The scheduler is started when running ns that is through the command $ns run.
The beginning and end of the FTP and CBR application can be done through the following
command
Event Time From To PKT PKT Flags Fid Src Dest Seq Pkt
Node Node Type Size Addr Addr Num id
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.
The second field gives the time at which the event occurs.
Gives the input node of the link at which the event occurs.
Gives the output node of the link at which the event occurs.
Gives the packet type (eg:- CBR or TCP)
Gives the packet size
Some flags
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.
This is the source address given in the form of ―node.port.
Department of ISE Page 16
Computer Networks Laboratory- BCS502
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
/-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:
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.
$ 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 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=”|”}
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 having6 fields, and which have crept in due to faulty data entry:
Program 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.
Program:
Topology:
Note:
1. Set the queue size fixed from n0 to n2 as 10, n1-n2 to 10 and from n2-n3as5. Syntax: To set
the queue size
$ns set queue-limit <from><to><size>
Eg:
$ns set queue-limit $n0 $n2 10
2. Go on varying the bandwidth from 10, 20 30. . and find the number ofpackets dropped at
the node2
Program 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.
Program:
#The below code is used to connect between the ping agents to the node n0, n4 , n5 and n6.
set ping0 [new Agent/Ping]
$ns attach-agent $n0 $ping0
#Schedule events
$ns at 0.1 "$ping0 send"
$ns at 0.2 "$ping0 send"
$ns at 0.3 "$ping0 send"
$ns at 0.4 "$ping0 send"
$ns at 0.5 "$ping0 send"
$ns at 0.6 "$ping0 send"
$ns at 0.7 "$ping0 send"
$ns at 0.8 "$ping0 send"
$ns at 0.9 "$ping0 send"
$ns at 1.0 "$ping0 send"
$ns at 1.1 "$ping0 send"
$ns at 1.2 "$ping0 send"
$ns at 1.3 "$ping0 send"
$ns at 1.4 "$ping0 send"
$ns at 1.5 "$ping0 send"
$ns at 1.6 "$ping0 send"
$ns at 1.7 "$ping0 send"
$ns at 1.8 "$ping0 send"
$ns at 0.1 "$ping5 send"
$ns at 0.2 "$ping5 send"
$ns at 0.3 "$ping5 send"
$ns at 0.4 "$ping5 send"
$ns at 0.5 "$ping5 send"
$ns at 0.6 "$ping5 send"
$ns at 0.7 "$ping5 send"
$ns at 0.8 "$ping5 send"
$ns at 0.9 "$ping5 send"
$ns at 1.0 "$ping5 send"
$ns at 1.1 "$ping5 send"
$ns at 1.2 "$ping5 send"
$ns at 1.3 "$ping5 send"
$ns at 1.4 "$ping5 send"
$ns at 1.5 "$ping5 send"
$ns at 1.6 "$ping5 send"
$ns at 1.7 "$ping5 send"
$ns at 1.8 "$ping5 send"
$ns at 5.0 "finish"
$ns run
OUTPUT:
Program 3
Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
window for different source / destination.
Experiment Specific Instructions
1. To analyze the given problem you have to write a Tcl script and simulate withns2
2. Begin by specifying the trace files and the nam files to be created
3. Define a finish procedure
4. Determine and create the nodes that will be used to create the topology. Here inour
experiment we are selecting 6 nodes namely 0, 1, 2, 3, 4, 5
5. Create the links to connect the nodes
6. Set up the LAN by specifying the nodes, and assign values for bandwidth, delay,queue type
and channel to it
7. Optionally you can position and orient the nodes and links to view a nice videooutput with
Nam
8. Set up the TCP and/or UDP connection(s) and the FTP/CBR (or any otherapplication)
that will run over it
9. Schedule the different events like simulation start and stop, data transmissionstart and
stop
10. Call the finish procedure and mention the time at what time your simulationwill end
11. Execute the script with ns
Steps for execution
Open gedit editor and type program. Program name should have theextension “ .tcl”
[root@localhost ~]# gedit lab3.tcl / vi lab3.tcl
Program
#set ns Simulator
set ns [new Simulator]
#define color for data flow
$ns color 1 Blue
$ns color 2 Red
#open trace file
set tracefile1 [open lab6.tr w]
set winfile [open winfile w]
$ns trace-all $tracefile1
#open namtrace file
set namfile [open lab6.nam w]
$ns namtrace-all $namfile
#define finish procedure
proc finish { } {
global ns tracefile1 namfile
$ns flush-trace
close $tracefile1
close $namfile
exec nam lab6.nam &
exit 0
}
#create 6 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$n1 shape box
#create link between nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/802_3]
#give node position
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns simplex-link-op $n3 $n2 orient left
$ns simplex-link-op $n2 $n3 orient right
#set queue size of link(n2-n3)
$ns queue-limit $n2 $n3 20
Topology:
Congestion graph
ise@Ubuntu20:~/cnlab$ xgraph congestion1.xg
Trace File
Program 4
Develop a program for error detecting code using CRC-CCITT (16- bits).
A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks and
storage devices to detect accidental changes to raw data.
Blocks of data entering these systems get a short check value attached, based on the
remainder of a polynomial division of their contents. On retrieval the calculation is repeated, and
corrective action can be taken against presumed data corruption if the check values do not match.
Algorithm:-
1. 1. Given a bit string, append 0S to the end of it (the number of 0s is the same as the
degree of the generator polynomial) let B(x) be the polynomial corresponding to B.
2. Divide B(x) by some agreed on polynomial G(x) (generator polynomial) and determine
the remainder R(x). This division is to be done using Modulo 2 Division.
3. Define T(x) = B(x) –R(x) (T(x)/G(x) => remainder 0).
4. Transmit T, the bit string corresponding to T(x).
5. Let T’ represent the bit stream the receiver gets and T’(x) the associated polynomial. The
receiver divides T1(x) by G(x). If there is a 0 remainder, the receiver concludes T = T’
and no error occurred otherwise, the receiver concludes an error occurred and requires a
retransmission.
Program:
package cnlab;
import java.io.*;
import java.util.Scanner;
class Crc
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
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)+"");
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];
}
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();
System.out.print("Enter checksum code: ");
message = sc.nextLine();
OUTPUT:
Program 5
Develop a program to implement a sliding window protocol in the data link layer.
ALGORITHM:
Program:
package pgm5;
import java.net.*;
import java.io.*;
import java.rmi.*;
public class slidsender
{
@SuppressWarnings({ "deprecation", "deprecation", "deprecation" })
public static void main(String a[])throws Exception
{
ServerSocket ser=new ServerSocket(4000);
Socket s=ser.accept();
DataInputStream in=new DataInputStream(System.in);
DataInputStream in1=new DataInputStream(s.getInputStream());
String sbuff[]=new String[8];
PrintStream p;
int sptr=0,sws=8,nf,ano,i; String ch;
do
{
p=new PrintStream(s.getOutputStream());
System.out.print("Enter the no. of frames : ");
nf=Integer.parseInt(in.readLine());
p.println(nf);
if(nf<=sws-1)
{
System.out.println("Enter "+nf+" Messages to be send\n");
for(i=1;i<=nf;i++)
{
sbuff[sptr]=in.readLine();
p.println(sbuff[sptr]);
sptr=++sptr%8;
}
sws-=nf;
System.out.print("Acknowledgment received");
ano=Integer.parseInt(in1.readLine());
System.out.println(" for "+ano+" frames");
sws+=nf;
}
else
{
System.out.println("The no. of frames exceeds window size");
break;
}
System.out.print("\nDo you wants to send some more frames : ");
ch=in.readLine();
p.println(ch);
}
while(ch.equals("yes"));
s.close();
}
}
@SuppressWarnings("deprecation")
public static void main(String a[])throws Exception
{
Socket s=new Socket(InetAddress.getLocalHost(),4000);
DataInputStream in=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
int i=0,rptr=-1,nf,rws=8;
String rbuf[]=new String[8];
String ch;
System.out.println();
do
{
nf=Integer.parseInt(in.readLine());
if(nf<=rws-1)
{
for(i=1;i<=nf;i++)
{
rptr=++rptr%8;
rbuf[rptr]=in.readLine();
System.out.println("The received Frame " +rptr+" is :
"+rbuf[rptr]);
}
rws-=nf;
System.out.println("\nAcknowledgment sent\n");
p.println(rptr+1);
rws+=nf;
}
else
break;
ch=in.readLine();
}
while(ch.equals("yes"));
}
}
OUTPUT : 1
Enter the no. of frames : 4
welcome to CN Lab
thank you
bye
Acknowledgment sent
OUTPUT : 2
Program 6
Develop a program to find the shortest path between vertices using the Bellman-Ford and path
vector routing algorithm.
Program:
package cnlab;
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[][])
{
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)
{
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;
Department of ISE Page 43
Computer Networks Laboratory- BCS502
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:
Enter the number of vertices
5 2 2
Enter the adjacency matrix 4
3
0 3 2 4 999
3 0 999 2 999 4
4
1
2 999 0 2 3 2
4 2 2 0 4 2 5
999 999 3 4 0 3 3
Enter the source vertex
1
distance of source 1 to 1 is 0
distance of source 1 to 2 is 3
distance of source 1 to 3 is 2
distance of source 1 to 4 is 4
distance of source 1 to 5 is 5
Program 7
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.
CLIENT SIDE:
package pgm7;
import java.net.*;
import java.io.*;
public class TCPC
{
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();
}
}
SERVER SIDE:
package pgm7;
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();
}
}
OUTPUT:
Program 8
Develop a program on a datagram socket for client/server to display the messages on client side,
typed at the server side.
Program:
Client Side:
package pgm8;
import java.io.*;
import java.net.*;
import java.net.InetAddress;
class UDPClient
{
public static void main(String[] args)throws Exception
{
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();
}
}
Server Side:
package pgm8;
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);
}
}
}
OUTPUT:
Program 9
Develop a program for a simple RSA algorithm to encrypt and decrypt the data.
Cryptography has a long and colorful history. The message to be encrypted, known as the
plaintext, are transformed by a function that is parameterized by a key. The output of the encryption
process, known as the ciphertext, is then transmitted, often by messenger or radio. The enemy, or
intruder, hears and accurately copies down the complete ciphertext. However, unlike the intended
recipient, he does not know the decryption key and so cannot decrypt the ciphertext easily. The art
of breaking ciphers is called cryptanalysis the art of devising ciphers (cryptography) and breaking
them (cryptanalysis) is collectively known as cryptology.
There are several ways of classifying cryptographic algorithms. They are generally categorized
based on the number of keys that are employed for encryption and decryption, and further defined
by their application and use. The three types of algorithms are as follows:
1. Secret Key Cryptography (SKC): Uses a single key for both encryption and decryption. It is
also known as symmetric cryptography.
2. Public Key Cryptography (PKC): Uses one key for encryption and another for decryption. It
is also known as asymmetric cryptography.
3. Hash Functions: Uses a mathematical transformation to irreversibly "encrypt" information
Public-key cryptography has been said to be the most significant new development in
cryptography. Modern PKC was first described publicly by Stanford University professor Martin
Hellman and graduate student Whitfield Diffie in 1976. Their paper described a two-key crypto
system in which two parties could engage in a secure communication over a non-secure
communications channel without having to share a secret key.
Generic PKC employs two keys that are mathematically related although knowledge of one key
does not allow someone to easily determine the other key. One key is used to encrypt the plaintext
and the other key is used to decrypt the ciphertext. The important point here is that it does not
matter which key is applied first, but that both keys are required for the process to work. Because
pair of keys is required, this approach is also called asymmetric cryptography.
In PKC, one of the keys is designated the public key and may be advertised as widely as the
owner wants. The other key is designated the private key and is never revealed to another party. It
is straight forward to send messages under this scheme.
Department of ISE Page 54
Computer Networks Laboratory- BCS502
The RSA algorithm is named after Ron Rivest, Adi Shamir and Len Adleman, who invented it
in 1977.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.
Algorithm
Program:
package pgm9;
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
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);
}
{
this.e = e;
this.d = d;
this.N = N;
}
// Encrypting message
public byte[] encrypt(byte[] message)
{
// Decrypting message
public byte[] decrypt(byte[] message)
{
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
}
OUTPUT:
Program 10
Develop a program for congestion control using a leaky bucket algorithm.
Theory
The congesting control algorithms are basically divided into two groups: open loop and closed loop.
Open loop solutions attempt to solve the problem by good design, in essence, to make sure it does
not occur in the first place. Once the system is up and running, midcourse corrections are not made.
Open loop algorithms are further divided into ones that act at source versus ones that act at the
destination.
In contrast, closed loop solutions are based on the concept of a feedback loop if there is any
congestion. Closed loop algorithms are also divided into two sub categories: explicit feedback and
implicit feedback. In explicit feedback algorithms, packets are sent back from the point of
congestion to warn the source. In implicit algorithm, the source deduces the existence of congestion
by making local observation, such as the time needed for acknowledgment to come back.
The presence of congestion means that the load is (temporarily) greater than the resources
(in part of the system) can handle. For subnets that use virtual circuits internally, these methods can
be used at the network layer.
Another open loop method to help manage congestion is forcing the packet to be transmitted
at a more predictable rate. This approach to congestion management is widely used in ATM
networks and is called traffic shaping.
The other method is the leaky bucket algorithm. Each host is connected to the network by an
interface containing a leaky bucket, that is, a finite internal queue. If a packet arrives at the queue
when it is full, the packet is discarded. In other words, if one or more process are already queued,
the new packet is unceremoniously discarded. This arrangement can be built into the hardware
interface or simulate d by the host operating system. In fact it is nothing other than a single server
queuing system with constant service time.
The host is allowed to put one packet per clock tick onto the network. This mechanism turns
an uneven flow of packet from the user process inside the host into an even flow of packet onto the
network, smoothing out bursts and greatly reducing the chances of congestion.
Program:
package cnlab;
import java.util.Scanner;
public class Leakybucket
{
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
{
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:
Enter the number of packets
3
Enter the packets
4
3
2
Clock packet size accept sent remaining
1 4 4 3 1
2 3 3 3 1
3 2 2 3 0