CN Lab Manual
CN Lab Manual
CN Lab Manual
TABLE OF CONTENTS
EXP.NO DATE EXPERIMENT NAME PAGE NO
1 INTRODUCTION TO NETWORK
PROGRAMMING BASICS
6 IMPLEMENTATION OF:
14 IMPLEMENTATION OF DIJIKSTRA’S
SHORTEST PATH ROUTING ALGORITHM
1. NETWORKING BASICS
Host : A computer system that is accessed by a user working at a remote location. It is the remote
process with which a process communicates. It may also be referred as Peer.
Server: In computer networking, a server is a computer designed to process requests and deliver
data to other computers over a local network or the Internet.
Iterative servers: This server knows ahead of time about how long it takes to handle each request &
server process handles each request itself.
Concurrent servers: The amount of work required to handle a request is unknown, so the server
starts another process to handle each request.
Client: A Client is an application that runs on a personal computer or workstation and relies on a
Protocols: A Protocol is a convention or standard rules that enables and controls the connection,
Port: An interface on a computer to which you can connect a device. It is a "logical connection
A port is a 16-bit number, used by the host-to-host protocol to identify to which higher_level
protocol or application program (process) it must deliver incoming messages.
PORTS RANGE
Association: Association is used for 5 tuple that completely specifies the two processes that
make up a connection.
The local address and foreign address specify the network ID & Host-ID of the local host and the
foreign host in whatever format is specified by protocol suite. The local process and foreign process
are used to identify the specific processes on each system that are involved in a connection.
which specify each half of a connection. This half association is called a Socket or transport address.
CLIENT-SERVER MODEL
Network applications can be divided into two process: a Client and a Server, with a communication
link joining the two processes.
Normally, from Client-side it is one-one connection. From the Server Side, it is many-one connection.
The standard model for network applications is he Client-Sever model. A Server is a process that is
waiting to be contacted by a Client process so that server can do something for the client.
Typical BSD Sockets applications consist of two separate application level processes; one process
(the client) requests a connection and the other process (the server ) accepts it.
The server process creates a socket, binds an address to it, and sets up a mechanism (called a
listen queue) for receiving connection requests. The client process creates a socket and requests a
connection to the server process. Once the server process accepts a client process's request and
establishes a connection, full-duplex (two-way) communication can occur between the two sockets.
Socket functions for elementary UDP client/server in Connection-less Scenario
Sockets Overview
The operating system includes the Berkeley Software Distribution (BSD) interprocess
communication (IPC) facility known as sockets. Sockets are communication channels that enable
unrelated processes to exchange data locally and across networks. A single socket is one end
Sockets Overview: In the operating system, sockets have the following characteristics:
Sockets are referenced by file descriptors and have qualities similar to those of a character special
device. Read, write, and select operations can be performed on sockets by using the appropriate
subroutines.
Sockets can be created in pairs, given names, or used to rendezvous with other sockets in
a communication domain, accepting connections from these sockets or exchanging messages with
them.
Socket() System Call: Creates an end point for communication and returns a descriptor.
Syntax
#include <sys/socket.h>
#include <sys/types.h>
Description: The socket subroutine creates a socket in the specified AddressFamily and of the
specified type. A protocol can be specified or assigned by the system. If the protocol is left
unspecified (a value of 0), the system selects an appropriate protocol from those protocols in the
address family that can be used to support the requested socket type. The socket subroutine returns
a descriptor (an integer) that can be used in later subroutines that operate on sockets.
Parameters
AddressFamily Specifies an address family with which addresses specified in later socket operations
should be interpreted. Commonly used families are:
Type Specifies the semantics of communication. The operating system supports the following types:
SOCK_STREAM
Provides sequenced, two-way byte streams with a transmission mechanism for out-of-band data.
SOCK_DGRAM
Provides datagrams, which are connectionless messages of a fixed maximum length (usually short).
SOCK_RAW
Provides access to internal network protocols and interfaces. This type of socket is available only to
the root user.
SOCK_SEQPACKET
Sequenced packet socketProtocol Specifies a particular protocol to be used with the socket.
Specifying the
Protocol parameter of 0 causes the socket subroutine to select system’s default for the combination
of family and type.
Return Values Upon successful completion, the socket subroutine returns an integer (the socket
Syntax
#include <sys/socket.h>
sockfd is a socket descriptor returned by the socket function. The second argument is a pointer
to a protocol specific address and third argument is size of this address structure.
a) Server registers their well-known address with a system. Both connection-oriented and
c) A Connectionless client needs to assure that the system assigns it some unique address,
so that the other end (the server) has a valid return address to send its responses to.
Return Values: Upon successful completion, the bind subroutine returns a value of 0. Otherwise,
The connect() function is used by a TCP client to establish a connection with a TCP server.
#include <sys/socket.h>
sockfd is a socket descriptor returned by the socket function. The second and third arguments
are a pointer to a socket address structure and its size. The socket address structure must contain
the IP address and port number of the server. Return Values: Upon successful completion, the
connect subroutine returns a value of 0.
This system call is used by a connection-oriented server to indicate that it is willing to receive
connections.
#include <sys/socket.h>
It is usually executed after both the socket and bind system calls, and immediately before accept
system call. The backlog argument specifies how many connections requests can be queued by
the system while it waits for the server to execute the accept system call.
accept() System call: The actual connection from some client process is waited for by having
#include <sys/socket.h>
accept takes the first connection request on the queue and creates another socket with the same
properties as sockfd. If there are no connection requests pending, this call blocks the caller until
one arrives. The cliaddr and addrlen arguments are used to return the protocol address of the
These system calls are similar to the standard read and write functions, but one additional
argument is required.
#include <sys/socket.h>
int sendto(int sockfd, char void *buff, int nbytes, int flags, struct sockaddr *to, int
addrlen);
int recvfrom(int sockfd, char *buff, int nbytes, int flags, struct sockaddr *from, int
*addrlen);
The first three arguments, sockfd, buff and nbytes are the same as the first three arguments to
read and write. The flags argument is either 0 or is formed by logically OR'ing one or more of
the constants.
The normal Unix close function is also used to close a socket and terminate a TCP connection.
#include <unistd.h>
DESCRIPTION:
TCP Server gets the message and opens the server socket to read the client details. Client send its
mesage. Then server displays the messages received from the client.
ALGORITHM :
Server :
Specify the port where the service will be defined to be used by client.
Server executes listen() system call to indicate its willingness to receive connections.
Accept the next completed connection from the client process by using an accept() system call.
Stop.
Client:
For echo server, send a message to the server to be echoed using send() system call.
Stop.
FLOW-CHART :
SOURCE CODE:
( Static Input )
//Server :
import java.io.*;
import java.net.*;
public class ServerFileName
try
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
catch(Exception e)
System.out.println(e);
//Client :
import java.io.*;
import java.net.*;
try
dout.flush();
dout.close();
s.close();
catch(Exception e)
System.out.println(e);
( Dynamic Input )
//Server :
import java.io.*;
import java.net.*;
try
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
catch(Exception e)
{
System.out.println(e);
//Client :
import java.io.*;
import java.net.*;
try
String str="";
str=br.readLine();
dout.writeUTF(str);
dout.flush();
dout.close();
s.close();
catch(Exception e)
System.out.println(e);
}
SAMPLE INPUT AND SAMPLE OUPUT :
( Static Input )
Client :
javac ClientFileName.java
java ClientFileName
Server:
javac ServerFileName.java
java ServerFileName
(Dynamic Input )
Client :
javac ClientFileName.java
java ClientFileName
hi testing!
Server:
javac ServerFileName.java
java ServerFileName
message= hi testing!
RESULT :
Thus, the java program to implement the echo client server using the TCP/IP sockets by giving
both (static and dynamic input) is executed.
2(b) IMPLEMENTATION OF TCP ECHO CHAT CLIENT-SERVER
AIM:
To implement the echo chat client and server using TCP sockets.
DESCRIPTION:
TCP Server gets the message and opens the server socket to read the client details. Client send its
message. Then server displays the messages received from the client. Similarly server sends the
message to the client. The client receives the message from the server and display it.
ALGORITHM:
Server :
Specify the port where the service will be defined to be used by client.
Server executes listen() system call to indicate its willingness to receive connections.
Accept the next completed connection from the client process by using an accept() system call.
Stop.
Client:
For echo server, send a message to the server to be echoed using send() s1ystem call.
10. Receive the message from the servert using recv() system call and display it.
13. Stop.
FLOW-CHART
SOURCE CODE:
//Server
import java.net.*;
import java.io.*;
class ServerFileName
{
Socket s=ss.accept();
String str="",str2="";
while(!str.equals("stop"))
str=din.readUTF();
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
din.close();
s.close();
ss.close();
//Client :
import java.net.*;
import java.io.*;
class ClientFileName
String str="",str2="";
while(!str.equals("stop"))
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
dout.close();
s.close();
}
SAMPLE INPUT AND SAMPLE OUPUT :
Client :
javac ClientFileName.java
java ClientFileName
hi
tested
Server:
javac ServerFileName.java
java ServerFileName
Client says: hi
hello
RESULT :
Thus, the java program to implement the echo chat client and server using the TCP sockets is
executed.
2(C) IMPLEMENTATION OF CONCURRENT ECHO SERVER USING TCP
CONNECTION SOCKET SYSTEM CALLS
Aim: To implement the concurrent echo server using TCP connection socket system calls.
Problem Description: The amount of work required to handle a request is unknown, so the server
starts another process to handle each request. In order to implement the Iterative Service we need to
create an application for instance say client, which will be invoking service which is established on the
Iterative server working on a user-defined port. The Client will be creating its socket endpoint and
establish a connection with the Iterative server by specifiying the port number similar to that of the
Server
Concurrent servers: The amount of work required to handle a request is unknown, so the server starts
another process to handle each request.
Algorithm:
Server:
Specify the port where the service will be defined to be used by client.
Server executes listen() system call to indicate its willingness to receive connections.
Accept the next completed connection from the client process by using an accept() system call.
Create a new process (child process) using fork(), to handle the client request. The parent process will
be waiting for new incoming connections.
Send the result of the request made by the client using send() system call.
Client:
Include appropriate header files.
For echo server, send a message to the server to be echoed using send() system call.
Receive the result of the request made to the server using recv() system call.
SOURCE CODE:
//Server :
import java.io.*;
import java.net.*;
class ServerFileName
try
server.setReuseAddress(true);
while (true)
new Thread(clientSock).start();
catch (IOException e)
e.printStackTrace();
finally
if (server != null)
try
server.close();
catch (IOException e)
e.printStackTrace();
// ClientHandler class
// Constructor
this.clientSocket = socket;
BufferedReader in = null;
try
clientSocket.getOutputStream(), true);
String line;
out.println(line);
catch (IOException e)
e.printStackTrace();
finally
try
{
if (out != null)
out.close();
if (in != null)
in.close();
clientSocket.close();
catch (IOException e)
e.printStackTrace();
//Client 1 :
import java.io.*;
import java.net.*;
import java.util.*;
// Client class
class Client1FileName
// driver code
{
// establish a connection by providing host and port number
// writing to server
while (!"exit".equalsIgnoreCase(line))
line = sc.nextLine();
out.println(line);
out.flush();
sc.close();
catch (IOException e)
e.printStackTrace();
}
//Client 2 :
import java.io.*;
import java.net.*;
import java.util.*;
// Client class
class Client2FileName
// driver code
// writing to server
while (!"exit".equalsIgnoreCase(line))
line = sc.nextLine();
out.println(line);
out.flush();
sc.close();
catch (IOException e)
e.printStackTrace();
//Client 3 :
import java.io.*;
import java.net.*;
import java.util.*;
// Client class
class Client3FileName
// driver code
// writing to server
while (!"exit".equalsIgnoreCase(line))
line = sc.nextLine();
out.println(line);
out.flush();
sc.close();
catch (IOException e)
e.printStackTrace();
Client 1:
javac Client1FileName.java
java Client1FileName
This is Client-1
javac Client2FileName.java
java Client2FileName
This is Client-2
Client 3:
javac Client3FileName.java
java Client3FileName
This is Client-3
PROGRAM EXECUTED!!!!
Server:
javac ServerFileName.java
java ServerFileName
RESULT :
Thus, the java program to implement the Concurrent server using the TCP connection socket
system call is executed.
EXP .NO : 3 PROGRAMS USING TCP SOCKETS
Aim:
To 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 using TCP/IP sockets.
Algorithm:
Server Process:
3. Convert the socket into a listening socket using listen( ) sytem call.
5. Receive the Client request using recv() system call which consist of the name of
7. On successful execution the result is passed back to the client by the server
Client Process:
1. Create a socket.
4. The client passes the command and data parameters (if any) to the server.
SOURCE CODE:
//Server :
import java.io.*;
import java.net.*;
public class ServerFileName{
Socket sr=s.accept();
fr.read(b, 0, b.length);
OutputStream os=sr.getOutputStream();
os.write(b, 0, b.length);
sr.close();
fr.close();
//Client :
import java.io.*;
import java.net.*;
InputStream is=s1.getInputStream();
is.read(b, 0, b.length);
fr.write(b, 0, b.length);
String st;
while((st=br.readLine()) != null)
System.out.println(st);
s1.close();
fr.close();
Client :
javac ClientFileName.java
java ClientFileName
Server:
javac ServerFileName.java
java ServerFileName
Execution process:
This content //COMPUTER NETWORKING LABORATORY// which is given as the content to be stored
in the Text file by the Client to the Server will be saved as the textfile content in the file at location
//("E:\\CONTENT.txt")// with respective filename mentioned as given in the Client code .
Preview:
RESULT :
Thus, the client-server program to make client sending the file name and the server to send back
the contents of the requested file if present using TCP/IP sockets is executed.
3(b) DATE AND TIME SERVER USING TCP SOCKETS
AIM: To implement date and time display from client to server using TCP Sockets.
DESCRIPTION: TCP Server gets the system date and time and opens the server socket to read the
client details. Client send its address to the server. Then client receives the date and time from
server to display. TCP socket server client connection is opened for communication. After the date
time is displayed the server client connection is closed with its respective streams to be closed.
ALGORITHM:
Server
2. Listen for new connection and when a connection arrives, accept it.
9. Stop
Client
7. Stop.
SOURCE CODE:
import java.net.*;
import java.io.*;
import java.util.*;
class tcpdateserver
ServerSocket ss = null;
Socket cs;
PrintStream ps;
BufferedReader dis;
String inet;
try
ss = new ServerSocket(4444);
while(true)
cs = ss.accept();
ps = new PrintStream(cs.getOutputStream());
ps.println(d);
inet = dis.readLine();
ps.close();
dis.close();
catch(IOException e)
{
System.out.println("The exception is :" + e);
import java.net.*;
import java.io.*;
class tcpdateclient
Socket soc;
BufferedReader dis;
String sdate;
PrintStream ps;
try
InetAddress ia = InetAddress.getLocalHost();
if (args.length == 0)
else
sdate=dis.readLine();
ps = new PrintStream(soc.getOutputStream());
ps.println(ia);
ps.close();
catch(IOException e)
{
Server:
$ javac tcpdateserver.java
$ java tcpdateserver
Client:
$ javac tcpdateclient.java
$ java tcpdateclient
Every time when a client connects to the server, server‟s date/time will be returned to the client for
synchronization.
RESULT :
Thus, the Java program to implement date and time display from client to server using TCP
Sockets is executed.
3(c) STRING REVERSE OPERATION USING TCP SOCKETS
Aim: To develop a program for connection-oriented Iterative Service in which server reverses the
string sent by the client and sends it back using TCP sockets.
Algorithm:
Server Process:
3. Convert the socket into a listening socket using listen( ) sytem call.
5. Receive the Client request using recv() system call which consist of the name of
7. On successful execution the result is passed back to the client by the server
Client Process:
1.Create a socket.
4.The client passes the command and data parameters (if any) to the server.
SOURCE CODE:
//Server:
import java.net.*;
import java.io.*;
System.out.println("Server is Waiting");
while(true){
StringBuilder op=inp.reverse();
out.writeUTF(op.toString());
//Client:
import java.net.*;
import java.io.*;
import java.util.Scanner;
InetAddress ia = InetAddress.getLocalHost();
out.writeUTF(inp);
System.out.println(in.readUTF().toString());
cSock.close();
}
}
SAMPLE INPUT AND SAMPLE OUTPUT:
Server:
javac ReverseServer.java
java ReverseServer
Server is Waiting
Client:
javac ReverseClient.java
java ReverseClient.java
cnlab
balnc
RESULT :
Thus, the Java program for connection-oriented Iterative Service in which server reverses the
string sent by the client and sends it back using TCP sockets is executed.
EXP .NO : 4 PROGRAMS USING UDP SOCKETS
ALGORITHM:
Server
1. Create two ports, server port and client port.
2. Create a datagram socket() and bind() it to client port.
3. Create a datagram packet to receive client message
4. Wait for client's data and accept it.
5. Read Client's message using using recvfrom() system call
6. Get data from user.
7. Create a datagram packet and send message through server port using sendto() system call.
8. Repeat steps 3-7 until the client has something to send.
9. Close the server socket.
10. Stop
Client
1. Create two ports, server port and client port.
2. Create a datagram socket and bind it to server port.
3. Get data from user.
4. Create a datagram packet and send data with server ip address and client port.
5. Create a datagram packet to receive server message using recvfrom() system call
6. Read server's response and display it.
7. Repeat steps 3-6 until there is some text to send.
8. Close the client socket.
SOURCE CODE:
import java.io.*;
import java.net.*;
class UDPChatServer
System.out.println("Server Ready");
while (true)
SrvSoc.receive(RPack);
if (Text.trim().length() == 0)
break;
SrvSoc.send(SPack);
System.out.println("\nClient Quits\n");
SrvSoc.close();
import java.io.*;
import java.net.*;
class UDPChatClient
InetAddress IPAddr;
String Text;
if (args.length == 0)
IPAddr = InetAddress.getLocalHost();
else
IPAddr = InetAddress.getByName(args[0]);
while (true)
{
Text = br.readLine();
SData = Text.getBytes();
CliSoc.send(SPack);
if (Text.trim().length() == 0)
break;
CliSoc.receive(RPack);
Echo = Echo.trim();
CliSoc.close();
Server
$ javac UDPChatServer.java
$ java UDPChatServer
Server Ready
From Client <<< are u the SERVER
Msg to Cleint : yes
From Client <<< what do u have to serve
Msg to Cleint : no eatables
Client Quits
Client
$ javac UDPChatClient.java
$ java UDPChatClient
Press Enter without text to quit
Enter text for server : are u the SERVER
From Server <<< yes
Enter text for server : what do u have to serve
From Server <<< no eatables
Enter text for server : Ok
RESULT:
Thus, the java program to implement a chat server and client in java using UDP sockets is executed.
4(b). DOMAIN NAME SYSTEM SERVER USING UDP SOCKETS
AIM:
To implement a DNS server and client in java using UDP sockets.
Problem Definition: The Domain Name System (DNS) is a hierarchical naming system for computers,
services, or any resource participating in the Internet. The Domain Name System distributes the
responsibility of assigning domain names and mapping those names to IP addresses
Problem Description:
The Client program sends a request containing domain-name to the server and the server returns back
the IP address of the domain-name to the client.
ALGORITHM:
Server
1. Create an array of hosts and its ip address in another array
2. Create a datagram socket and bind it to a port
3. Create a datagram packet to receive client request
4. Read the domain name from client to be resolved
5. Lookup the host array for the domain name
6. If found then retrieve corresponding address
7. Create a datagram packet and send ip address to client
8. Repeat steps 3-7 to resolve further requests from clients
9. Close the server socket
10. Stop
Client
1.Create a datagram socket
2. Get domain name from user
3. Create a datagram packet and send domain name to the server
4. Create a datagram packet to receive server message
5. Read server's response
6. If ip address then display it else display "Domain does not exist"
7. Close the client socket
8. Stop
SOURCE CODE:
import java.io.*;
import java.net.*;
{
if (array[i].equals(str))
return i;
return -1;
while (true)
serversocket.receive(recvpack);
String capsent;
else
senddata = capsent.getBytes();
serversocket.send(pack);
serversocket.close();
}
import java.io.*;
import java.net.*;
InetAddress ipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);
senddata = sentence.getBytes();
clientsocket.send(pack);
clientsocket.receive(recvpack);
RESULT :
Thus, the domain name requests by the client are resolved into their respective logical address
using lookup method is executed.
EXP .NO : 5 PROGRAMS USING RAW SOCKETS
ALGORITHM:
SOURCE CODE:
//PingWebsite
// sub-process
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
throws Exception
{
// creating the sub process, execute system command
String s = null;
System.out.println(s);
System.out.println(s);
// Driver method
commandList.add("ping");
// can be replaced by IP
commandList.add("www.google.com");
PingWebsite.commands(commandList);
javac PingWebsite.java
java PingWebsite
RESULT :
Thus, the java program to implement a ping using raw sockets is executed.
5(b). IMPLEMENTATION OF TRACEROUTE USING RAW SOCKETS
AIM:
To write a java program for Traceroute using raw sockets.
ALGORITHM:
(i) Details of the intermediate nodes such as IP address that lies between source to
destination.
(iii) Time taken for reachiing the each and every intermediate nodes .
SOURCE CODE:
//Traceroute
import java.io.*;
import java.net.*;
import java.lang.*;
class Traceroute
BufferedReader in;
try{
Runtime r=Runtime.getRuntime();
Process p=r.exec("tracert www.google.com");
String line;
if(p==null)
while((line=in.readLine())!=null)
System.out.println(line);
catch(IOException e)
System.out.println(e.toString());
javac Traceroute.java
java Traceroute
RESULT :
Thus, the java program for tracing the route using the raw sockets is executed.
EXP .NO : 6 IMPLEMENTATION OF
ALGORITHM:
Client:
Server:
3. Server maintains the table in which IP and corresponding MAC addresses are stored.
5. Map the IP address with its MAC address and return the MAC address to client.
SOURCE CODE:
//Server: Serverarp.java
import java.io.*;
import java.net.*;
import java.util.*;
class Serverarp
try
{
ServerSocket obj=new ServerSocket(138);
Socket obj1=obj.accept();
while(true)
String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
if(str.equals(ip[i]))
dout.writeBytes(mac[i]+'\n');
break;
obj.close();
catch(Exception e)
System.out.println(e);
//Client: Clientarp.java
import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
try
String str1=in.readLine();
dout.writeBytes(str1+'\n');
String str=din.readLine();
clsct.close();
catch (Exception e)
System.out.println(e);
Server:
javac Serverarp.java
java Serverarp
Client:
javac Clientarp.java
java Clientarp
Enter the Logical address(IP):
165.165.80.80
RESULT:
Thus, the java program for simulating ARP protocols using TCP socket is executed.
6 (b). REVERSE ADDRESS RESOLUTION PROTOCOL (RARP) USING UDP SOCKET
Aim: To write a java program for simulating RARP protocols using UDP sockets.
ALGORITHM :
Client:
Server:
2. Server maintains the table in which IP and corresponding MAC addresses are stored.
4. Map the IP address with its MAC address and return the IP address to client.
SOURCE CODE :
//Server: Serverrarp.java
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrarp
try
while(true)
{
byte[] sendbyte=new byte[1024];
server.receive(receiver);
String s=str.trim();
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
if(s.equals(mac[i]))
sendbyte=ip[i].getBytes();
server.send(sender);
break;
break;
catch(Exception e)
System.out.println(e);
}
//Client: Clientrarp.java
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrarp
try
InetAddress addr=InetAddress.getByName("127.0.0.1");
String str=in.readLine();
sendbyte=str.getBytes();
client.send(sender);
client.receive(receiver);
client.close();
catch(Exception e)
System.out.println(e);
}
}
Server:
javac Serverrarp.java
java Serverrarp
Client:
javac Clientrarp.java
java Clientrarp
6A:08:AA:C2
RESULT:
Thus, the java program for simulating RARP protocols using UDP socket is executed.
EXP .NO : 7 IMPLEMENTATION OF SLIDING WINDOW PROTOCOL
ALGORITHM :
Sender:
5. If error free acknowledgement from receiver is recieved and next frame expected→sequence
comes, then sequence's next frame is expected.
7. Stop.
Receiver:
1. Start.
3. If error free frame received and the sequence is next frame expected, then it passes packet to
higher layer and next frame is expected.
4.Stop.
SOURCE CODE:
//Server: Sender.java
import java.io.*;
import java.net.*;
Socket sender;
ObjectOutputStream out;
ObjectInputStream in;
Sender(){}
try{
sequence=0;
out=new ObjectOutputStream(sender.getOutputStream());
out.flush();
in=new ObjectInputStream(sender.getInputStream());
str=(String)in.readObject();
packet=br.readLine();
n=packet.length();
do{
try{
if(i<n)
msg=String.valueOf(sequence);
msg=msg.concat(packet.substring(i,i+1));
else if(i==n)
msg="end";out.writeObject(msg);break;
}
out.writeObject(msg);
sequence=(sequence==0)?1:0;
out.flush();
System.out.println("data sent>"+msg);
ack=(String)in.readObject();
if(ack.equals(String.valueOf(sequence)))
i++;
else
sequence=(sequence==0)?1:0;
}catch(Exception e){}
}while(i<n+1);
}catch(Exception e){}
finally{
try{
in.close();
out.close();
sender.close();
catch(Exception e){}
}
public static void main(String args[])
s.run();
//Client : Receiver.java
import java.io.*;
import java.net.*;
ServerSocket reciever;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,data="";
int i=0,sequence=0;
Receiver(){}
try{
connection=reciever.accept();
sequence=0;
out=new ObjectOutputStream(connection.getOutputStream());
out.flush();
in=new ObjectInputStream(connection.getInputStream());
out.writeObject("connected .");
do{
try{
packet=(String)in.readObject();
if(Integer.valueOf(packet.substring(0,1))==sequence){
data+=packet.substring(1);
sequence=(sequence==0)?1:0;
System.out.println("\n\nreceiver >"+packet);
else
if(i<3)
out.writeObject(String.valueOf(sequence));i++;
else
out.writeObject(String.valueOf((sequence+1)%2));
i=0;
catch(Exception e){}
while(!packet.equals("end"));
System.out.println("Data recived="+data);
out.writeObject("connection ended .");
catch(Exception e){}
finally{
try{
in.close();
out.close();
reciever.close();
}catch(Exception e){}
while(true){
s.run();
Server:
javac Sender.java
java Sender
Client:
javac Receiver.java
java Receiver
RESULT:
Thus, the java program to implement the Stop and Wait Sliding Window protocol is executed.
7 (b). GO BACK ‘N’ PROTOCOL
Problem definition:
The Program sends the frames from the Client to the Server with checking for missing frames via
sending an acknowledgement.
Algorithm:
Server:
2.Start the function sender and let send base and next seq as’0’.
3.If next days < send base+v then send packet send seq assign next seq as next seqn+1.
6.If time out then start timer again send packets send base, and base+1... send packet next seqn-1.
Client:
1.Start the program and function as receiver and assign next seq=0.
2.If a packet received and it is not completed also it seq.no = next.seqn.no then deliver the data to
upper layer.
SOURCE CODE:
//Server:ARQ_Server.java
import java.net.*;
import java.io.*;
import java.util.*;
System.out.println("Server established.");
Socket client=server.accept();
int x=(Integer)ois.readObject();
int k=(Integer)ois.readObject();
int j=0;
int i=(Integer)ois.readObject();
boolean flag=true;
int mod=r.nextInt(6);
while(mod==1||mod==0)
mod=r.nextInt(6);
while(true)
int c=k;
for(int h=0;h<=x;h++)
System.out.print("|"+c+"|");
c=(c+1)%x;
System.out.println();
System.out.println();
if(k==j)
j++;
System.out.println();
else
System.out.println();
{
System.out.println("Error found. Acknowledgement not sent.");
flag=!flag;
j--;
else if(k==j-1)
oos.writeObject(k);
System.out.println("Acknowledgement sent");
System.out.println();
if(j%mod==0)
flag=!flag;
k=(Integer)ois.readObject();
if(k==-1)
break;
i=(Integer)ois.readObject();
oos.writeObject(-1);
//Client:ARQ_Client.java
import java.util.*;
import java.net.*;
import java.io.*;
int m=Integer.parseInt(br.readLine());
int x=(int)((Math.pow(2,m))-1);
int count=Integer.parseInt(br.readLine());
int h=0;
for(int i=0;i<count;i++)
data[i]=Integer.parseInt(br.readLine());
h=(h+1)%x;
boolean flag=false;
listener=new GoBackNListener(ois,x);
listener.t.start();
int strt=0;
h=0;
oos.writeObject(x);
do
int c=h;
for(int i=h;i<count;i++)
System.out.println("|"+c+"|");
c=(c+1)%x;
System.out.println();
System.out.println();
h=strt;
for(int i=strt;i<x;i++)
{
System.out.println("Sending frame:"+h);
h=(h+1)%x;
System.out.println();
oos.writeObject(i);
oos.writeObject(data[i]);
Thread.sleep(100);
listener.t.join(3500);
if(listener.reply!=x-1)
System.out.println();
strt=listener.reply+1;
flag=false;
else
flag=true;
}while(!flag);
oos.writeObject(-1);
Thread t;
ObjectInputStream ois;
int reply,x;
GoBackNListener(ObjectInputStream o,int i)
t=new Thread(this);
ois=o;
reply=-2;
x=i;
@Override
try
int temp=0;
while(reply!=-1)
{
reply=(Integer)ois.readObject();
reply=temp;
if(reply!=-1)
temp=reply;
System.out.println();
reply=temp;
catch(Exception e)
Server:
javac ARQ_Server.java
java ARQ_Server
Server established.
Client is now connected.
Frame 0 recieved
Data:0
Acknowledgement sent
Frame 1 recieved
Data:1
Error found. Acknowledgement not sent.
Frames recieved not in correct order
Expected farme:1
Recieved frame no :2
Frames recieved not in correct order
Expected farme:1
Recieved frame no :3
Frames recieved not in correct order
Expected farme:1
Recieved frame no :4
Client:
javac ARQ_Client.java
java ARQ_Client
Sending frame:0
Acknowledgement of frame no 0 recieved.
Sending frame:1
Sending frame:2
Sending frame:3
Sending frame:4
Sending frame:5
*/
/*
RESULT:
Thus, the java program to implement the Go Back ‘N’ protocol is executed.
7 (c). SELECTIVE REPEAT ARQ PROTOCOL
Aim: To write a java program to implement the Selective Repeat ARQ protocol .
ALGORITHM :
1.Start.
2.Establish Connection.
11.Wait for the acknowledgement of each packet and repeat the process for the packet for which
the negative acknowledgement is received.
13. Increment the frame count and repeat steps to 13 until all packets are transmitted.
15. Stop.
SOURCE CODE:
//Server : RepeatARQserver.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
try
int a[] = { 30, 40, 50, 60, 70, 80, 90, 100 };
int y = a.length;
dos.write(y);
dos.flush();
dos.write(a[i]);
dos.flush();
int k = dis.read();
dos.write(a[k]);
dos.flush();
catch (IOException e)
System.out.println(e);
finally
try
dis.close();
dos.close();
catch (IOException e)
e.printStackTrace();
//Client : RepeatARQclient.java
import java.lang.System;
import java.net.*;
import java.io.*;
import java.text.*;
import java.util.Random;
import java.util.*;
try {
int n = 0;
int rand = 0;
System.out.println(addr);
connection.getOutputStream());
connection.getInputStream());
int p = in.read();
v[i] = in.read();
System.out.println(v[i]);
//g[i] = v[i];
v[rand] = -1;
if (v[i] == -1) {
n = i;
out.write(n);
out.flush();
System.out.println();
v[n] = in.read();
System.out.println("quiting");
} catch (Exception e) {
System.out.println(e);
Server:
javac RepeatARQserver.java
java RepeatARQserver
Client:
javac RepeatARQclient.java
java RepeatARQclient
RESULT:
Thus, the java program to implement the Selective Repeat ARQ protocol is executed.
EXP .NO : 8 REMOTE COMMAND EXECUTION USING TCP SOCKETS
Aim: To write a java program for remote command execution using TCP sockets
Problem Definition:
Problem Description:
The problem can be implemented using sockets General implementation steps are as follows.
ALGORITHM :
Server:
3. Convert the socket into listening socket using listen () system call.
4. Wait for the client connection to complete using accept () system call.
5. Receive the client request using recv() system call which consists of the name of the command
that is to be executed along with the data parameters (if any).
7. On successful execution the result is passed back to the client by the server.
Client:
1. Create a socket.
4. The client passes the command and data parameters (if any) to the server.
5. Read the result sent by the server, write it to the standard output.
SOURCE CODE:
//Server: RemoteServer.java
import java.io.*;
import java.net.*;
class RemoteServer
try
int Port;
InputStreamReader(System.in));
Port=Integer.parseInt(Buf.readLine());
Socket s=ss.accept();
if(s.isConnected()==true)
InputStream in=s.getInputStream();
OutputStream ou=s.getOutputStream();
InputStreamReader(in));
String cmd=buf.readLine();
pr.println(cmd);
Runtime H=Runtime.getRuntime();
Process P=H.exec(cmd);
pr.flush();
pr.close();
ou.close();
in.close();
catch(Exception e)
//Client: RemoteClient.java
import java.io.*;
import java.net.*;
class RemoteClient
try
int Port;
InputStreamReader(System.in));
Port=Integer.parseInt(Buf.readLine());
if(s.isConnected()==true)
InputStream in=s.getInputStream();
OutputStream ou=s.getOutputStream();
InputStreamReader(System.in));
BufferedReader buf1=new BufferedReader(new
InputStreamReader(in));
pr.println(buf.readLine());
pr.flush();
String str=buf1.readLine();
pr.close();
ou.close();
in.close();
catch(Exception e)
Server:
javac RemoteServer.java
java RemoteServer
Client:
javac RemoteClient.java
java RemoteClient
RESULT:
Thus, the java program for Remote Command Execution using TCP socket is executed.
EXP.NO:9 REMOTE METHOD INVOCATION TO FIND FACTORIAL OF A NUMBER
Aim: To write the Remote Method Invocation program to find the factorial of a given number.
ALGORITHM:
1. Start.
2. To perform RMI operation create interface file , implementation file , server file and client file.
4. Perform the RMI compilation for the implementation file to create sub and skeleton by using rmic
command.
7.Stop.
SOURCE CODE:
//Server : rmiserver.java
import java.net.*;
import java.rmi.*;
try
Naming.rebind("rmi://localhost:5000/abc",m);
catch(Exception e)
System.out.println("Exception"+e);
}
}
//Client : rmiclient.java
import java.io.*;
import java.rmi.*;
try
serverint f=(serverint)Naming.lookup("rmi://localhost:5000/abc");
int n1=Integer.parseInt(m.readLine());
catch(Exception e)
System.out.println(e);
import java.rmi.*;
import java.rmi.server.*;
}
public int fact(int n)
int i,c=1;
for(i=1;i<=n;i++)
c=i*c;
return c;
import java.rmi.*;
Server:
javac serverimpl.java
java rmiserver
Client:
javac rmiclient.java
java rmiclient
RESULT:
Thus, the Remote Method Invocation program to find the factorial of a given number is executed.
EXP.NO:10 UPLOAD AND DOWNLOAD A PAGE IN A WEBSERVER
USING TCP SOCKET
Aim: To write a java program to create a TCP socket or http for a webpage to upload and to
download data.
ALGORITHM:
Server:
1. Start
3. Create server socket using port number and accept the connection using socket.
4. Now, read the content of image using data input stream class.
5. Create new byte array called data with image size as its length and close the connection.
6. Now create a buffered image object reference and read the data using Image IO. read() method.
7. Create a frame through JFrame class and set the image read inside it through the object of the
Jlabel class.
8. Pack the frame and make it visible so that the uploaded image can be viewed and wait sometime
for image to be downloaded.
9. Stop.
Client:
1. Start
2. Import awt and swing packages for uploading image and net package for downloading the data.
4. Read the image and convert into byte array from disk using the Byte Array of () ByteArrayOutput
Stream class.
5. Send the data that is to be uploaded to server using data output stream class and close the
connection.
6. To download an image or data create an object to the string class say the website and specify the
URL from where the image or data to be downloaded.
7. Now create an object to the URL class with the string representation.
8. Read the content of the data or image to be downloaded using an object of input stream class
and write the read content into file using write() method of the output stream class.
SOURCE CODE:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
try{
String website =
"https://images.financialexpress.com/2021/07/"+fileName;
int length = 0;
outputStream.write(buffer, 0, length);
inputStream.close();
outputStream.close();
}catch(Exception e){
}
}
//Uploading Code:
//Server: updownserver.java
import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class updownserver{
ServerSocket server=null;
Socket socket;
server=new ServerSocket(4000);
socket=server.accept();
InputStream in=socket.getInputStream();
int len=dis.readInt();
dis.readFully(data);
dis.close();
in.close();
BufferedImage bImage=ImageIO.read(ian);
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
//Client : updownclient.java
import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
Socket soc;
BufferedImage img=null;
soc=new Socket("localhost",4000);
System.out.println("Client is runnimg");
try{
img=ImageIO.read(new File("Image-1-1-1.jpg"));
ImageIO.write(img,"jpg",baos);
baos.flush();
byte[] bytes=baos.toByteArray();
baos.close();
OutputStream out=soc.getOutputStream();
dos.writeInt(bytes.length);
dos.write(bytes,0,bytes.length);
dos.close();
out.close();
catch(Exception e)
soc.close();
soc.close();
Server:
javac updownserver.java
java updownserver.java
Client connected
Image Size:60KB
Client:
javac updownclient.java
java updownclient
Client is running
Downloading:
javac Download.java
java Download
Downloaded image:
RESULT:
Thus, the java program to create a TCP socket for uploading and downloading a page in the
webserver is executed.
EXP.NO:11 REMOTE SCREEN CAPTURE
Aim: To implement a screen capture program between server and client using TCP Socket.
ALGORITHM:
Server:
1.Start.
2.Import net,io,awt,image package.
3.Establish the socket connection for server.
4.Connect the client using accept() function call.
5.Read the length and make it as a limit for array.
6.Get the data from the array
7.Display the image
8.Stop.
Client:
1.Start.
2.Import the necessary package.
3.Establish the connection.
4.Read the image using robot class and objects.
5.Get the capture of image using then robot class object “create screen capture”.
6.Sent the image to the server which is captured.
7.Stop.
SOURCE CODE:
//Server: screenserver.java
import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class screenserver
ServerSocket server=null;
Socket socket;
server=new ServerSocket(4000);
socket=server.accept();
System.out.println("Client connected...");
InputStream in=socket.getInputStream();
int len=dis.readInt();
dis.readFully(data);
dis.close();
in.close();
BufferedImage bImage=ImageIO.read(ian);
ImageIO.write(bImage,"jpg",new File("screencaptured.jpg"));
}
//Client: screenclient.java
import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.Rectangle;
Socket soc;
BufferedImage img=null;
soc=new Socket("localhost",4000);
System.out.println("Client is running...");
try{
String format="jpg";
BufferedImage screenFullImage=robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage,format,new File("screen.jpg"));
System.out.println("Screen Capture...");
img=ImageIO.read(new File("screen.jpg"));
ImageIO.write(img,"jpg",baos);
baos.flush();
byte[] bytes=baos.toByteArray();
baos.close();
dos.writeInt(bytes.length);
dos.write(bytes,0,bytes.length);
dos.close();
out.close();
catch(Exception e){
System.out.println("Exception: "+e.getMessage());
soc.close();
soc.close();
}
SAMPLE INPUT AND SAMPLE OUTPUT:
Server:
javac screenserver.java
java screenserver
Client connected...
Client:
javac screenclient.java
java screenclient
Client is running
Reading image from disk...
Screen Capture...
Sending image to server...
Image sent to server....
RESULT:
Aim: To write a java program to implement a Remote Mouse Control using TCP SOCKET.
ALGORITHM:
Server:
1.Start.
2.Create a mouse panel in order to visualize the mouse move on the screen.
3. Using Server socket , establish the connection between the client and server.
4. Using getInputStream(), get the motion of mouse on the screen.
5.Create a Robot class, get the mouse events.
6. Store the value in integer forms.
7. Stop.
Client:
1.Start.
2.Create the same panel as that of the server side.
3.Connection is established using socket.
4.Using getOutputStream(), give the mouse motion to server side.
5.Convert the string values that is used ,when the mouse is moved on the screen.
6.Stop.
SOURCE CODE:
//Server: Moverserver.java
import java.awt.*;
import java.awt.event.*;
import java.awt.event.InputEvent;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.awt.Robot;
class Moveserver extends JFrame
public Moveserver()
super("server");
mousepanel.setBackground(Color.BLACK);
setLayout(new GridLayout(1,1));
mousepanel.setSize(300,100);
add(mousepanel);
String a,b;
Integer x,y;
boolean flag=true;
try{
System.out.println("Server Listening.........");
Socket s=ss.accept();
System.out.println("Connection Established.....");
m.setSize(300,100);
m.setVisible(true);
while(flag){
a=in.readLine();
b=in.readLine();
x=Integer.valueOf(a);
y=Integer.valueOf(b);
robot.mouseMove(x,y);
m.repaint();
catch(Exception e)
System.out.println("Exception: "+e);
//Client: Moveclient.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class Moveclient extends JFrame implements MouseMotionListener{
static Socket s;
int x,y;
String xs,ys;
public Moveclient()
mousepanel.setBackground(Color.BLACK);
setLayout(new GridLayout(1,1));
mousepanel.setSize(300,100);
add(mousepanel);
mousepanel.addMouseMotionListener(this);
try
s=new Socket("127.0.0.1",8500);
System.out.println("Connection Established");
out=new PrintWriter(s.getOutputStream(),true);
m.setSize(300,100);
m.setVisible(true);
catch(Exception e)
System.out.println("Exception: "+e);
x=event.getX();
y=event.getY();
xs=String.valueOf(x);
ys=String.valueOf(y);
out.println(xs);
out.println(ys);
}
}
SAMPLE INPUT AND SAMPLE OUTPUT:
Server:
javac Moveserver.java
java Moveserver
Server Listening......
Connection Established......
Client:
javac Moveclient.java
java Moveclient
Conncection Established
Server:
RESULT:
Aim: To write a java program to implement a Remote Keyboard Monitoring Control using TCP
Socket.
ALGORITHM:
Server:
1.Start.
2.Specify the port number and create server socket.
3.Accept the client request using accept() method.
4.After binding socket, the server is ready to receive the keyboard press of the client.
5.The server created implements a robot class and create object for keyboard to press the keycode
specified.
6.Close the connection.
7.Stop.
Client:
1.Start.
2.Instantly initiate socket object specifying server’s port number and IP address.
3.Client request the server to establish the connection.
4.Implement a key adapter to the created mouse panel.
5.If the connection is established,the client gets the keypress from the keyboard using keypress()
method.
6.Stop.
SOURCE CODE:
//Server : Mytelserver.java
import java.io.*;
import java.net.*;
public class Mytelserver
String is;
String word;
try
Socket sock=serv.accept();
System.out.println("Server started");
while(!done)
is=in.readLine();
System.out.println(is);
serv.close();
catch(Exception e)
{
System.out.println("Exception;"+e);
}
//Client: keyclient.java
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
Label label;
static Socket s;
TextField txtField;
try
s=new Socket("127.0.0.1",3333);
System.out.println("Connection Established");
catch(Exception e)
{
System.out.println("Exception:"+e);
public keyclient()
label=new Label();
txtField=new TextField(20);
txtField.addKeyListener(new MyKeyListener());
add(label, BorderLayout.NORTH);
panel.add(txtField, BorderLayout.CENTER);
add(panel, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
System.exit(0);
);
setSize(400,400);
setVisible(true);
{
public void keyPressed (KeyEvent ke) {
char i=ke.getKeyChar();
String str=Character.toString(i);
out.println(str);
label.setText(str);}
}
SAMPLE INPUT AND SAMPLE OUTPUT:
Server:
javac Mytelserver.java
java Mytelserver
Server started
Client:
javac keyclient.java
java keyclient
Conncection Established
RESULT:
Thus, the java program to implement remote keyboard monitoring control is executed.
EXP.NO:14 IMPLEMENTATION OF DIJKSTRA’S SHORTEST PATH
ROUTING ALGORITHM
Aim: To write a Java program to implement Dijkstra’s shortest path routing algorithm to find the
shortest path from the given source node to destination node.
ALGORITHM:
The following code implements the Dijkstra Algorithm using the diagram mentioned below:-
SOURCE CODE:
//filename : Dijkstra.java
// A Java program that finds the shortest path using Dijkstra's algorithm.
// The program uses the adjacency matrix for the representation of a graph
// import statements
import java.util.*;
import java.io.*;
import java.lang.*;
// A utility method to compute the vertex with the distance value, which is minimum
// from the group of vertices that has not been included yet
{ m = distance[vx];
m_index = vx;
}
return m_index;
System.out.println("The shortest Distance from source 0th node to all other nodes are: ");
// for a graph that is being represented using the adjacency matrix representation
int distance[] = new int[totalVertex]; // The output array distance[i] holds the shortest dist
ance from source s to j
distance[j] = Integer.MAX_VALUE;
spSet[j] = false;
distance[s] = 0;
// iteration.
// it means it is processed
spSet[ux] = true;
// edge from ux to vx, and the total weight of path from source s to
printSolution(distance, totalVertex);
// main method
// A 9 * 9 matrix is created.
// arr[x][y] = - 1 means, there is no any edge that connects the nodes x and y directly
int grph[][] = new int[][] { { -1, 3, -1, -1, -1, -1, -1, 7, -1 },
{ -1, 4, 1, 3, -1, 5, 5, 6, -1 } };
obj.dijkstra(grph, 0);
javac Dijkstra.java
java Dijkstra
RESULT:
Thus, the java program to implement Dijkstra’s shortest path routing algorithm to find the
shortest path from the given source node to destination node is executed.
.
EXP.NO:15 SECURE KEY DISTRIBUTION
Aim: To write a Java program to implement a Secure key distribution between the client and server.
ALGORITHM:
Server:
1.Start
2.Import net and other necessary package
3.Declare object for socket, server socket and it writer stream to transfer the encrypted string.
4. Initialize string variable is null.
5.Get an integer value form the user as key string from the user
6.Read the string in character integer and read the key value to be displayed in encrypted string.
7.Send the encouraged string and key value client using print stream socket.
8.Convert each character to integer and the value to display it as encrypted string.
9.After sending the string and key, exit the program.
10.Stop.
Client:
1.Start
2.Import net and other necessary packages.
3.Declare object for socket, input stream to receive the string and key from the server.
4.Store the string characteristics to its different variable.
5.Request the user to enter the key for decryption.
6.Compare the key with received key.
7.If the both keys are equal then convert the each character of the string to integer and declare the
key value.
8.Convert the integer value to characteristics and form it into a string and display decrypted string.
9.Print the message as cannot decrypt wrong message and quit.
10.End.
SOURCE CODE:
//Server: SecurityServer.java
import java.io.*;
import java.net.*;
class SecurityServer
try
Socket s=ss.accept();
int i=0,k;
String s2="";
String s1=br.readLine();
k=Integer.parseInt(br.readLine());
while(i<s1.length())
char c1=s1.charAt(i++);
int n=(int)c1+k+1;
c1=(char)n;
s2+=c1;
ps.println(s2);
ps.println(k);
ps.close();
s.close();
ss.close();
catch(Exception e)
System.out.println("\n ERROR:"+e);
}}}
//Client: SecurityClient.java
import java.io.*;
import java.net.*;
class SecurityClient
int i=0,k1;
String s2=br.readLine();
int k=Integer.parseInt(br.readLine());
System.out.println("RECEIVED MSG:"+s2);
k1=Integer.parseInt(br1.readLine());
if(k==k1)
while(i<s2.length())
char c1=s2.charAt(i++);
int n=(int)c1-k1-1;
c1 = (char)n;
s3+=c1;
s.close();
}}}
Server:
javac SecurityServer.java
java SecurityServer
ENTER A STRING:
computer
Client:
javac SecurityClient.java
java SecurityClient
RESULT:
Thus, the java program to implement a Secure key distribution between the client and
server is executed.
EXP.NO:16 ENCRYPT AND DECRYPT USING RSA
Aim: To develop a java program to encrypt and decrypt the data using RSA Algorithm .
ALGORITHM:
1. Start.
2. Import necessary packages like io,util,Random,BigInteger.
3.Declare the variable such as bitlength of each prime number,two distinct large prime numbers p
and q,modules,public exponent E and private exponent D.
4. Inside the constructor, generate two distinct large prime numbers.
5. Generate the private and public key.
6. Read the message to be encrypted and encrypt using RSA encrypt().
7.Decrypt the encrypted message using decrypt() function by modpower() function.
8.Print the decrypted message.
9.Stop.
SOURCE CODE:
//filename : RSA
import java.math.BigInteger;
import java.util.Random;
import java.io.*;
class RSA {
private BigInteger p;
private BigInteger q;
private BigInteger N;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 1024;
private int blocksize = 256;
//blocksize in byte
private Random r;
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);
}
public RSA(BigInteger e, BigInteger d, BigInteger N) {
this.e = e;
this.d = d;
this.N = N;
}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);
//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();
}
}
SAMPLE INPUT AND SAMPLE OUTPUT:
javac RSA.java
java RSA
RESULT:
Thus, the java program to encrypt and decrypt the data using RSA Algorithm is executed.
..........................................