6. Write a program to find the shortest path between vertices using Bellman-ford algorithm.
Implementation Algorithm:
1. send my routing table to all my neighbors whenever my link table changes
2. when I get a routing table from a neighbor on port P with link metric M:
a. add L to each of the neighbor's metrics
b. for each entry (D, P', M') in the updated neighbor's table:
i. if I do not have an entry for D, add (D, P, M') to my routing table
ii. if I have an entry for D with metric M", add (D, P, M') to my routing
table if M' < M"
3. if my routing table has changed, send all the new entries to all my neighbor
PROGRAM
import java.util.*;
public class Belmanford
{
private int D[];
private int n;
public static final int max_value=999;
public Belmanford(int n)
{
this.n=n;
D=new int[n+1];
}
public void shortest(int s,int a[][])
{
for(int i=1;i<=n;i++)
{
D[i]=max_value;
}
D[s]=0;
for(int k=1;k<=n-1;k++)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(a[i][j]!=max_value)
{
if(D[j]>D[i]+a[i][j])
D[j]=D[i]+a[i][j];
}
}
}
}
for (int i=1;i<=n;i++)
{
for (int j=1;j<=n;j++)
{
if(a[i][j]!=max_value)
{
if(D[j]>D[i]+a[i][j])
{
System.out.println("the graph contains -ve edge cycle");
return;
}
}
}
}
for (int i=1;i<=n;i++)
{
System.out.println("distance of source " +s+ " to " + i + " is " + D[i]);
}
}
public static void main(String[] args)
{
int n=0,s;
Scanner sc=new Scanner(System.in);
System.out.println("enter the no.of values");
n=sc.nextInt();
int a[][]=new int [n+1][n+1];
System.out.println("enter the weighted matrix:");
for (int i=1;i<=n;i++)
{
for (int j=1;j<=n;j++)
{
a[i][j]=sc.nextInt();
if(i==j)
{
a[i][j]=0;
continue;
}
if(a[i][j]==0)
a[i][j]=max_value;
}
}
System.out.println("enter the source vertex:");
s=sc.nextInt();
Belmanford b=new Belmanford(n);
b.shortest(s,a);
sc.close();
}
}
OUTPUT
10. Write a program for congestion control using leaky bucket algorithm
The leaky-bucket algorithm:
The algorithm can be conceptually understood as follows:
1. Consider a bucket with a hole in the bottom.
2. The empty space of the bucket represents an amount of credit available measured in bytes.
3. The size of the bucket is b bytes. This means that if the bucket is empty, b bytes of credit is
available.
4. If a packet arrives and its size is less than the available credit, the packet can be forwarded.
Otherwise, it is discarded or queued depending on the application.
5. The bucket leaks through the hole in its bottom at a constant rate of r bytes per second, this
indicates credit accumulation.
PROGRAM
import java.util.*;
public class leaky
{
static int min(int x,int y)
{
if(x<y)
return x;
else
return y;
}
public static void main(String[] args)
{ int drop=0,mini,nsec,cap,count=0,i,process;
int inp[]=new int[25];
Scanner sc=new Scanner(System.in);
System.out.println("Enter The Bucket Size\n");
cap= sc.nextInt();
System.out.println("Enter The Operation Rate\n");
process= sc.nextInt();
System.out.println("Enter The No. Of Seconds You Want To Stimulate\n");
nsec=sc.nextInt();
for(i=0;i<nsec;i++)
{ System.out.print("Enter The Size Of The Packet Entering At "+ i+1 + " sec");
inp[i] = sc.nextInt();
}
System.out.println("\nSecond | Packet Recieved | Packet Sent | Packet Left | Packet
Dropped|\n");
for(i=0;i<nsec;i++)
{ count+=inp[i];
if(count>cap)
{ drop=count-cap;
count=cap;
}
System.out.print(i+1);
System.out.print("\t\t"+inp[i]);
mini=min(count,process);
System.out.print("\t\t"+mini);
count=count-mini;
System.out.print("\t\t"+count);
System.out.print("\t\t"+drop);
drop=0;
System.out.println();
}
for(;count!=0;i++)
{
if(count>cap)
{
drop=count-cap;
count=cap;
}
System.out.print(i+1);
System.out.print("\t\t0");
mini=min(count,process);
System.out.print("\t\t"+mini);
count=count-mini;
System.out.print("\t\t"+count);
System.out.print("\t\t"+drop);
System.out.println();
}
}
}
OUTPUT
8. Write a program on datagram socket for client/server to display
the messages on client side, typed at the server side.
A datagram socket is the one for sending or receiving point for a packet delivery
service. Each packet sent or received on a datagram socket is individually addressed
and routed. Multiple packets sent from one machine to another may be routed
differently, and may arrive in any order.
Datagram packets are used to implement a connectionless packet delivery service
supported by the UDP protocol. Each message is transferred from source machine
to destination based on information contained within that packet. That means, each
packet needs to have destination address and each packet might be routed
differently, and might arrive in any order. Packet delivery is not guaranteed.
Java supports datagram communication through the following classes:
DatagramPacket
DatagramSocket
PROGRAM
/* Datagram Socket Program */
UDP Server
import java.io.*;
import java.net.*;
public class UDPServer
{
public static void main(String[] args)
{
DatagramSocket skt=null;
try
{
System.out.println("server is started");
skt=new DatagramSocket(6788);
byte[] buffer = new byte[1000];
while(true)
{
DatagramPacket request = new DatagramPacket(buffer,buffer.length);
skt.receive(request);
String[] message = (new String(request.getData())).split(" ");
byte[] sendMsg= (message[1].toUpperCase()+ " from server to client").getBytes();
DatagramPacket reply = new
DatagramPacket(sendMsg,sendMsg.length,request.getAddress(),request.getPort());
skt.send(reply);
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
UDP Client
import java.io.*;
import java.net.*;
public class UDPClient
{
public static void main(String[] args)
{
DatagramSocket skt;
try
{
skt=new DatagramSocket();
String msg= "atme college ";
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[1000];
DatagramPacket reply= new DatagramPacket(buffer,buffer.length);
skt.receive(reply);
System.out.println("client received:" +new String(reply.getData()));
skt.close();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
Output1:
client received : COLLEGE from server to client
NOTE: First Run Server program in one CMD PROMPT after that
Run Client PROGRAM in another PROMPT
5. Develop a program to implement a sliding window protocol in the
data link layer
PROGRAM
//SENDER SIDE
import java.net.*;
import java.io.*;
import java.rmi.*;
public class slidsender
{
public static void main(String args[]) throws Exception
{
ServerSocket ser=new ServerSocket(8080);
Socket s=ser.accept();
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader in1 = new BufferedReader(new
InputStreamReader(s.getInputStream()));
String sbuff[]=new String[8];
PrintStream p;
int sptr=0,sws=8,nf,ano,i;
String ch;
do
{
p=new PrintStream(s.getOutputStream());
System.out.println("Enter the number of frames: ");
nf=Integer.parseInt(in.readLine());
p.println(nf);
if(nf<=sws-1)
{
System.out.println("Enter the "+nf+" messages to be send\n");
for(i=1;i<=nf;i++)
{
sbuff[sptr]=in.readLine();
p.println(sbuff[sptr]);
sptr=++sptr%8;
}
sws=-nf;
System.out.println("Acknowledgement received");
ano=Integer.parseInt(in1.readLine());
System.out.println("for "+ano+" frames");
sws+=nf;
}
else
{
System.out.println("The number of frames exceeds window size");
break;
}
System.out.println("\nDo you want to send some more frames?\n");
ch=in.readLine();
p.println(ch);
}
while(ch.equals("yes"));
s.close();
}
}
//RECEIVER SIDE
import java.util.*;
import java.net.*;
import java.io.*;
class slidreceiver
{
public static void main(String a[])throws Exception
{
Socket s=new Socket(InetAddress.getLocalHost(),8080);
BufferedReader in = new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintStream p=new PrintStream(s.getOutputStream());
int i=0,rptr=-1,nf,rws=8;
String rbuf[]=new String[8];
String ch; System.out.println();
do
{
nf=Integer.parseInt(in.readLine());
if(nf<=rws-1)
{
for(i=1;i<=nf;i++)
{
rptr=++rptr%8;
rbuf[rptr]=in.readLine();
System.out.println("The received Frame " +rptr+" is :
"+rbuf[rptr]);
}
rws-=nf;
System.out.println("\nAcknowledgment sent\n");
p.println(rptr+1); rws+=nf; }
else
break;
ch=in.readLine();
}
while(ch.equals("yes"));
}
}
OUTPUT
SENDER WINDOW
RECEIVER SIDE
Experiment No: 9
RSA Algorithm to Encrypt and Decrypt the Data
A very simple example of RSA encryption
This is an extremely simple example using numbers you can work out on a pocket
calculator (those of you over the age of 35 can probably even do it by hand on paper).
1. Select primes p = 11, q = 3.
2. n = pq = 11.3 = 33
phi = (p-1)(q-1) = 10.2 = 20
3. Choose e=3
Check gcd(e, p-1) = gcd(3, 10) = 1 (i.e. 3 and 10 have no common factors except 1),
and check gcd(e, q-1) = gcd(3, 2) = 1
therefore gcd(e, phi) = gcd(e, (p-1)(q-1)) = gcd(3, 20) = 1
4. Compute d such that ed ≡ 1 (mod phi)
i.e. compute d = e^-1 mod phi = 3^-1 mod 20
i.e. find a value for d such that phi divides (ed-1)
i.e. find d such that 20 divides 3d-1.
Simple testing (d = 1, 2, ...) gives d = 7
Check: ed-1 = 3.7 - 1 = 20, which is divisible by phi.
5. Public key = (n, e) = (33, 3)
Private key = (n, d) = (33, 7).
This is actually the smallest possible value for the modulus n for which the RSA
algorithm works.
Now say we want to encrypt the message m = 7,
c = m^e mod n = 7^3 mod 33 = 343 mod 33 = 13.
Hence the ciphertext c = 13.
To check decryption we compute
m' = c^d mod n = 13^7 mod 33 = 7.
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.
One way of calculating m' is as follows:-
m' = 13^7 mod 33 = 13^(3+3+1) mod 33 = 13^3.13^3.13 mod 33
= (13^3 mod 33).(13^3 mod 33).(13 mod 33) mod 33
= (2197 mod 33).(2197 mod 33).(13 mod 33) mod 33
= 19.19.13 mod 33 = 4693 mod 33
= 7.
Now if we calculate the cipher text c for all the possible values of m (0 to 32), we get
m 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
c 0 1 8 27 31 26 18 13 17 3 10 11 12 19 5 9 4
m 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
c 29 24 28 14 21 22 23 30 16 20 15 7 2 6 25 32
Note that all 33 values of m (0 to 32) map to a unique code c in the same range in a
sort of random manner. In this case we have nine values of m that map to the same value of c
- these are known as unconcealed messages. m = 0 and 1 will always do this for any N, no
matter how large. But in practice, higher values shouldn't be a problem when we use large
values for N.
If we wanted to use this system to keep secrets, we could let A=2, B=3, ..., Z=27. (We
specifically avoid 0 and 1 here for the reason given above). Thus the plaintext message
"HELLOWORLD" would be represented by the set of integers m1, m2, ...
{9,6,13,13,16,24,16,19,13,5}
Using our table above, we obtain ciphertext integers c1, c2, ...
{3,18,19,19,4,30,4,28,19,26}
Note that this example is no more secure than using a simple Caesar substitution
cipher, but it serves to illustrate a simple example of the mechanics of RSA encryption.
Remember that calculating m^e mod n is easy, but calculating the inverse c^-e mod n
is very difficult, well, for large n's anyway. However, if we can factor n into its prime
factors
p and q, the solution becomes easy again, even for large n's. Obviously, if we can get hold of
the secret exponent d, the solution is easy, too.
Key Generation Algorithm
1. Generate two large random primes, p and q, of approximately equal size such that
their product n = pq is of the required bit length, e.g. 1024 bits. [See note 1].
2. Compute n = pq and (φ) phi = (p-1)(q-1).
3. Choose an integer e, 1 < e < phi, such that gcd(e, phi) = 1. [See note 2].
4. Compute the secret exponent d, 1 < d < phi, such that
ed ≡ 1 (mod phi). [See note 3].
5. The public key is (n, e) and the private key is (n, d). The values of p, q, and phi
should also be kept secret.
n is known as the modulus.
e is known as the public exponent or encryption exponent.
d is known as the secret exponent or decryption exponent.
Encryption
Sender A does the following:-
1. Obtains the recipient B's public key (n, e).
2. Represents the plaintext message as a positive integer m [see note 4].
3. Computes the ciphertext c = m^e mod n.
4. Sends the ciphertext c to B.
Decryption
Recipient B does the following:-
1. Uses his private key (n, d) to compute m = c^d mod n.
2. Extracts the plaintext from the integer representative m.
PROGRAM
import java.util.*;
import java.io.*;
public class rsa
{ static int gcd(int m,int n)
{ while(n!=0)
{ int r=m%n;
m=n;
n=r;
}
return m;
}
public static void main(String args[])
{
int p=0,q=0,n=0,e=0,d=0,phi=0;
int nummes[]=new int[100];
int encrypted[]=new int[100];
int decrypted[]=new int[100];
int i=0,j=0,nofelem=0;
Scanner sc=new Scanner(System.in);
String message ;
System.out.println("Enter the Message tobe encrypted:");
message= sc.nextLine();
System.out.println("Enter value of p and q\n");
p=sc.nextInt();
q=sc.nextInt();
n=p*q;
phi=(p-1)*(q-1);
for(i=2;i<phi;i++)
if(gcd(i,phi)==1) break;
e=i;
for(i=2;i<phi;i++)
if((e*i-1)%phi==0)
break;
d=i;
for(i=0;i<message.length();i++)
{
char c = message.charAt(i);
int a =(int)c;
nummes[i]=c-96;
}
nofelem=message.length();
for(i=0;i<nofelem;i++)
{
encrypted[i]=1;
for(j=0;j<e;j++)
encrypted[i] =(encrypted[i]*nummes[i])%n;
}
System.out.println("\n Encrypted message\n");
for(i=0;i<nofelem;i++)
{
System.out.print(encrypted[i]);
System.out.print((char)(encrypted[i]+96));
}
for(i=0;i<nofelem;i++)
{ decrypted[i]=1;
for(j=0;j<d;j++)
decrypted[i]=(decrypted[i]*encrypted[i])%n;
}
System.out.println("\n Decrypted message\n ");
for(i=0;i<nofelem;i++)
System.out.print((char)(decrypted[i]+96));
return;
}
}
OUTPUT
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.
Using TCP/IP Sockets, write a client-server program to make client
sending the file name and the server to send back the contents of the
requested file if present. Implement the above program 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 creates a socket object on it
end of the communication. The client and the server can now
communicate by writing to and reading from the socket.
PROGRAM
CLIENT PROGRAM
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws
UnknownHostException, IOException {
String ipAddress = "localhost";
int portNumber = 9000;
Socket socket = new Socket(ipAddress, portNumber);
System.out.println("Enter the name of the file ");
Scanner scanner = new Scanner(System.in);
String fileName = scanner.nextLine();
PrintWriter out = new
PrintWriter(socket.getOutputStream(), true);
out.println(fileName);
BufferedReader bReader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String string = "";
while((string = bReader.readLine()) != null) {
System.out.println(string);
}
scanner.close();
socket.close();
}
}
SERVER SIDE
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException,
InterruptedException {
ServerSocket serverSocket = new ServerSocket(9000);
System.out.println("Server is up and running!");
Socket socket = serverSocket.accept();
BufferedReader bReader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String fileName = bReader.readLine();
System.out.println("Searching for file: " + fileName);
File file = new File("client.txt");
PrintWriter out = new
PrintWriter(socket.getOutputStream(), true);
String existingFile = file.getName();
if(fileName.equals(existingFile)) {
BufferedReader fileReader = new
BufferedReader(new FileReader(file));
System.out.println("File found! Streaming data
from file to client...");
String string = "";
while((string = fileReader.readLine()) != null) {
out.println(string);
Thread.sleep(2000);
}
System.out.println("Streaming done");
fileReader.close();
}
else {
System.out.println("There is no file " +
fileName + " in server!");
out.println("Sorry, No such file exists!");
}
serverSocket.close();
}
}
OUTPUT
CLIENT WINDOW OUTPUT
SERVER WINDOW OUTPUT