CN Lab Manual-22scheme
CN Lab Manual-22scheme
TECHNOLOGY
(Affiliated to VTU, Belagavi, Approved by AICTE, New Delhi and Govt. of Karnataka, NAAC-‘A’ Grade)
Rajanukunte, Bengaluru-560064
Tel: 080-2846 8196, Fax: 2846 8193 / 98, Web: www.saividya.ac.in
MOTTO
“Learn to lead”
VISION MISSION
To provide quality education and skilled training to
produce dedicated engineers and managers.
To promote research, innovation and ethical practices by
Contribute dedicated, skilled, intelligent creating supportive environment.
engineers and business administrators to To undertake collaborative projects with academia and
architect strong India and the world industry that transform young minds into socially
responsible citizen and globally competent professionals.
world. To enhance personality traits which leads to
entrepreneurship qualities among the students.
COMPUTER NETWORKS
(BCS502)
(As per Visvesvaraya Technological University Syllabus)
Compiled By:
Name:
USN :
Trademark
Edition: 2024 - 25
Document owner
The primary contacts for questions regarding this document are:
1. Dr. Tejashwini N
Author(s): 2. Prof. Sowmya H N
Department: Computer Science & Engineering
[email protected]
Dept. of CSE, SVIT Page: 1
Program Outcomes
PO1 : Engineering Knowledge - Apply knowledge of mathematics, science, Engineering
fundamentals and computing skills to solve IT related engineering problems.
PO2: Problem Analysis - Identify, formulate, research literature and analyze complex computer
science engineering problems.
PO3: Design/Development of Solutions - Design software / hardware solutions for complex IT
problems to uplift the societal status of common man.
PO4 : Conduct Investigation of complex problems - Use research-based knowledge and methods
including design of software and or hardware experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
PO5 : Modern Tool Usage - Create/select an appropriate IT tool to model, implement and automate
the complex computational system.
PO6 : The engineer and Society - Apply reasoning informed by the contextual knowledge to assess
societal issues, cultural issues, and the consequent responsibilities relevant to the IT practice
PO7: Environment and sustainability - Understand the impact of IT solutions in environmental
context and demonstrate the knowledge of, and need for sustainable development.
PO8 : Ethics - Apply ethical principles in responsible way to follow the IT norms and cyber ethics.
PO9 : Individual and team work - Function effectively as an individual and as a member or leader
in diverse teams / multidisciplinary teams.
PO10 : Communication - Communicate effectively on complex engineering activities with the
engineering community and the society for the effective presentation and / or report generation.
PO11 : Project management & Finance - Demonstrate the knowledge of computing / managerial
principles to solve and manage IT projects.
PO12 : Life Long Learning - Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
PSO2 : Apply standard Software Engineering practices and strategies in software project development
PSO3 : Demonstrate the knowledge of Discrete Mathematics, Data management and Data engineering.
COMPUTER NETWORKS
Sub Code : BCS502 IA Marks : 50
Hrs / Week : 04I + 02P Exam Hours : 03
Total Hrs : 40 Exam Marks : 50
The student has to secure 40% of 25 marks to qualify in the CIE of the theory component of IPCC.
CIE for the practical component of the IPCC
15 marks for the conduction of the experiment and preparation of laboratory record, and 10
marks for the test to be conducted after the completion of all the laboratory sessions.
On completion of every experiment/program in the laboratory, the students shall be evaluated
including viva-voce and marks shall be awarded on the same day.
The CIE marks awarded in the case of the Practical component shall be based on the
continuous evaluation of the laboratory report. Each experiment report can be evaluated for 10
marks. Marks of all experiments’ write-ups are added and scaled down to 15 marks.
The laboratory test (duration 02 hours) after completion of all the experiments shall be
conducted for 50 marks and scaled down to 10 marks.
Scaled-down marks of write-up evaluations and tests added will be CIE marks for the
laboratory component of IPCC for 25 marks.
The student has to secure 40% of 25 marks to qualify in the CIE of the practical component of
the IPCC.
Course Outcome
At the end of the course students will be able to
CO 1: Explain the fundamentals of computer networks.
CO2: Apply the concepts of computer networks to demonstrate the working of various layers and
protocols in communication network.
CO3: Analyze the principles of protocol layering in modern communication systems.
CO4: Demonstrate various Routing protocols and their services using tools such as Cisco packet
tracer.
Simulation
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.
NS Simulator Preliminaries.
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.
Which is thus the first line in the tcl script? This line declares a new variable as using the set
command, you can call this variable as you wish, In general people declares it as ns because it is
an instance of the Simulator class, so an object the code[new Simulator] is indeed the installation
of the class Simulator using the reserved word new.
In order to have output files with data on the simulation (trace files) or files used for visualization
(nam files), we need to create the files using “open” command:
The above creates a 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
$ns flush-trace
Close $tracefile1
Close $namfile
Exit 0
The word proc declares a procedure in this case called finish and without arguments. The
word global is used to tell that we are using variables declared outside the procedure. The simulator
method “flush-trace” will dump the traces on the respective files. The tcl command “close” closes
the trace files defined before and exec executes the nam program for visualization. The command
exit will ends the application and return the number 0 as status to the system. Zero is the default
for a clean exit. Other values can be used to say that is a exit because something fails.
At the end of ns program we should call the procedure “finish” and specify at what time
the termination should occur. For example,
$ns at 125.0 “finish”
will be used to call “finish” at time 125sec.Indeed,the at method of the simulator allows us to
schedule events explicitly.
The simulation can then begin using the command
$ns run
Once we define several nodes, we can define the links that connect them. An example of a
definition of a link is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of
propagation delay and a capacity of 10Mb per sec for each direction.
To define a directional link instead of a bi-directional one, we should replace “duplex-link”
by “simplex-link”.
In NS, an output queue of a node is implemented as a part of each link whose input is that
node. The definition of the link then includes the way to handle overflow at that queue. In our case,
if the buffer capacity of the output queue is exceeded then the last packet to arrive is dropped.
Many alternative options exist, such as the RED (Random Early Discard) mechanism, the FQ (Fair
Queuing), the DRR (Deficit Round Robin), the stochastic Fair Queuing (SFQ) and the CBQ (which
including a priority and a round-robin scheduler).
In ns, an output queue of a node is implemented as a part of each link whose input is that
node. We should also define the buffer capacity of the queue related to each link. An example
would be: #set Queue Size of link (n0-n2) to 20
Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.
TCP has many parameters with initial fixed defaults values that can be changed if
mentioned explicitly. For example, the default TCP packet size has a size of 1000bytes.This can
be changed to another value, say 552bytes, using the command $tcp set packetSize_ 552.
When we have several flows, we may wish to distinguish them so that we can identify them
with different colors in the visualization part. This is done by the command $tcp set fid_ 1 that
assigns to the TCP connection a flow identification of “1”.We shall later give the flow
identification of “2” to the UDP connection.
Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event should occur.
The initializing command set ns [new Simulator] creates an event scheduler, and events are then
scheduled using the format:
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”
Event Time From To PKT PKT Flags Fid Src Dest Seq Pkt
Node Node Type Size Addr Addr Num id
1. The first field is the event type. It is given by one of four possible symbols r, +, -, d which
correspond respectively to receive (at the output of the link), enqueued, dequeued and dropped.
2. The second field gives the time at which the event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (eg CBR or TCP)
6. Gives the packet size
7. Some flags
8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script one
can further use this field for analysis purposes; it is also used when specifying stream color for
the NAM display.
9. This is the source address given in the form of “node.port”.
10. This is the destination address, given in the same form.
11. This is the network layer protocol’s packet sequence number. Even though UDP
implementations in a real network do not use sequence number, ns keeps track of UDP packet
sequence number for analysis purposes
12. The last field shows the Unique id of the packet.
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
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
PART - A
Experiment 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.
Step1: Open text editor, type the below program and save with extention .tcl (prog1.tcl )
proc finish { } {
global ns nf nd
$ns flush-trace
close $nf
close $nd
exec nam prog1.nam &
exit 0
}
Step2: Open text editor, type the below program and save with extention .awk (prog1.awk )
BEGIN {
dcount = 0;
rcount = 0;
}
{
event = $1;
if(event == "d")
{
dcount++;
}
if(event == "r")
{
rcount++;
}
}
END {
printf("The no.of packets dropped : %d\n ",dcount);
printf("The no.of packets recieved : %d\n ",rcount);
}
Step 4: Now press the play button in the simulation window and the simulation will begins.
Step 5: After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f prog1.awk prog1.tr
Number of packets droped = 16
Experiment 2:
Step1: Open text editor, type the below program and save with extention.tcl (prog3.tcl )
proc finish {} {
global ns nf nd
$ns flush-trace
close $nf
close $nd
exec nam prog4.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
Step2: Open text editor, type the below program and save with extention .awk (prog3.awk )
BEGIN {
count=0;
}
{
event=$1;
if(event=="d")
{
count++;
Dept. of CSE, SVIT Page:20
Computer Network Laboratory (BCS502) SVIT, Bengaluru
}
}
END {
printf("No of packets dropped : %d\n",count);
}
Step3: Run the simulation program
[root@localhost~]# ns prog3.tcl
(Here “ns” indicates network simulator. We get the topology shown in the snapshot.)
Step 4: Now press the play button in the simulation window and the simulation will begins.
Step 5: After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f prog3.awk prog3.tr
Experiment 3:
Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
window for different source / destination.
Step1: Open text editor, type the below program and save with extention .tcl (prog5.tcl )
$ns make-lan "$n3 $n4 $n5 $n6 $n7 $n8" 512Kb 40ms LL Queue/DropTail Mac/802_3
Step2: Open text editor, type the below program and save with extention .awk (prog5.awk )
BEGIN {
}
{
if($6=="cwnd_") {
printf("%f\t%f\n",$1,$7);
}
}
Dept. of CSE, SVIT Page:24
Computer Network Laboratory (BCS502) SVIT, Bengaluru
END {
}
Step 4: Now press the play button in the simulation window and the simulation will begins.
Step 5: After simulation is completed run awk file and generate the graph ,
[root@localhost~]# awk –f prog5.awk cwnd.tr > a1
[root@localhost~]# awk –f prog5.awk cwnd2.tr > a2
[root@localhost~]#xgraph a1 a2
Experiment 4
CRC
Problem Statement
Write a program for error detecting code using CRC-CCITT (16 bits).
Theory
CRC(Cyclic Redundancy Check) is an error detecting technique used in digital networks and
storage devices to detect the accidental changes to raw data. It cannot be used for correcting errors.
The CRC does error checking via polynomial division. The generated polynomial g(x) =
x +x +x5+x0
16 12
16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1 17 bits.
Algorithm:
1. Given a bit string (message to be sent), append 16 0S to the end of it (the number of 0s is
the same as the degree of the generator polynomial) let this string + 0S be called as modified
string B
2. Divide B by agreed on polynomial g(x) and determine the remainder R(x). The 16-bit
remainder received is called as checksum.
3. The message string is appended with checksum and sent to the receiver.
4. At the receiver side, the received message is divided by generator polynomial g(x).
5. If the remainder is 0, the receiver concludes that there is no error occurred otherwise, the
receiver concludes an error occurred and requires a retransmission.
PROGRAM:
import java.io.*;
class crc_gen
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
int data_bits, divisor_bits, tot_length;
divisor_bits = 17;
divisor = new int[]{1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1};
tot_length=data_bits+divisor_bits-1;
div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];
/* CRC GENERATION */
for(int i=0;i<data.length;i++)
div[i]=data[i];
rem=divide(divisor, rem);
System.out.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i]);
/* ERROR DETECTION */
System.out.println();
System.out.println("Enter CRC code of "+tot_length+" bits : ");
for(int i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.readLine());
rem=divide(divisor, rem);
{
int cur=0;
while(true)
{
for(int i=0;i<divisor.length;i++)
rem[cur+i]=(rem[cur+i]^divisor[i]);
if((rem.length-cur)<divisor.length)
break;
}
return rem;
}
}
OUTPUT:
RUN1:
RUN 2:
Experiment 5:
Problem Statement:
Develop a program to implement a sliding window protocol in the data link layer.
Theory:
In computer networks sliding window protocol is a method to transmit data on a network. Sliding
window protocol is applied on the Data Link Layer of OSI model. At data link layer data is in the
form of frames. In Networking, Window simply means a buffer which has data frames that needs to be
transmitted.
Both sender and receiver agrees on some window size. If window size=w then after sending w frames
sender waits for the acknowledgement (ack) of the first frame.
As soon as sender receives the acknowledgement of a frame it is replaced by the next frames to be
transmitted by the sender. If receiver sends a collective or cumulative acknowledgement to sender
then it understands that more than one frames are properly received, for eg:- if ack of frame 3 is
received it understands that frame 1 and frame 2 are received properly.
In sliding window protocol the receiver has to have some memory to compensate any loss in
transmission or if the frames are received unordered.
η = (W*tx)/(tx+2tp)
W = Window Size
tx = Transmission time
tp = Propagation delay
It is of two types:-
1. Selective Repeat: Sender transmits only that frame which is erroneous or is lost.
2. Go back n: Sender transmits all frames present in the window that occurs after the error
bit including error bit also.
PROGRAM:
#include<stdio.h>
int main()
{
int w,i,f,frames[50];
for(i=1;i<=f;i++)
scanf("%d",&frames[i]);
printf("\nWith sliding window protocol the frames will be sent in the following manner
(assuming no corruption of frames)\n\n");
printf("After sending %d frames at each stage sender waits for acknowledgement sent by
the receiver\n\n",w);
for(i=1;i<=f;i++)
{
if(i%w==0)
{
printf("%d\n",frames[i]);
printf("Acknowledgement of above frames sent is received by sender\n\n");
}
else
printf("%d ",frames[i]);
}
if(f%w!=0)
printf("\nAcknowledgement of above frames sent is received by sender\n");
return 0;
}
OUTPUT:
Enter window size: 3
Enter 5 frames: 12 5 89 4 6
With sliding window protocol the frames will be sent in the following manner (assuming no
Dept. of CSE, SVIT Page:33
Computer Network Laboratory (BCS502) SVIT, Bengaluru
corruption of frames)
12 5 89
Acknowledgement of above frames sent is received by sender
46
Acknowledgement of above frames sent is received by sender
Experiment 6
Bellman-Ford algorithm
Problem Statement
Write a program to find the shortest path between vertices using bellman-ford algorithm.
Theory
Routing algorithm is a part of network layer software which is responsible for deciding which output
line an incoming packet should be transmitted on. If the subnet uses datagram internally, this decision must
be made anew for every arriving data packet since the best route may have changed since last time. If the
subnet uses virtual circuits (connection Oriented), routing decisions are made only when a new established
route is being set up.
Routing algorithms can be grouped into two major classes: adaptive and nonadaptive. Nonadaptive
algorithms do not base their routing decisions on measurement or estimates of current traffic and topology.
Instead, the choice of route to use to get from I to J (for all I and J) is compute in advance, offline, and
downloaded to the routers when the network ids booted. This procedure is sometime called static routing.
Adaptive algorithms, in contrast, change their routing decisions to reflect changes in the topology, and
usually the traffic as well. Adaptive algorithms differ in where they get information (e.g., locally, from
adjacent routers, or from all routers), when they change the routes (e.g., every ∆T sec, when the load
changes, or when the topology changes), and what metric is used for optimization (e.g., distance, number
of hops, or estimated transit time).
Two algorithms in particular, distance vector routing and link state routing are the most popular.
Distance vector routing algorithms operate by having each router maintain a table (i.e., vector) giving the
best known distance to each destination and which line to get there. These tables are updated by exchanging
information with the neighbors.
The distance vector routing algorithm uses Bellman-Ford routing algorithm and Ford-Fulkerson
algorithm. In distance vector routing, each router maintains a routing table that contains two parts: the
preferred out going line to use for that destination, and an estimate of the time or distance to that destination.
The metric used might be number of hops, time delay in milliseconds, total number of packets queued along
the path, or something similar.
The Routing tables are shared among the neighbors, and the tables at the router are updated, such that
the router will know the shortest path to the destination.
Program
import java.io.*;
import java.util.Scanner;
class dist_vec
{
public static void main(String args[])
{
int dmat[][];
int dist[][];
int via[][];
int n=0,i=0,j=0,k=0,count=0;
Scanner in = new Scanner(System.in);
Output 1
Problem statement:
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.
Theory:
Procedure:
Server Program
import java.net.*;
import java.io.*;
String str;
while((str = contentRead.readLine()) != null) // reading line-by-line from file
{
pwrite.println(str); // sending each line to client
}
Client Program:
import java.net.*;
import java.io.*;
Dept. of CSE, SVIT Page:38
Computer Network Laboratory (BCS502) SVIT, Bengaluru
String str;
while((str = socketRead.readLine()) != null) // reading line-by-line
{
System.out.println(str);
}
pwrite.close(); socketRead.close(); keyRead.close();
}
}
OUTPUT:
Create a text file say abc.txt and type some content in it.
Compile and execute server side program
Experiment 8
Client-Server Program using UDP Socket
Problem Statement
Write a program on datagram socket for client/server to display the messages on client side, typed
at the server side.
Theory
Procedure:
Server Program
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
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();
System.out.println("Enter the Message");
String data = br.readLine();
sendData = data.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, port);
serverSocket.send(sendPacket);
serverSocket.close();
}
}
Client Program
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
Dept. of CSE, SVIT Page:41
Computer Network Laboratory (BCS502) SVIT, Bengaluru
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = "Hello Server";
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,
9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
OUTPUT
Compile and execute server side program
RSA Algorithm
Problem Statement
Write a program for simple RSA algorithm to encrypt and decrypt the data.
Theory
Cryptography is the study of creating ciphers(cipher text) and breaking them (cryptanalysis). 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 hacker, 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.
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. In public key cryptography, one key is used to encrypt the plaintext and
the other key is used to decrypt the ciphertext.
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. Public key of the receiver is used for encryption, so that only
the receiver can decrypt the message (using his private key).
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.
Algorithm
The message is encrypted using public key and decrypted using private key.
Note that we don't have to calculate the full value of 13 to the power 7 here. We can make use of the
fact that a = bc mod n = (b mod n).(c mod n) mod n so we can break down a potentially large number into
its components and combine the results of easier, smaller calculations to calculate the final value.
Program:
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
Dept. of CSE, SVIT Page:44
Computer Network Laboratory (BCS502) SVIT, Bengaluru
public RSA()
{
r = new Random();
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
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);
}
d = e.modInverse(phi);
}
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
// 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:
Experiment 10
Leaky Bucket
Problem Statement
Write a program for congestion control using 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:
import java.lang.*;
import java.util.Random;
import java.io.*;
import java.util.Scanner;
class leaky_bucket
{
public static void main(String args[])
{
int drop=0,mini,nsec,p_remain=0;
int o_rate,b_size,i,packet[];
{
p_remain+=packet[i];
if(p_remain>b_size)
{
drop=p_remain-b_size;
p_remain=b_size;
System.out.print(i+1+" ");
System.out.print(packet[i]+" ");
mini=Math.min(p_remain,o_rate);
System.out.print(mini+" ");
p_remain=p_remain-mini;
System.out.print(p_remain+" ");
System.out.print(drop+" ");
System.out.println();
drop=0;
}
}
while(p_remain!=0)
{
if(p_remain>b_size)
{
drop=p_remain-b_size;
p_remain=b_size;
}
mini=Math.min(p_remain,o_rate);
System.out.print(" "+p_remain+" "+mini);
p_remain=p_remain-mini;
System.out.println(p_remain+" "+drop);
drop=0;
}
}
}
Viva Questions
1) What is a Link?
A link refers to the connectivity between two devices. It includes the type of cables and protocols
used in order for one device to be able to communicate with the other.
4) What is a LAN?
LAN is short for Local Area Network. It refers to the connection between computers and other
network devices that are located within a small physical location.
5) What is a node?
A node refers to a point or joint where a connection takes place. It can be computer or device that
is part of a network. Two or more nodes are needed in order to form a network connection.
Routers can connect two or more network segments. These are intelligent network devices that
store information in its routing table such as paths, hops and bottlenecks. With this info, they are
able to determine the best path for data transfer. Routers operate at the OSI Network Layer.
15) What is the job of the Network Layer under the OSI reference model?
The Network layer is responsible for data routing, packet switching and control of network
congestion. Routers operate under this layer.
16) How does a network topology affect your decision in setting up a network?
Dept. of CSE, SVIT Page:51
Computer Network Laboratory (BCS502) SVIT, Bengaluru
Network topology dictates what media you must use to interconnect devices. It also serves as basis
on what materials, connector and terminations that is applicable for the setup.
23) What are proxy servers and how do they protect computer networks?
Proxy servers primarily prevent external users who identifying the IP addresses of an internal
network. Without knowledge of the correct IP address, even the physical location of the network
cannot be identified. Proxy servers can make a network virtually invisible to external users.
25) What is the importance of implementing a Fault Tolerance System? Are there
limitations?
A fault tolerance system ensures continuous data availability. This is done by eliminating a single
point of failure. However, this type of system would not be able to protect data in some cases, such
as in accidental deletions.
30) What is OSI and what role does it play in computer networks?
OSI (Open Systems Interconnect) serves as a reference model for data communication. It is made
up of 7 layers, with each layer defining a particular aspect on how network devices connect and
communicate with one another. One layer may deal with the physical media used, while another
layer dictates how data is actually transmitted across the network.
31) What is the purpose of cables being shielded and having twisted pairs?
The main purpose of this is to prevent crosstalk. Crosstalks are electromagnetic interferences or
noise that can affect data being transmitted across cables.
34) What is the equivalent layer or layers of the TCP/IP Application layer in terms of OSI
reference model?
The TCP/IP Application layer actually has three counterparts on the OSI model: the Session layer,
Presentation Layer and Application Layer.
Dept. of CSE, SVIT Page:53
Computer Network Laboratory (BCS502) SVIT, Bengaluru
51) What protocol can be applied when you want to transfer files between different
platforms, such between UNIX systems and Windows servers?
Use FTP (File Transfer Protocol) for file transfers between such different servers. This is possible
because FTP is platform independent.
53) One way of securing a network is through the use of passwords. What can be considered
as good passwords?
Good passwords are made up of not just letters, but by combining letters and numbers. A password
that combines uppercase and lowercase letters is favorable than one that uses all upper case or all
lower case letters. Passwords must be not words that can easily be guessed by hackers, such as
dates, names, favorites, etc. Longer passwords are also better than short ones.
57) What happens when you use cables longer than the prescribed length?
Cables that are too long would result in signal loss. This means that data transmission and reception
would be affected, because the signal degrades over length.
63) What advantages does fiber optics have over other media?
One major advantage of fiber optics is that is it less susceptible to electrical interference. It also
supports higher bandwidth, meaning more data can be transmitted and received. Signal degrading
is also very minimal over long distances.
65) What are the different network protocols that are supported by Windows RRAS
services?
There are three main network protocols supported: NetBEUI, TCP/IP, and IPX.
66) What are the maximum networks and hosts in a class A, B and C network?
For Class A, there are 126 possible networks and 16,777,214 hosts
For Class B, there are 16,384 possible networks and 65,534 hosts
For Class C, there are 2,097,152 possible networks and 254 hosts
67) What is the standard color sequence of a straight-through cable?
orange/white, orange, green/white, blue, blue/white, green, brown/white, brown.
68) What protocols fall under the Application layer of the TCP/IP stack?
The following are the protocols under TCP/IP Application layer: FTP, TFTP, Telnet and SMTP.
69) You need to connect two computers for file sharing. Is it possible to do this without using
a hub or router?
Yes, you can connect two computers together using only one cable. A crossover type cable can be
use in this scenario. In this setup, the data transmit pin of one cable is connected to the data receive
pin of the other cable, and vice versa.
74) When you move the NIC cards from one PC to another PC, does the MAC address gets
transferred as well?
Yes, that's because MAC addresses are hard-wired into the NIC circuitry, not the PC. This also
means that a PC can have a different MAC address when the NIC card was replace by another one.
76) In a network that contains two servers and twenty workstations, where is the best place
to install an Anti-virus program?
An anti-virus program must be installed on all servers and workstations to ensure protection. That's
because individual users can access any workstation and introduce a computer virus when plugging
in their removable hard drives or flash drives.
77) Describe Ethernet.
Ethernet is one of the popular networking technologies used these days. It was developed during
the early 1970s and is based on specifications as stated in the IEEE. Ethernet is used in local area
networks.
IP addresses are displayed as a series of four decimal numbers that are separated by period or dots.
Another term for this arrangement is the dotted decimal format. An example is 192.168.101.2
86) What are the different technologies involved in establishing WAN links?
Analog connections - using conventional telephone lines; Digital connections - using digitalgrade
telephone lines; switched connections - using multiple sets of links between sender and receiver
to move data.
90) How does dynamic host configuration protocol aid in network administration?
Instead of having to visit each client computer to configure a static IP address, the network
administrator can apply dynamic host configuration protocol to create a pool of IP addresses
known as scopes that can be dynamically assigned to clients.