0% found this document useful (0 votes)
155 views25 pages

CN Lab Manual PDF

The document discusses the Bellman-Ford algorithm for finding the shortest path between vertices in a weighted graph. It is based on maintaining distance tables that store the shortest distance and path to each node. The algorithm is slower than Dijkstra's but can handle graphs with negative edge weights, allowing it to detect negative cycles. An example Java program is provided to implement the Bellman-Ford algorithm to compute shortest paths from a source vertex to all others.

Uploaded by

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

CN Lab Manual PDF

The document discusses the Bellman-Ford algorithm for finding the shortest path between vertices in a weighted graph. It is based on maintaining distance tables that store the shortest distance and path to each node. The algorithm is slower than Dijkstra's but can handle graphs with negative edge weights, allowing it to detect negative cycles. An example Java program is provided to implement the Bellman-Ford algorithm to compute shortest paths from a source vertex to all others.

Uploaded by

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

COMPUTER NElWORK LABORATORY l8CSL57

PART-B
Java is a general-purpose computer programming language that is simple, concurrent,
class-based, object-oriented language. The compiled Java code can run on all platforms that
support Java without the need for recompilation hence Java is called as "write once, run
anywhere" (WORA). The Java compile::d intermediate output called "byte-code" that can run on
any Java virtual machine (JVM) regardless of computer architecture. The language derives
much of its syntax from C and C++, but it has fewer low-level facilities than either of them.
In Linux operating system Java libraries are preinstalled. It's very easy and convenient
to compile and run Java programs in Linux environment. To compile and run Java Program
is a two-step process:

Compile Java Program from Command Prompt


[root@host ~)# javac Filename.java

The Java compiler (Javac) compiles java program and generates a byte-code
with the same file name and .class extension.

Run Java program from Command Prompt


[root@host ~]# java Filename

The java interpreter (Java) runs the byte-code and gives the respective output. It is
important to note that in above command we have omitted the .class suffix of the byte-
code (Filename.class).

Dept. ofISE, DSATM 2020-21


Page 42
r

c o l\fPUTER NETWORK LABORATORY 18CSL57

1. 1YRITE A PROGRAM FOR ERROR DETECTING CODE USING CRC-CCITT


~- BITSb - -
CRC(Cyclic Redundancy Check) is an error detecting technique used in digital networks
and storage devices to detect the accidental cha:nges to raw data. It cannot bt! used for correcting
errors.

If an error is detected in the received message, a 'Negative acknowledg1!ment' is sent to


the sender. The sender and the receiver agree upon a fixed polynomial called generator
polynomial. The standard agreed generator pol!momial is x 16+x 12+x5+x0 (any polynomial can be
considered, of degree 16).

The CRC does error checking via polynomial division. The generated polynomial g(x) =
X16-t-x lz+xS+xO

16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 I 0

I 0 0 0 l 0 0 0 0 0 0 1 0 0 0 0 I -+ 17 bits.

So the g(x) value is 10001000000100001

Algorithm:

1. Given a bit string (message to be sent), append 16 os to the end of it (th•~ number of OS is
the same as the d egree Of the generator polynomial) let this string + os be called as
modified string B .
· I g(x)
2. Divide B by agre~d on poIynom1a • and dt·termine
' the remainder R(x). The 16-btt

remainder received is called as checksum.


3. The message strmg. 1s. append ed wt'th chi~cksum and sent to the receiver. .
. d ssa1:1e is divided by generator polynom1al g(x).
4. At the receiver side, the receive me :i •

. I d that there is no error occurred otherwise, the


5. If the remainder is 0, the receiver cone u es . .
red and requires a retransm1ss1on.
receiver concludes an error occur
COMPUTER NETWORK LABORATORY

SOURCE CODE:
-
l8CSL57

import java. io. *;

class Crc

public static void main(String args[ ]) !throws IOException {

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

int[] data;
int[ ]div;
int[ ]divisor;
in t[ Jrem;
int[ ] ere;
int data_bits, divisor_bits, tot_length;
System.out.println("Enter number of data bits : ");
data_bits=lnteger.parselnt(br.readLine( ));
data=new int[data_bits];
System.out.println("Enter data bits:");
for(int i=0; i<data_bits; i++)
data[i]= Integer.parselnt(br.readLine( ) );
System.out.println("Enter number of bits in divisor : ");
divisor bits=Integer.parseh1t(br.readLine( ));
divisor=new int[ divisor_bits];
System.out.println("Enter Divisor bits : ");
for(int i=0; i<divisor_bits; i++)
divisor[ i]= Integer .parselnt(br.readLine());
tot_length=data_bits+divisor_ bits- l;
div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];

Dept. of ISE, DSATM 2020-21


Page 44
~---------------·---·------·-·---·---
coMPUTER NETWORK LABORATORY

ror(int i==0;i<data.length;i++)
18CSLS7

div[i]==data[i];
System.out.print("Dividend (after appending O's) are "); for(int i=0; i< div.length; i++)
· System.out.print(div[i]);
System.out.printlnO;
for(int j'=O; j<div .length; j++) {
remOJ == div[j];
}

rem-divide(div, divisor, rem);


ror(int i=0;i<div.Jength;i++) //append dividend and ramainder
{
crc[i]=(div[i]"rem[i]);
}

System.out.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i ]);
System.out.printlnO;
System.out.println("Enter CRC code of "+tot_length+" bits: ");
for(int i=0; i<crc.length; i++)
crc[iJ=Integer.parse/nt(br.readLineO);
for(int j=0; j<crc.length; j++){
remU] = crc[j];
}

rem=divide(crc, divisor, rem);


for(int i=0; i< rem.length; i++)
{

if(rem[i]!=O)

Dept. ofI SE, DSATM 2020-21 Page 45


COMPUTER NETWORK LABORATORY

System.out.println("Error'');
-
l8CSL57

break;
}

ifO = rem.length- I)
System.out.println(''No Error");
}
}
static int[] divide(int div[ ],int divisor[], int rem[])
{

int cur=O;

wbile(true)

for(int i=O;i<divisor.length;i++)

rem[cur+i]=(rem[cur+i]"divisor[i]);

wbile(rem[cur] 0 && cur!=rem.length-1)

cur++;

if((rem.length-cur)<divisor.length)

break;

return rem;

OUTPUT:
Enter number of data bits:
7
Enter data bits:
I
0

Dept. ofISE, DSATM 2020-21


Page 46 -
co l\lPUTER NETWORK LA!JORATORY
Ill' liillillilill _ _ __
18CSL57

0
0
,I
Enter number of bits in divisor:
3
Enter divisor bits:
1
0
1
Divided (after appending O's) are: 101100100
CRC code:
101100111
Enter CRC code of 9 bits:
I
0
I
I
0
0

Error
COMPUTER NETWORK LABORATORY

2. WRITE A PROGRAM TO FIND THE SHORTEST PATH BETWEEN VERTICE_§


USING BELLMAN-FORD ALGORITHM.
l8CSL57

-
Distance Vector Algorithm is a decentralized routing algorithm that requires that each
router simply inform its neighbors of its routing table. For each network path, the receiving
routers pick the neighbor advertising the lowest cost, then add this entry into its routing table
for re-advertisement. To find the shortest path, Distance Vector Algorithm is based on one of
two basic algorithms: the Bellman-Ford and the Dijkstra algorithms.

Routers that use this algorithm have to maintain the distance tables (which is a one-
dimension array -- "a vector"), which tell the distances and shortest path to sending packets to
each node in the network. The information in the distance table is always up date by exchanging
information with the neighboring nod1~s.

The number of data in the table equals to that of all nodes in networks (excluded itself).
The columns of table represent the directly attached neighbors whereas the rows represent all
destinations in the network. Each data contains the path for sending packets to each destination
in the network and distance/or time to transmit on that path (we call this as "cost"). The
measurements in this algorithm are the number of hops, latency, the number of outgoing
packets, etc.

The Bellman-Ford algorithm is an algorithm that computes shortest paths from a single
source vertex to all of the other vertices in a weighted digraph. It is slower than Dijkstra's
algorithm for the same problem, but more versatile, as it is capable of handling graphs in which
some of the edge weights are negative numbers.

Negative edge weights are found in various applications of graphs, hence the usefulness
of this algorithm. If a graph contains a "negative cycle" (i.e. a cycle whose edges sum to a
negative value) that is reachable from the source, then there is no cheapest path: any path that
has a point on the negative cycle can be made cheaper by one more walk around the negative
cycle. In such a case, the Bellman-Ford algorithm can detect negative cycles and report their
existence.

Dept. of ISE, DSATM 2020-21 a


Page 48
- C()J\{PUT.ER NETWORK LABORATORY
18CSL57

package bellmanford;
·jrnport java.util. *;
public class Bellmanford

{
static final int MAX=20;
static int A[ ][ ];
static int n;
public static void main(String[ J args) {
A=new int [MAX][MAX];
read_matrix( );
shortest( );
write();
}
static void shortest( )
{
for(int k= I ;k<=n;k++)
for(int i=l ;i<=n;i++)
for(int j= I ;j<=n;j++) {
if(A[i]U]> A[i] [k]+A[k][j])
A[i][j]=A[i][k]+A[k](j];
}
}
static void write( ){
System.out.println("\n the output matrix is: ");
for(int i= I ;i<=n;i++){
for(int j= I ;j<=n;j++) {
System.out.print(" "+A[i]U]);
}

System.out.println( );
COMPUTER NETWORK LABORATORY l8Cs1.5 7

static void read_matrix( ){


System.out.println("\n enter the number of vertices: ");
Scanner src=new Scanner(System.in);
n;; src.nextlnt( );
System.out.println("\n enter the adj matrix: ");
for(int i= 1;i<=n;i++){
for(int j= l ;j<=n;j++){
A[i]Ll]=src.nextlnt( );
}
}
}
}

' r~r:-,r:-"0.;~"
~-e~·,
:.:...:.x.,.re:.£ ,,..
[root@localhost ~}# javac BellmanFord.java
[root@localhost ~}# java BellmanFord
En t er the number of vertices
4
Enter the adjacency matrix
es ae
5 8 3 4
0 3 8 2
,e 4 2 e
·Enter the source vertex
2
distance of source 2 to 1 is S
·distance of source 2 to 2 is 8
distance of source 2 to 3 is 3
distance of source 2 to 4 is 4
[root@localhost ~]# 0

Dept. oflSE, DSATM 2020-21 Page 50


-
~~--------liiliiiiiiiiia--...
col\t:PlJTER NETWORK LABORATORY

v srNG TCP/IP SOCKETS, WRITE A CLIENT SERVER PROGRAM TO MAKE


3.-
18CSL57
_iliiiiiiliiiiiiiiiiiiiiiiiiiiiiiiliiliiiiiiiliiiiiilaiilliiiiiiiill_i_ __

--
rHE CLIENT SEND THE FILE NAME AND TO MAKE THE SERVER SEND BACK
THE CONTENTS OF THE REQUESTED FILE IF PRESENT. IMPLEMENT THE
AHOVE PROGRAl\tl USING AS MESSAGE QUEUES OR FIFOS AS IPC

-
cHANNELS.

Socket is an interface which enables the client and the server to communicate and pass
on information from one another. Sockets provide the communication mechanism between two
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 creatt:s a socket object
on its end of the communication. The client and the server can now communicate by writing to
and reading from the socket.
Source Code:

TCP Client
import java.io.BufferedReader;
import java.io.DatalnputStream;
impol'.t java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;
class Client
{ .
public static void main(String args[])throws Exception
{
String address="";
Scanner sc=new Scanner(System.in);
System.out.println("Enter Server Address: ");
address=sc.nextLine(); •
//create the socket on port 5000 Socket s=new Socket(address,5000),
DatainputStream din=new DatalnputStream(s.getlnput:StreamO); ())·
DataOutputStream dout=new DataOutputStream(s.getOutputS~eam(S ' . ))·
BufferedReader br=new BufferedReader(new lnputStreamRea er ystem.m '
System.out.println("Send Get to start ... ");
String str="",filename="";
try

Page 51
18CSLS7
_c__MP
0
_UT_E:R~N;.:E~
TW~O:RK~LA~B:;o:RA~T~O:RY~ --iiiiiiiiiiiliiili-----·-·---·--·
{
while(!str.equals("start"))
str=br.readLine();
<lout. writeUTF(str);
'<lout.flush();
filename=din.readUTF();
System.out.println("Receving file: "+filename);
filename="client"+filename;
System.out.println("Saving as file: "+filename);
long sz=Long.parseLong(din.readUTF());
System.out.println ("File Size: "+(s7/(1024*1024))+" MB");
byte b[]=new byte [1024];
System.out.println("Receving file .. ");
FileOutputStream fos=new FileOutputStream(new File(filename),true);
long bytesRead;
do
{
bytesRead = din.read(b, 0, b.length);
fos.write(h,0,h.length);
}while(!(bytesRead<l 024));
System.out.println("Comleted");
fos.closeQ;
<lout.close();
s.close();
}
catch(EOFException e)
{
//do nothing
}
}
}
TCP Server
import java.io.DatalnputStream; import java.io.DataOutputStream; import java.io.File;
import java.io.FilelnputStream; import java.net.ServerSocket; import java.n,et.Socket;
import java.util.Scanner; class Server
{
public static void main(String args[])throws Exception
{
String filename; System.out.println("Enter File Name: ");
Scanner sc=new Scanner(System.in);
filename=sc.nextLine();
sc.closeQ; while(true)
{
//create server socket on port 5000 ServerSocket ss=new ServerSocket(S00O); System.out.println
("Waiting for request");
Socket s=ss.accept();

II&&;
Dept. ofISE, DSATM 2020-21
Page 52
col\lr vTER NETWORK LABORATORY 18CSL57
_ __

ut.println ("Connected With "+s.getlnetAddressQ.toString())·


syst~ -~tstream din=new DatalnputStream(s.getlnputStream()); '
g::1o!tputStream dout=new DataOutputStream(s.getOutputStream());

trY
{ tr-='" "·
strin~s - dUTF();
str:::d10 ·rea · In ("SendGet ....Ok")·,
out.pnnt
tJ:: equals("stop")){ System.out.println("Sending File: "+filename); dout.writeUTF(filename);
dout.flushO;
ile r-new File(filename);
;ileJnPutStream fin=new FilelnputStream(f);
ng sz:==(int) f.length{);
1
b~e bQ===new byte [ I 024];
int read; .
dout.writeUTF(Long.toStrmg(sz));
dout.flush();
System.out.pnn· ti n ("s·1ze: "+sz) ;
System.out.println ("Buf size: "+ss.getReceiveBufferSize());
while((read = fin.read(b)) != -1)
{
dout.write(b, 0, read);
dout.flushO;
}
fin.closeQ;
System.oiit.println(" ..ok");
dout.flush();
}
dout.writeUTF("stop");
System.out.println("Send Complete");
dout.flush();
}
catch(Exception e)
{
e.printStackTrace{);
System.out.println(" An error occured");
}
din.closeQ;
s.closeo;
ss.closeQ·
} ,
}
}
Note: Create two different files Client.java and Server.Java. Follow the steps given:
I. Open a terminal run the server program and provide the filename to send
z?>MPtrrQ NETWORK LABoRATORY
s l8Cst57

2. °"."n
one more terminal run the client program and provide the add~s of the serve,. W
can give localhost address " 127.o.o. I" as it is running on same maclune or give the JP address ,'
the machine. f
3. Send any start bit to start sending file.
4. Refer https://www.tutorialspointcom/java/java_ networking.htm for all the Panun«eo
methods description in socket communication. '
Output:
At server side:
, ii\'l.' '". '_'·i'.~·l;_'i\' •
:cl-~ ' '

(root@localhost
Enter File Naflle:
-J•
lroot@localhoat ~ J • J avac server.Java
java server
. 2-tempte. jpg
Waiting for request
·Connected With /127.e.e.1
SendGet •••• Ok
Sending File: 2-temp\e.jpg
Size: 19868
But s:1.2e: 431599
. , ok
Send Complete
o•1ting for request

At client side:

:r root @l·o
.(root@localhost -J# java client
Enter .S erver Address:
'127 .8.8.1
send Get to start ...
start
Receving file: 2-temple.jpg
Saving as file: client2•temple.jpg
File Size:
:Receving file..
Completed
8 MB
-t
[root@localhost -J• D

Dept. ofISE, DSATM 2020-21


Page 5~
--
l}TER NETWORK LABORATORY ISCSL57
cO:>lM~P~:.:.----------------iiililiiiiliiiiiiiiiiiliiiiiiiliiiilliiiiliiiii-ililiiiiiiiiiiiiiiili_ _ _
~,RITE A PROGRAM ON DATAGRAM SOCKET F OR C LIENT/SERVER T O
4. ~
SPLA Y THE MESSAGES O N CLIENT SIDE, TYPED AT THE SERVER SIDE.
J

-~

package udps;
import java.uti I.Scanner;
import j ava.net. *;
. *·,
import java.10.

public class UDPS {


public static void main(String[] args) {
DatagramSocket skt=null;
String ch;
scanner input=new Scanner(System.in);
try

skt=new DatagramSocket(6788);
byte[] buffer=new byte[I000];
while(true)

DatagramPacket request=new DatagramPacket(buffer,buffer.length);


skt.receive(request);
System.out.print("enter the data: ");
ch=input.nextLine( );
byte[] sendMsg=(ch +" -> server processed").getBytes();
DatagramPacketreply=new
DatagramPacket(sendMsg,sendMsg.length,request.getAddress( ),request.getPort( ));
skt.send(reply);
COMPUTER NETWORK LABORATORY l8CSLS7

catch(Exception ex)
{ }
}
}
UDP CLIENT
package udpc;
import java.util.Scanner;
import java.net. *;
import java.io. *;
public class UDPC
{

public static void main(String[] args) {


DatagramSocket skt;
try
{

skt=new DatagrarnSocket( );
String msg="text message";
byte[ ] b=msg.getBytes( );
InetAddress host=InetAddress.getByName(" 127.0.0.1 ");
int serverSocket=6788;
DatagramPacket request=new DatagramPacket(b,b.length,host,serverSocket);
skt.send(request);
byte[] buffer=new byte[I 000];
Datagram Packet reply=new DatagramPacket(buffer,buffer.length);
skt.receive( reply);
System.out.println("Client receiv(:d: "+ new String(reply.getData( )));
skt.close( );
}
catch(Exception ex)
{ }
}

Dept. ofISE, DSATM 2020-21 Page 56


. UTERNETWORK LABORATORY l8CSL57
~co~~~
p ~ -&iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiaiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii---.._;_iiiiiiiiiiiiiiiiiiiaiiiiiiiiiii

---
}

.
•ie and execute server side program
CoJJ1 P1
bhljtth@abhljlt~-HP-Pavtl~o~-.6-Notebook-PC:~$ ja
c DPSer er~java
bhljlth@abhljlth-HP-Pavtl~on- 6-Note ook-PC: - $ ja I. PServ r
ECEIVED: Hello ~erver ,
nter the Messagfl . . . .
ello Cl~e~t.. i .• . . .
Jbhljith@aoh~Jit~-HP-Pavtllon-~&-NotcbookHPC: SI

Open new terminal, compile and execute client side program

bhljlth@abhlj\th-HP-Pavtlloo-96-Notcbook PC:~S javac U Cl ent.jfva


bhljlth@abhtjlth-HA.•Pavttton-g6-N~tebook. PC:~$ java uo · \thnt •
ROM SERVER:Hello Cllent
.bhtjtth@abhljtth-HP-Pavlllon-gG-N tebooktPc: ~S I If I'

I /I
. '

Dept, ofISE, DSATM 2020-21 Page 57


I COMPUTER NETWORK LABORATORY l8Cs1.57

S. WRITE A PROGRAM FOR 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-fotward 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:

Generate two large random primes, p and q, of approximately equal size such that their
product n = p*q
Compute n = p*q and Euler's totient function (q>) phi(n) = (p-l)(q-1).
Choose an integer e, l < e < phi, such that gcd(e, phi) = l.
Compute the secret exponent d,, 1 < d < phi, such that e*d = 1 (mod phi).
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:


Using the public key (e,n)
Represents the plaintext message as a positive integer M
Computes the cipher text C = M''e mod n.
Sends the cipher text C to B (Receiver).

Dept. of ISE, DSATM 2020-21


-
Page 58
PUTER NETWORK LABORATORY
c~~l\l~~pz~iiliiii--iliiiillliiiiliiiiilliilliii••••iiiliiiiiiiiiiiiiiiiiliiiiiiiiii.._iiliiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii;
- - -- 18CSL57
iiiiiiiiiiiliiiiiiiiiiiiiiiiiliiiiliiiiiiiillilii
l)ecr'YJ>tion:

Recipient B does the following:


Uses his private key (d, n) to compute M- C
· - Ad modn.
Extracts the plaintext from the integer r .
epresentat,ve m.

RSA KEY GENERATION


=---
package rsa ;
import java. io.DatalnputStream;
importjava.io.IOException;
import java.math.Biglnteger;
import java.util.Random;

public class RSA {


private Biglnteger p;
private Biglnteger q;
private Biglnteger N;
private Biglnteger phi;
private Biglnteger e;
private Biglnteger d;
private int bitlength = I 024;
private Random r
'

public RSA( )
{

r == new Random( );
P == Biglnteger.probablePrime(bitlength, r);
q === Biglnteger.probablePrime(bitlength, r);
N === p.multiply(q);

-
Phi == p.subtract(Biglnteger.ONE).multiply(q.subtract(Biglnteger.ONE));
e ::: Biglnteger.probablePrime(bitlength / 2, r);
t~
i ·pt, of ISE, DSATM - 2020-21 Page 59
1CO
~ MP
~ UT
~ E:R~N:E~TW
= O=RK
~ L~A~B~O;:
RA_:T
~O~R
:_Y
~_.iiiiiiaiiiiliiiiiiiiiaiiiiiiiiiiiiiiliiii_ _ _ _ _ _l._
8C~Sts
7
Ii '

while (phi.gcd(e).compareTo(Biginteger.ONE) > 0 && e.compareTo(phi) < 0)


{
e.add(Biglnteger.ONE);
}

d = e.modlnverse(phi);
}

public RSA(Biglnteger e, Biglnteger d, Biginteger N)


{
this.e = e;
this.d = d;
this.N =N;
}

II @Suppress Warnings(" deprecation");


public static void main(String[] args) throws IOException {
RSA rsa = new RSA( );
DatalnputStream in = new DatainputS~eam(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.getBytesO);
// decrypt
byte[ ] decrypted = rsa.decrypt(encrypted);
System.out.println("Decrypting Bytes:"+ bytesToString(decrypted));
System.out.println("Decrypted String:"+ new String(decrypted));
}

Dept. of ISE, DSATM 2020-21 Page 60


TER NETWORK LABORATORY
U
co~M
;;a ~r~~-----iiiiiliiiiiiiliiiiiiaa•----•--iiiiiiiiiiiii----iiiiiiiiiiiiiiiii 18CSL57
•-iiiiiiiiiiiiiiiiiiiiiiiiiliiiiiiiiiiiil

. t static String bytesToString(byte[ ] encrypted)


pf1V8 e

String test = '"';


for (byte b : encrypted)

test+== Byte.toString(b);

}
return test;

// Encrypt message
public byte[ Jencrypt(byte[ ] message)
{
return (new Biglnteger(message)).modPow(e, N).toByteArray( );

// Decrypt message
public byte[ ] decrypt(byte[ ] message)
{
return (new Biglnteger(message)).modPow(d, N).toByteArray( );

OUTPUT:
C:\Users\abhijith\Desktop>javac RSA.java

C:\Users\abhijith\Desktop>java RSA
Enter the plain text:
hi bangalore
Encrypting String: hi bangalore
5t ri ng in Bytes: 10410532989711010397108111114101
Decrypt i ng Bytes: 10410532989711010397108111114101
Decrypted String: hi bangalore

Page 61
COMPUTER NETWORK LABORATORY l8CSt57

6. WRITE A PROGRAM FOR CONGESTION CONTROL USING LEAKY BU~


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
I the bottom. In case the bucket contains water (or packets) then the output flow follows a
I
constant rate, while if the bucket is full any additional load will be lost because of spillover.
I 1

be
1
I I In a . similar way if the bucket is empty the output will
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)).

~,
Hon
.C omput.er

• . . .Packet ·
Unregulated Flow '
a.
,..,.....,__..___--'--
.
Bucket Holds
~ c e .Containln(I
the leal<y bu~
·o · •-, .· pac'--s
{

(a) A leaky bucket wttl1 W1'ter

(b) A leaky bw:ket. with packets

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. oflSE, DSATM 2020-21 Page 62


col\1Pu . ·-•
- iiiiii--~•~sc~s~L;s~1

package leaky;

import java.io. *;
import java.util. *;

public class Leaky {


public static void main(String args[ ]) throws Exception

{
Queue q==new Queue( );
scanner src=new Scanner(System.in);
System.out.println("\nEnter the packets to be sent:"); _
int size==src.nextlnt( );
q.insert(size);
q.delete( );
}
}
class Queue
{
int q[ J,f=0,r=0,size;
void insert(int n)

Scanner in = new Scanner(System.in);


q=new intf 10];
for(int i=O;i<n;i++)

System.out.print("\nEnter " + i + " element: ");

int ele=in.nextlnt( );
if(r+l> IO)
COMPUTER NETWORK LABORATORY l8CSt57

break;
}
else
{
r++·
'
q[i]=ele; .J { l'O
}
}
}
L-- :
L__ J
>"'

void delete( ) 2,oO 3 dO r _1 CJO


{

Scanner in= new Scanner(System.in);


t;j.} ~ _ iw 0
. 51) lSZ)
Thread t=new Thread{ );
if(r=O) 1 So -::::- ls-o
I,

System.out.print("\nQueue empty ");


else
{
for(int i=f;i<r;i++)
{
try
{
t.sleep(l 000);
}
catch(Exception e){ }
System.out.print{"\nLeaked Packet: "+q[i]);
f++;
}
}

System.out.println( );
}
}

Dept. ofISE, DSA TM 2020-21 Page 64


coMPUTER NETWORK LABORATORY

-
OUTPUT:

En ter the packets to be sent:


12
Ent e r 0 element: 2
En ter 1 element: 3
Enter 2 element: s
Enter 3 element: 6

Ente l" 4 element: a


Ente r 5 element: 9

Ente r 6 element: 4
Enter 7 element: 5
Enter- 8 element: 6

Enter 9 element: 2

Enter 1 0 element: 3
o ueue is full
Lost Pack et: 3

Leaked Packet: 2
Leaked Packet: 3
Leaked Packet: 5
Leaked Packet: 6
Leaked Pac ket: 8
) Leaked Packet: 9
i Leaked Packet: 4

I
'
18CSL57
COMPUTER NETWORK LABORATORY

Additional Programs
l. Simulate a four node point-to-point network and connect the links as follows: nO -n2, n I
- n2 and n2 - n3. Apply TCP agent between n0 - n3 and UDP~ I - n3. Apply relevant
applications over TCP and UDP agents changing the parameter and detertnine the
number of packets sent by TCP/ UDP.
2. Simulate an Ethernet LAN using N nodes (6-10). Change error rate and data rate and
compare throughput.
3. Implementation of creating links between the source and destination using both ftp and -.
tcp.
4. Write a java program for distance vector algorithm to find suitable path for transmission.
5. Implement the above program using as message queues or FIFOs as IPC channels using
java.
6. Write ajava program to demonstrate AES algorithm.
7. Write a java program to demonstrate different types of ciphers.
8. Write ajava program to demonstrate 32-bit CRC-CCIT algorithm.
9. Write ajava program to demonstrate Bellman ford algorithm with negative weights.
10. Write ajava program to demonstrate the Dijkstra's algorithm.
11. Write ajava program to demonstrate Diffie-Hellman algorithm.
12. Write a java program to demonstrate BGP protocol.

Dept. off SE, DSATM 2020-21 Page 66

You might also like