CN Lab Manual_BCS502_2024-25 final
CN Lab Manual_BCS502_2024-25 final
CN Lab Manual_BCS502_2024-25 final
LABORATORY MANUAL
SEMESTER : V
SUBCODE : BCS502
PROGRAM OUTCOMES
PO2: Problem analysis: Identify, formulate, review research literature, and analyse complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3: Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activitieswith
an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9: Individual and Team Work: Function effectively as an individual and as a member or
leader in diverse teams, and in multi – disciplinary settings.
VISION
“To be a Respected and Most Sought after Engineering Educational Institution Engaged in
Equipping Individuals capable of Building Learning Organizations in the New Millennium”.
MISSION
Our Mission is to develop Competent Students with good value Systems and Face Challenges of
the Continuously Changing World.
DEPARTMENT VISION
“To Create Technocrats with Cognitive Skills and Technical Proficiency to Succeed
in the Challenging World of New Era”.
CN Lab Manual BCS502
DEPARTMENT VISION
“To Create Technocrats with Cognitive Skills and Technical Proficiency to Succeed in the
Challenging World of New Era”.
DEPARTMENT MISSION
DEPT OF AIML 1
CN Lab Manual BCS502
COURSE OUTCOMES
At the end of the course the student will be able to:
CO1. Learn the basic needs of communication system.
CO2. Explain the fundamentals of computer networks.
CO3. Apply the concepts of computer networks to demonstrate the working of various layers and
protocols in communication network.
CO4. Analyze the principles of protocol layering in modern communication systems.
CO5: Demonstrate various Routing protocols and their services using tools such as Cisco packet
tracer.
DEPT OF AIML 2
CN Lab Manual BCS502
Program List:
Implement three nodes point ‒ to ‒ point network with duplex links between them. Set the
1
queue size, vary the bandwidth, and find the number of packets dropped.
Implement transmission of ping messages/trace route over a network topology consisting of 6
2 nodes and find the number of packets dropped due to congestion.
Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
3 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.
Develop a program to find the shortest path between vertices using the Bellman-Ford and path
6 vector routing algorithm.
Using TCP/IP sockets, write a client ‒ server program to make the client send the file name
7
and to make the server send back the contents of the requested file if present.
Develop a program on a datagram socket for client/server to display the messages on client
8 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.
DEPT OF AIML 3
CN Lab Manual BCS502
Index
Sl. Page
Program List CO PO RBT
No. No
Implement three nodes point ‒ to ‒ point network with PO1,
duplex links between them. Set the queue size, vary the PO2,
1 bandwidth, and find the number of packets dropped. CO1 PO3, L3
PO5,
PO12
Implement transmission of ping messages/trace route over a PO1,
network topology consisting of 6 nodes and find the number PO2,
2 of packets dropped due to congestion. PO3,
CO1 L3
PO5,
PO12
Implement an Ethernet LAN using n nodes and set multiple PO1,
traffic nodes and plot congestion window for different PO2,
3 source / destination. CO3 L2
PO5,
PO12
PO1,
Develop a program for error detecting code using CRC-
PO2,
4 CCITT (16- bits). CO1 PO3, L3
PO5,
PO12
Develop a program to implement a sliding window protocol PO1,
PO2,
5 in the data link layer. L2
CO2 PO5,
PO12
Develop a program to find the shortest path between PO1,
vertices using the Bellman-Ford and path PO2,
6 vector routing algorithm. PO3,
CO1 L3
PO5,
PO12
Using TCP/IP sockets, write a client ‒ server program to PO1,
PO2,
7 make the client send the file name and to make the server CO2 L2
send back the contents of the requested file if present. PO5,
PO12
Develop a program on a datagram socket for client/server to PO1, L3
display the messages on client side, typed at the server side. PO2,
8 CO2 PO3,
PO5,
PO12
Develop a program for a simple RSA algorithm to encrypt PO1, L3
9 and decrypt the data. CO2 PO2,
PO3,
DEPT OF AIML 4
CN Lab Manual BCS502
PO5,
PO12
DEPT OF AIML 5
CN Lab Manual BCS502
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.
• 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
• Hello World!
puts stdout{Hello, World!}
Hello, World!
DEPT OF AIML 6
CN Lab Manual BCS502
......
}}
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
1. An ns simulation starts with the command
DEPT. OF AIML 7
CN Lab Manual BCS502
Which is thus the first line in the tcl script? This line declares a new variable as using the set
command, you can call this variable as you wish, In general people declares it as ns because
it is an instance of the Simulator class, so an object the code[new Simulator] is indeed the
installation of the class Simulator using the reserved word new.
In order to have output files with data on the simulation (trace files) or files used for
visualization (nam files), we need to create the files using ―open‖ command:
The above creates a data trace file called ―out.tr‖ and a nam visualization trace file called ―out.nam‖.
Within the tcl script, these files are not called explicitly by their names, but instead by pointers that are
declared above and called ―tracefile1‖ and ―namfile‖ respectively. Remark that they begins with a #
symbol. The second line open the file ―out.tr‖ to be used for writing, declared with the letter ―w‖. The
third line uses a simulator method called trace-all that have as parameter the name of the file where the
traces will go.
The last line tells the simulator to record all simulation traces in NAM input format. It also gives the
file name that the trace will be written to later by the command $ns flush-trace. In our case, this will
be the file pointed at by the pointer ―$namfile‖,i.e the file ―out.tr‖.
set tracefile1 [open out.tr w]
$ns trace-all $tracefile1
set namfile [open out.nam w]
$ns namtrace-all $namfile
$ns run
set n0 [$ns node]
$ns duplex-link $n0 $n2 10Mb 10ms DropTail
The termination of the program is done using a ―finish‖ procedure.
DEPT. OF AIML 8
CN Lab Manual BCS502
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 an exit because something fails.
At the end of ns program, we should call the procedure ―finish‖ and specify at what time the
termination should occur. For example
will be used to call ―finish‖ at time 125sec.Indeed, the at method of the simulator allows us to schedule
events explicitly.
The simulation can then begin using the command
DEPT. OF AIML 9
CN Lab Manual BCS502
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
Proc finish { } {
global ns tracefile1 namfile
$ns flush-trace Close $tracefile1
Close $namfile
Exec nam out.nam & Exit 0
$ns at 125.0 ―finish‖
#set Queue Size of link (n0-n2) to 20
$ns queue-limit $n0 $n2 20 set tcp [new Agent/TCP]
set sink [new Agent /TCPSink]
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:
DEPT. OF AIML 10
CN Lab Manual BCS502
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
Defines the behaviour of the destination node of TCP and assigns to it a pointer called sink.
#Setup a UDP connection
DEPT. OF AIML 11
CN Lab Manual BCS502
Scheduling Events
DEPT. OF AIML 12
CN Lab Manual BCS502
NS is a discrete event based simulation. The tcp script defines when event should occur fig shown
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.
DEPT. OF AIML 13
CN Lab Manual 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:
Syntax:
Here, selection_criteria filters input and select lines for the action component to act
DEPT. OF AIML 14
CN Lab Manual BCS502
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:
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
DEPT. OF AIML 15
CN Lab Manual BCS502
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:
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:
DEPT. OF AIML 16
CN Lab Manual BCS502
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 ns-allinone-
2.34.tar.gz
[root@localhost opt] # ns-allinone-2.34 ns-allinone-2.34.tar.gz
➢ Now go to ns-allinone-2.33 folder and install it
DEPT. OF AIML 17
CN Lab Manual BCS502
[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 . .
[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
DEPT. OF AIML 18
CN Lab Manual BCS502
DEPT. OF AIML 19
CN Lab Manual BCS502
DEPT. OF AIML 20
CN Lab Manual BCS502
DEPT. OF AIML 21
CN Lab Manual BCS502
Here ―ns‖ indicates network simulator. We get the topology shown in the snapshot.
ii) Now press the play button in the simulation window and the simulation will
begins.
6) After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab1.awk lab1.tr
7) To see the trace file contents open the file as ,
[root@localhost~]# vi lab1.tr
Trace file contains 12 columns:-Event type, Event time, From Node, Source Node, Packet
Type, Packet Size, Flags
(indicated by-------- ), Flow ID, Source address, Destination address, Sequence ID,
Packet ID
DEPT. OF AIML 22
CN Lab Manual BCS502
OUTPUT:
Note:
1. Set the queue size fixed from n0 to n2 as 10, n1-n2 to 10 and from n2-
n3 as 5. Syntax: To set the queue size
$ns set queue-limit <from> <to> <size> Eg:
$ns set queue-limit $n0 $n2 10
Go on varying the bandwidth from 10, 20 30 . . and find the number of packets
dropped at the node 2
DEPT. OF AIML 23
CN Lab Manual BCS502
DEPT. OF AIML 24
CN Lab Manual BCS502
DEPT. OF AIML 25
CN Lab Manual BCS502
DEPT. OF AIML 26
CN Lab Manual BCS502
DEPT. OF AIML 27
CN Lab Manual BCS502
Topology: Output
DEPT. OF AIML 28
CN Lab Manual BCS502
Note:
Vary the bandwidth and queue size between the nodes n0-n2 , n2-n4. n6-n2 and n2- n5 and
see the number of packets dropped at the nodes.
DEPT. OF AIML 29
CN Lab Manual BCS502
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination
DEPT. OF AIML 30
CN Lab Manual BCS502
DEPT. OF AIML 31
CN Lab Manual BCS502
AWK file (Open a new editor using “vi command” and write awk file and save
with
“.awk” extension)
cwnd:- means congestion window
BEGIN {
}
{
if($6= ="cwnd_") /* don‘t leave space after writing cwnd_ */ printf("%f\t%f\t\n",$1,$7); /*
you must put \n in printf */
}
END {
}
Steps for execution
[root@localhost
~]# vi lab3.tcl
[root@localhost
~]# vi lab3.awk
[root@localhost~]#
ns lab3.tcl STEPS
FOR EXECUTION:
1) Open vi editor and type program. Program name should have the extension ― .tcl ‖
2) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
3) Open vi editor and type awk program. Program name should have the extension ―.awk ‖
4) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
DEPT. OF AIML 32
CN Lab Manual BCS502
Topology
Output
DEPT. OF AIML 33
CN Lab Manual BCS502
4. 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.
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.
DEPT. OF AIML 34
CN Lab Manual BCS502
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.
DEPT. OF AIML 35
CN Lab Manual BCS502
SOURCE CODE:
import java.util.Scanner; class CRC{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
for(int i=0;i<generator.length();i++)
divisor[i] = Integer.parseInt(generator.charAt(i)+"");
//Calculation of CRC
for(int i=0;i<datastream.length();i++){
if(data[i]==1)
for(int j=0;j<divisor.length;j++)
data[i+j] ^= divisor[j];
}
//Display CRC
System.out.print("The CRC code is: ");
for(int i=0;i<datastream.length();i++)
data[i] = Integer.parseInt(datastream.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 CRC code: ");
datastream = sc.nextLine();
System.out.print("Enter generator: ");
DEPT. OF AIML 36
CN Lab Manual BCS502
generator = sc.nextLine();
data = new int[datastream.length() + generator.length()-1];
divisor = new int[generator.length()];
for(int i=0;i<datastream.length();i++)
data[i] = Integer.parseInt(datastream.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<datastream.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 occured.");
}
}
OUTPUT:
DEPT. OF AIML 37
CN Lab Manual BCS502
5 Develop a program to implement a sliding window protocol in the data link layer.
DEPT. OF AIML 38
CN Lab Manual BCS502
6. Develop a program to find the shortest path between vertices using the Bellman-
Ford and path vector routing algorithm.
DEPT. OF AIML 39
CN Lab Manual BCS502
SOURCE CODE:
import java.util.Scanner;
public class BellmanFord
{
private int D[];
private int num_ver;
public static final int MAX_VALUE = 999;
public BellmanFord(int num_ver)
{
this.num_ver = num_ver;
D = new int[num_ver + 1];
}
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];
}
}
}
}
DEPT. OF AIML 40
CN Lab Manual BCS502
DEPT. OF AIML 41
CN Lab Manual BCS502
continue;
}
if (A[sn][dn] == 0)
{
A[sn][dn] = MAX_VALUE;
}
}
}
System.out.println("Enter the source vertex");
source = scanner.nextInt();
BellmanFord b = new BellmanFord (num_ver);
b.BellmanFordEvaluation(source, A);
scanner.close();
}
}
OUTPUT:
DEPT. OF AIML 42
CN Lab Manual BCS502
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.
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.
tcp program server side
import java.net.*;
import java.io.*;
public class server1
{
public static void main(String args[]) throws Exception
{ // establishing the connection with the server
ServerSocket sersock = new ServerSocket(4000);
System.out.println("Server ready for connection");
Socket sock = sersock.accept(); // binding with port: 4000
System.out.println("Connection is successful");
// reading the file name from client
InputStream istream = sock.getInputStream( );
BufferedReader fileRead =new BufferedReader(new InputStreamReader(istream));
String fname = fileRead.readLine( );
// reading file contents
BufferedReader contentRead = new BufferedReader(new FileReader(fname) );
// keeping output stream ready to send the contents
OutputStream ostream = sock.getOutputStream( );
PrintWriter pwrite = new PrintWriter(ostream, true);
String str;
while((str = contentRead.readLine()) != null) // reading line-by-line from file
{
pwrite.println(str); // sending each line to client
}
DEPT. OF AIML 43
CN Lab Manual BCS502
DEPT. OF AIML 44
CN Lab Manual BCS502
DEPT. OF AIML 45
CN Lab Manual BCS502
DEPT. OF AIML 46
CN Lab Manual BCS502
}
}
CLIENT
package client;
import java.io.*;
import java.net.*;
public class clientpgm {
public static void main(String[] args) throws Exception{
BufferedReader clientRead =new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IP = InetAddress.getByName("127.0.0.1");
byte[] sendbuffer = new byte[1024];
byte[] receivebuffer = new byte[1024];
System.out.print("\nClient: ");
String clientData = clientRead.readLine();
sendbuffer = clientData.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendbuffer, sendbuffer.length, IP, 9876);
clientSocket.send(sendPacket);
System.out.println("Waiting for Server response!") ;
DatagramPacket receivePacket =
new DatagramPacket(receivebuffer, receivebuffer.length);
clientSocket.receive(receivePacket);
String serverData = new String(receivePacket.getData());
System.out.println("\nServer Message received: " + serverData);
System.out.println("Client terminated.") ;
clientSocket.close();
}
}
DEPT. OF AIML 47
CN Lab Manual BCS502
OUTPUT:
SERVER END CLIENT END
Waiting for Client request Client: Hello I am client
Waiting for server response!
Connected to client 127.0.0.1
Client message: Hello I am client
Hello I am server
Message sent to client!
Server message received hello I am server
Client Terminated.
DEPT. OF AIML 48
CN Lab Manual BCS502
9. Develop a program for a simple RSA algorithm to encrypt and decrypt the data.
RSA is an example of public key cryptography. It was developed by Rivest, Shamir and Adelman. The
RSA algorithm can be used for both public key encryption and digital signatures. Its security is based on the
difficulty of factoring large integers.
The RSA algorithm's efficiency requires a fast method for performing the modular exponentiation operation. A
less efficient, conventional method includes raising a number (the input) to a power (the secret or public key of
the algorithm, denoted e and d, respectively) and taking the remainder of the division with N. A straight-
forward implementation performs these two steps of the operation sequentially: first, raise it to the power and
second, apply modulo. The RSA algorithm comprises of three steps, which are depicted below:
Key Generation Algorithm
1. Generate two large random primes, p and q, of approximately equal size such that their product n = p*q
2. Compute n = p*q and Euler’s totient function (φ) phi(n) = (p-1)(q-1).
3. Choose an integer e, 1 < e < phi, such that gcd(e, phi) = 1.
4. Compute the secret exponent d, 1 < d < phi, such that e*d ≡ 1 (mod phi).
5. The public key is (e, n) and the private key is (d, n). The values of p, q, and phi should also be kept secret.
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.
SOURCE CODE:
import java.math.BigInteger;
import java.util.Random;
import java.io.*;
public class RSA {
BigInteger p, q, N, phi, e, d;
int bitlength = 100;
DEPT. OF AIML 49
CN Lab Manual BCS502
Random r;
public RSA() {
r = new Random();
// returns a prime number with in the specified bit length
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
N = p.multiply(q);
// In c equivalent – phi = (p-1)*(q-1)
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitlength/2, r);
// In C equivalent - while ( phi.gcd(e) > 1 && e < phi )
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0 ) {
e.add(BigInteger.ONE); // In C equivalent- e+1
}
d = e.modInverse(phi);
}
// RSA Main
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()));
// encrypt
byte[] encrypted = rsa.encrypt(teststring.getBytes());
System.out.println("Encrypted String in Bytes: " + bytesToString(encrypted));
// decrypt
byte[] decrypted = rsa.decrypt(encrypted);
System.out.println("Decrypted String in Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: ");
System.out.println(new String(decrypted));
}
private static String bytesToString(byte[] encrypted) {
String test = "";
for (byte b : encrypted) {
test += Byte.toString(b);
}
DEPT. OF AIML 50
CN Lab Manual BCS502
return test;
}
// Encrypt message
public byte[] encrypt(byte[] message) {
return (new BigInteger(message)).modPow(e, N).toByteArray();
}
// Decrypt message
public byte[] decrypt(byte[] message) {
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
}
OUTPUT
Enter the plain text:
EPCET
Encrypting String: EPCET
String in Bytes: 839711211610497103105114105
Encrypted String in Bytes: 91-2-10491-456154-32-71-122-35-187884101-3125-1856102-17356-582
Decrypted String in Bytes: 839711211610497103105114105
Decrypted String:
EPCET
DEPT. OF AIML 51
CN Lab Manual BCS502
10. Develop a program for congestion control using a leaky bucket algorithm.
The main concept of the leaky bucket algorithm is that the output data flow remains constant
despite the variant input traffic, such as the water flow in a bucket with a small hole at the
bottom. In case the bucket contains water (or packets) then the output flow follows a constant
rate, while if the bucket is full any additional load will be lost because of spillover. In a similar
way if the bucket is empty the output will be zero. From network perspective, leaky bucket
consists of a finite queue (bucket) where all the incoming packets are stored in case there is
space in the queue, otherwise the packets are discarded. In order to regulate the output flow,
leaky bucket transmits one packet from the queue in a fixed time (e.g. at every clock tick).
In the following figure we can notice the main rationale of leaky bucket algorithm, for
both the two approaches (e.g. leaky bucket with water (a) and with packets (b)).
While leaky bucket eliminates completely bursty traffic by regulating the incoming data flow
its main drawback is that it drops packets if the bucket is full. Also, it doesn‘t take into account
the idle process of the sender which means that if the host doesn‘t transmit data for some time
the bucket becomes empty without permitting the transmission of any packet.
DEPT. OF AIML 52
CN Lab Manual BCS502
Source Code:
import java.util.Scanner;
a) {
return (int) (Math.random() * a);
}
OUTPUT:
CN Lab Manual BCS502
CN Lab Manual BCS502
Viva Questions
1. What are functions of different layers?
2. Differentiate between TCP/IP Layers and OSI Layers
3. Why header is required?
4. What is the use of adding header and trailer to frames?
5. What is encapsulation?
6. Why fragmentation requires?
7. What is MTU?
8. Which layer imposes MTU?
9. Differentiate between flow control and congestion control.
10. Differentiate between Point-to-Point Connection and End-to-End connections.
11. What are protocols running in different layers?
12. What is Protocol Stack?
13. Differentiate between TCP and UDP.
14. Differentiate between Connectionless and connection oriented connection.
15. Why frame sorting is required?
16. What is meant by subnet?
17. What is meant by Gateway?
18. What is an IP address?
19. What is MAC address?
20. Why IP address is required when we have MAC address?
21. What is meant by port?
22. What are ephemerical port number and well known port numbers?
23. What is a socket?
24. What are the parameters of socket()?
25. Describe bind(), listen(), accept(),connect(), send() and recv().
26. What are system calls? Mention few of them.
27. What is IPC? Name three techniques.
28. Explain mkfifo(), open(), close() with parameters.
29. What is meant by file descriptor?
30. What is meant by traffic shaping?
31. How do you classify congestion control algorithms?
32. Differentiate between Leaky bucket and Token bucket.
33. How do you implement Leaky bucket?
34. How do you generate busty traffic?
35. What is the polynomial used in CRC-CCITT?
36. What are the other error detection algorithms?
37. What is difference between CRC and Hamming code?
38. Why Hamming code is called 7,4 code?
39. What is odd parity and even parity?
40. What is meant by syndrome?
41. What is generator matrix?
42. What is spanning tree?
43. Where Pirm’s algorithm does finds its use in Networks?
44. Differentiate between Prim’s and Kruskal’s algorithm.
45. What are Routing algorithms?
46. How do you classify routing algorithms? Give examples for each.
47. What are drawbacks in distance vector algorithm?
CN Lab Manual BCS502