You are on page 1of 131

IT219 – COMPUTER NETWORKS LABORATORY MANUAL

TABLE OF CONTENTS
EXP.NO DATE EXPERIMENT NAME PAGE NO

1 INTRODUCTION TO NETWORK
PROGRAMMING BASICS

2 PROGRAMS USING TCP SOCKETS:


a. ECHO SERVER (Static and Dynamic Input)
b. ECHO CLIENT AND SERVER
c. CONCURRENT SERVER

3 PROGRAMS USING TCP SOCKETS:


a. FILE TRANSFER
b. DATE AND TIME SERVER
c. STRING OPERATION

4 PROGRAMS USING UDP SOCKETS:


a. CLIENT – SERVER CHAT
b. DOMAIN NAME SYSTEM SERVER
5 PROGRAMS USING RAW SOCKETS:
a. PING
b. TRACE ROUTE

6 IMPLEMENTATION OF:

a. ADDRESS RESOLUTION PROTOCOL


b. REVERSE ADDRESS RESOLUTION
PROTOCOL

7 IMPLEMENTATION OF SLIDING WINDOW


PROTOCOL:

a. STOP AND WAIT PROTOCOL


b. GO BACK ‘N’ PROTOCOL
c. SELECTIVE REPEAT ARQ PROTOCOL
8 REMOTE COMMAND EXECUTION USING
SOCKETS

9 REMOTE COMMAND INVOCATION TO FIND


FACTORIAL OF A NUMBER

10 UPLOAD AND DOWNLOAD A PAGE IN A


WEBSERVER USING SOCKET

11 REMOTE SCREEN CAPTURE

12 REMOTE MOUSE CONTROL

13 REMOTE KEYBOARD CONTROL

14 IMPLEMENTATION OF DIJIKSTRA’S
SHORTEST PATH ROUTING ALGORITHM

15 SECURE KEY DISTRIBUTION

16 ENCRYPT AND DECRYPT USING RSA


ALGORITHM
EXP .NO : 1 INTRODUCTION TO NETWORK PROGRAMMING BASICS

1. NETWORKING BASICS

Computer networking is the engineering discipline concerned with communication between


computer systems or devices. It is the practice of linking computing devices together with hardware
and software that supports data communications across these devices.

KEY CONCEPTS AND TERMS

Packet A message or data unit that is transmitted between communicating processes.

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.

Channel: Communication path created by establishing a connection between endpoints.

Network A group of two or more computer systems linked together

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

server to perform some operations.


Network Address: Network addresses give computers unique identities they can use to
communicate with each other. Specifically, IP addresses and MAC addresses are used on most home
and business networks.

Protocols: A Protocol is a convention or standard rules that enables and controls the connection,

communication and data transfer between two computing endpoints.

Port: An interface on a computer to which you can connect a device. It is a "logical connection

place" and specifically, using the Internet's protocol, TCP/IP.

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

Well-known ports 1-1023

Ephemeral ports 1024-5000

User-defined ports 5001-65535

Connection: It defines the communication link between two processes.

Association: Association is used for 5 tuple that completely specifies the two processes that

make up a connection.

{ Protocol, local-address, local-process, foreign-address, foreign- process}

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.

We also define Half association as either

{ protocol, local-address, local process} or { protocol, local-address, local process}

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.

Socket functions for elementary TCP client/server in Connection-oriented Scenario

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

point of a two-way communication channel.

Sockets Overview: In the operating system, sockets have the following characteristics:

A socket exists only as long as a process holds a descriptor referring to it.

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.

ELEMENTARY SOCKET SYSTEM CALLS

Socket() System Call: Creates an end point for communication and returns a descriptor.

Syntax

#include <sys/socket.h>
#include <sys/types.h>

int socket ( int AddressFamily, int Type, int Protocol);

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:

AF_UNIX: Denotes the Unix internal protocols

AF_INET: Denotes the Internet protocols.

AF_NS: Denotes the XEROX Network Systems protocol.

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.

IPROTO_TCP TCP Transport protocol

IPROTO_UDP UDP Transport protocol

IPROTO_SCTP SCTP Transport protocol

Return Values Upon successful completion, the socket subroutine returns an integer (the socket

descriptor). It returns -1 on error.

Bind( ) System call: Binds a name to a socket.


Description: The bind subroutine assigns a Name parameter to an unnamed socket. It assigns a

local protocol address to a socket.

Syntax

#include <sys/socket.h>

int bind (int sockfd, struct sockaddr *myaddr, int addrlen);

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.

There are 3 uses of bind:

a) Server registers their well-known address with a system. Both connection-oriented and

connection-less servers need to do this before accepting client requests.

b) A Client can register a specific address for itself.

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,

it returns a value of -1 to the calling program.

The connect() function is used by a TCP client to establish a connection with a TCP server.

#include <sys/socket.h>

int connect(int sockfd, struct sockaddr *servaddr, int addrlen);

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.

Otherwise, it returns a value of -1 to the calling program.

listen() System call

This system call is used by a connection-oriented server to indicate that it is willing to receive

connections.

#include <sys/socket.h>

int listen (int sockfd, int backlog);

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.

Return values: Returns 0 if OK, -1 on error

accept() System call: The actual connection from some client process is waited for by having

the server execute the accept system call.

#include <sys/socket.h>

int accept (int sockfd, struct sockaddr *cliaddr, int *addrlen);

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

connected peer process (the client). addrlen is called a value-result argument.

Send( ),sendto( ),recv( ) and recvfrom( ) system calls:

These system calls are similar to the standard read and write functions, but one additional

argument is required.

#include <sys/socket.h>

int send(int sockfd, char *buff, int nbytes, int flags);

int sendto(int sockfd, char void *buff, int nbytes, int flags, struct sockaddr *to, int

addrlen);

int recv(int sockfd, char *buff, int nbytes, int flags);

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.

Close( ) system call:

The normal Unix close function is also used to close a socket and terminate a TCP connection.

#include <unistd.h>

int close (int sockfd);


EXP .NO : 2 PROGRAMS USING TCP SOCKETS

2(a). IMPLEMENTATION OF TCP/IP ECHO SERVER (STATIC AND DYNAMIC


INPUT)
AIM:

To implement the echo client server using TCP/IP sockets.

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 :

Include appropriate header files.

Create a TCP Socket ().

Fill in the socket address structure (with server information)

Specify the port where the service will be defined to be used by client.

Bind the address and port using bind() system call.

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.

Receive a message from the Client using recv() system call.

Write the result thus obtained on the standard output.

Repeat steps 7-8 until „bye‟ or „null‟ is read.

Close all streams.

Close the server socket.

Stop.

Client:

Include appropriate header files.

Create a TCP Socket.

Fill in the socket address structure (with server information)

Specify the port of the Server, where it is providing service


Establish connection to the Server using connect() system call.

Get input from user using write()

If equal to bye or null, then go to step 10.

For echo server, send a message to the server to be echoed using send() system call.

Repeat steps 6-8.

Close the input and output streams.

Close the client socket.

Stop.

FLOW-CHART :

SOURCE CODE:

( Static Input )

//Server :

import java.io.*;

import java.net.*;
public class ServerFileName

public static void main(String[] args)

try

ServerSocket ss=new ServerSocket(6666);

Socket s=ss.accept(); //establishes connection

DataInputStream dis=new DataInputStream(s.getInputStream());

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.*;

public class ClientFileName

public static void main(String[] args)

try

Socket s=new Socket("localhost",6666);

DataOutputStream dout=new DataOutputStream(s.getOutputStream());


dout.writeUTF("Hello Server");

dout.flush();

dout.close();

s.close();

catch(Exception e)

System.out.println(e);

( Dynamic Input )

//Server :

import java.io.*;

import java.net.*;

public class ServerFileName

public static void main(String[] args)

try

ServerSocket ss=new ServerSocket(6666);

Socket s=ss.accept(); //establishes connection

DataInputStream dis=new DataInputStream(s.getInputStream());

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.*;

public class ClientFileName

public static void main(String[] args)

try

Socket s=new Socket("localhost",6666);

DataInputStream din=new DataInputStream(s.getInputStream());

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

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

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

message= Hello Server

(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 :

Include appropriate header files.

Create a TCP Socket ().

Fill in the socket address structure (with server information)

Specify the port where the service will be defined to be used by client.

Bind the address and port using bind() system call.

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.

Receive a message from the Client using recv() system call.

Write the result thus obtained on the standard output.

Repeat steps 7-8 until „bye‟ or „null‟ is read.

Send the message to the client using send() system call.

Close all streams.

Close the server socket.

Stop.

Client:

Include appropriate header files.

Create a TCP Socket.

Fill in the socket address structure (with server information)

Specify the port of the Server, where it is providing service

Establish connection to the Server using connect() system call.


Get input from user using write()

If equal to bye or null, then go to step 10.

For echo server, send a message to the server to be echoed using send() s1ystem call.

Repeat steps 6-8.

10. Receive the message from the servert using recv() system call and display it.

11.Close the input and output streams.

12.Close the client socket.

13. Stop.

FLOW-CHART

SOURCE CODE:

//Server

import java.net.*;

import java.io.*;

class ServerFileName
{

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

ServerSocket ss=new ServerSocket(3333);

Socket s=ss.accept();

DataInputStream din=new DataInputStream(s.getInputStream());

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

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

String str="",str2="";

while(!str.equals("stop"))

str=din.readUTF();

System.out.println("client says: "+str);

str2=br.readLine();

dout.writeUTF(str2);

dout.flush();

din.close();

s.close();

ss.close();

//Client :

import java.net.*;

import java.io.*;

class ClientFileName

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

Socket s=new Socket("localhost",3333);


DataInputStream din=new DataInputStream(s.getInputStream());

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

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

String str="",str2="";

while(!str.equals("stop"))

str=br.readLine();

dout.writeUTF(str);

dout.flush();

str2=din.readUTF();

System.out.println("Server says: "+str2);

dout.close();

s.close();

}
SAMPLE INPUT AND SAMPLE OUPUT :

Client :

javac ClientFileName.java

java ClientFileName

hi

Server says: hello

tested

Server says: done

Server:

javac ServerFileName.java

java ServerFileName

Client says: hi

hello

Client says: tested


done

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:

Include appropriate header files.

Create a TCP Socket.

Fill in the socket address structure (with server information)

Specify the port where the service will be defined to be used by client.

Bind the address and port using bind() system call.

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.

Receive a message from the Client using recv() system call.

Send the result of the request made by the client using send() system call.

Client:
Include appropriate header files.

Create a TCP Socket.

Fill in the socket address structure (with server information)

Specify the port of the Server, where it is providing service

Establish connection to the Server using connect() system call.

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.

Write the result thus obtained on the standard output.

SOURCE CODE:

//Server :

import java.io.*;

import java.net.*;

class ServerFileName

public static void main(String[] args)

ServerSocket server = null;

try

// server is listening on port 1234

server = new ServerSocket(1234);

server.setReuseAddress(true);

// running infinite loop for getting client request

while (true)

// socket object to receive incoming client requests

Socket client = server.accept();

// Displaying that new client is connected to server

System.out.println("New client connected"+ client.getInetAddress() .getHostAddress());

// create a new thread object


ClientHandler clientSock = new ClientHandler(client);

// This thread will handle the client separately

new Thread(clientSock).start();

catch (IOException e)

e.printStackTrace();

finally

if (server != null)

try

server.close();

catch (IOException e)

e.printStackTrace();

// ClientHandler class

private static class ClientHandler implements Runnable

private final Socket clientSocket;

// Constructor

public ClientHandler(Socket socket)


{

this.clientSocket = socket;

public void run()

PrintWriter out = null;

BufferedReader in = null;

try

// get the outputstream of client

out = new PrintWriter(

clientSocket.getOutputStream(), true);

// get the inputstream of client

in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

String line;

while ((line = in.readLine()) != null)

// writing the received message from client

System.out.printf(" Sent from the client: %s\n",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

public static void main(String[] args)

{
// establish a connection by providing host and port number

try (Socket socket = new Socket("localhost", 1234))

// writing to server

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// reading from server

BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));

// object of scanner class

Scanner sc = new Scanner(System.in);

String line = null;

while (!"exit".equalsIgnoreCase(line))

// reading from user

line = sc.nextLine();

// sending the user input to server

out.println(line);

out.flush();

// displaying server reply

System.out.println("Server replied "+ in.readLine());

// closing the scanner object

sc.close();

catch (IOException e)

e.printStackTrace();

}
//Client 2 :

import java.io.*;

import java.net.*;

import java.util.*;

// Client class

class Client2FileName

// driver code

public static void main(String[] args)

// establish a connection by providing host and port number

try (Socket socket = new Socket("localhost", 1234))

// writing to server

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// reading from server

BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));

// object of scanner class

Scanner sc = new Scanner(System.in);

String line = null;

while (!"exit".equalsIgnoreCase(line))

// reading from user

line = sc.nextLine();

// sending the user input to server

out.println(line);

out.flush();

// displaying server reply

System.out.println("Server replied "+ in.readLine());


}

// closing the scanner object

sc.close();

catch (IOException e)

e.printStackTrace();

//Client 3 :

import java.io.*;

import java.net.*;

import java.util.*;

// Client class

class Client3FileName

// driver code

public static void main(String[] args)

// establish a connection by providing host and port number

try (Socket socket = new Socket("localhost", 1234))

// writing to server

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// reading from server

BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));

// object of scanner class

Scanner sc = new Scanner(System.in);


String line = null;

while (!"exit".equalsIgnoreCase(line))

// reading from user

line = sc.nextLine();

// sending the user input to server

out.println(line);

out.flush();

// displaying server reply

System.out.println("Server replied "+ in.readLine());

// closing the scanner object

sc.close();

catch (IOException e)

e.printStackTrace();

SAMPLE INPUT AND SAMPLE OUPUT :

Client 1:

javac Client1FileName.java

java Client1FileName

This is Client-1

Server replied This is Client-1


Client 2:

javac Client2FileName.java

java Client2FileName

This is Client-2

Server replied This is Client-2

Client 3:

javac Client3FileName.java

java Client3FileName

This is Client-3

Server replied This is Client-3

PROGRAM EXECUTED!!!!

Server replied PROGRAM EXECUTED!!!!

Server:

javac ServerFileName.java

java ServerFileName

New client connected127.0.0.1

Sent from the client: This is Client-1

New client connected127.0.0.1

Sent from the client: This is Client-2

New client connected127.0.0.1

Sent from the client: This is Client-3

Sent from the client: PROGRAM EXECUTED!!!!

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

3(a). FILE TRANSFER 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:

1. Create a socket using socket( ) system call..

2. Bind server’s address and port using bind( ) system call.

3. Convert the socket into a listening socket using listen( ) sytem call.

4. Wait for client connection to complete using accept( ) system call.

5. Receive the Client request using recv() system call which consist of the name of

the command that is to be executed along with data parameters(if any)

6. The command is interpreted and executed.

7. On successful execution the result is passed back to the client by the server

Client Process:

1. Create a socket.

2. Fill in the internet socket address structure (with server information).

3. Connect to server using connect system call.

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 standard output.

6. Close the socket connection.

SOURCE CODE:

//Server :

import java.io.*;

import java.net.*;
public class ServerFileName{

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

ServerSocket s = new ServerSocket(1263);

Socket sr=s.accept();

FileInputStream fr = new FileInputStream("E:\\TextFile.txt");

byte []b=new byte[2000];

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.*;

public class ClientFileName{

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

byte []b=new byte[2000];

Socket s1=new Socket("localhost",1263);

InputStream is=s1.getInputStream();

FileOutputStream fr=new FileOutputStream("E:\\CONTENT.txt");

is.read(b, 0, b.length);

fr.write(b, 0, b.length);

File f=new File("E:\\sharmi.txt");

BufferedReader br=new BufferedReader(new FileReader(f));

String st;
while((st=br.readLine()) != null)

System.out.println(st);

s1.close();

fr.close();

SAMPLE INPUT AND SAMPLE OUPUT :

Client :

javac ClientFileName.java

java ClientFileName

COMPUTER NETWORKING LABORATORY

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

1. Create a server socket and bind it to port.

2. Listen for new connection and when a connection arrives, accept it.

3. Send server’s date and time to the client.

4. Read client’s IP address sent by the client.

5. Display the client details.

6. Repeat steps 2-5 until the server is terminated.

7. Close all streams.

8. Close the server socket.

9. Stop

Client

1. Create a client socket and connect it to the server’s port number.

2. Retrieve its own IP address using built-in function.

3. Send its address to the server.

4. Display the date & time sent by the server.

5. Close the input and output streams.

6. Close the client socket.

7. Stop.

SOURCE CODE:

//TCP Date Server--tcpdateserver.java

import java.net.*;
import java.io.*;

import java.util.*;

class tcpdateserver

public static void main(String arg[])

ServerSocket ss = null;

Socket cs;

PrintStream ps;

BufferedReader dis;

String inet;

try

ss = new ServerSocket(4444);

System.out.println("Press Ctrl+C to quit");

while(true)

cs = ss.accept();

ps = new PrintStream(cs.getOutputStream());

Date d = new Date();

ps.println(d);

dis = new BufferedReader(new InputStreamReader(cs.getInputStream()));

inet = dis.readLine();

System.out.println("Client System/IP address is :"+ inet);

ps.close();

dis.close();

catch(IOException e)

{
System.out.println("The exception is :" + e);

// TCP Date Client--tcpdateclient.java

import java.net.*;

import java.io.*;

class tcpdateclient

public static void main (String args[])

Socket soc;

BufferedReader dis;

String sdate;

PrintStream ps;

try

InetAddress ia = InetAddress.getLocalHost();

if (args.length == 0)

soc = new Socket(InetAddress.getLocalHost(),4444);

else

soc = new Socket(InetAddress.getByName(args[0]),4444);

dis = new BufferedReader(new InputStreamReader(soc.getInputStream()));

sdate=dis.readLine();

System.out.println("The date/time on server is : " +sdate);

ps = new PrintStream(soc.getOutputStream());

ps.println(ia);

ps.close();

catch(IOException e)
{

System.out.println("THE EXCEPTION is :" + e);

SAMPLE INPUT AND SAMPLE OUTPUT:

Server:

$ javac tcpdateserver.java

$ java tcpdateserver

Press Ctrl+C to quit

Client System/IP address is : localhost.localdomain/127.0.0.1

Client System/IP address is : localhost.localdomain/127.0.0.1

Client:

$ javac tcpdateclient.java

$ java tcpdateclient

The date/time on server is: Wed Jul 06 07:12:03 GMT 2011

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:

1. Create a socket using socket( ) system call..

2. Bind server’s address and port using bind( ) system call.

3. Convert the socket into a listening socket using listen( ) sytem call.

4. Wait for client connection to complete using accept( ) system call.

5. Receive the Client request using recv() system call which consist of the name of

the command that is to be executed along with data parameters(if any)

6. The command is interpreted and executed.

7. On successful execution the result is passed back to the client by the server

Client Process:

1.Create a socket.

2.Fill in the internet socket address structure (with server information).

3.Connect to server using connect system call.

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 standard output.

6.Close the socket connection.

SOURCE CODE:

//Server:

import java.net.*;

import java.io.*;

public class ReverseServer{

public static void main(String arg[]) throws Exception{

ServerSocket server = new ServerSocket(1234);

System.out.println("Server is Waiting");
while(true){

Socket con = server.accept();

DataInputStream in = new DataInputStream(con.getInputStream());

DataOutputStream out = new DataOutputStream(con.getOutputStream());

StringBuilder inp = new StringBuilder(in.readUTF().toString());

StringBuilder op=inp.reverse();

out.writeUTF(op.toString());

//Client:

import java.net.*;

import java.io.*;

import java.util.Scanner;

public class ReverseClient{

public static void main(String arg[]) throws Exception{

InetAddress ia = InetAddress.getLocalHost();

Socket cSock = new Socket(ia,1234);

DataInputStream in = new DataInputStream(cSock.getInputStream());

DataOutputStream out = new DataOutputStream(cSock.getOutputStream());

System.out.println("Please Enter String");

Scanner sc = new Scanner(System.in);

String inp = sc.nextLine();

out.writeUTF(inp);

System.out.println("Response from server");

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

Please Enter String

cnlab

Response from server

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

4(a). CLIENT-SERVER CHAT USING UDP SOCKETS


AIM:
To implement a chat server and client in java using UDP sockets.
DESCRIPTION:
UDP is a connectionless protocol and the socket is created for client and server to transfer the data.
Socket connection is achieved using the port number.

Socket functions for elementary UDP client/server in Connection-less Scenario

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:

// UDP Chat Server -- UDPChatServer.java

import java.io.*;

import java.net.*;

class UDPChatServer

public static int clientport = 8040,serverport = 8050;

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

DatagramSocket SrvSoc = new DatagramSocket(clientport);

byte[] SData = new byte[1024];

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

System.out.println("Server Ready");

while (true)

byte[] RData = new byte[1024];

DatagramPacket RPack = new DatagramPacket(RData,RData.length);

SrvSoc.receive(RPack);

String Text = new String(RPack.getData());

if (Text.trim().length() == 0)

break;

System.out.println("\nFrom Client <<< " + Text );

System.out.print("Msg to Client : " );

String srvmsg = br.readLine();

InetAddress IPAddr = RPack.getAddress();


SData = srvmsg.getBytes();

DatagramPacket SPack = new DatagramPacket(SData,SData.length,IPAddr,


serverport);

SrvSoc.send(SPack);

System.out.println("\nClient Quits\n");

SrvSoc.close();

// UDP Chat Client -- UDPChatClient .java

import java.io.*;

import java.net.*;

class UDPChatClient

public static int clientport = 8040,serverport = 8050;

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

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


DatagramSocket

CliSoc = new DatagramSocket(serverport);

InetAddress IPAddr;

String Text;

if (args.length == 0)

IPAddr = InetAddress.getLocalHost();

else

IPAddr = InetAddress.getByName(args[0]);

byte[] SData = new byte[1024];

System.out.println("Press Enter without text to quit");

while (true)
{

System.out.print("\nEnter text for server : ");

Text = br.readLine();

SData = Text.getBytes();

DatagramPacket SPack = new DatagramPacket(SData,SData.length, IPAddr,


clientport );

CliSoc.send(SPack);

if (Text.trim().length() == 0)

break;

byte[] RData = new byte[1024];

DatagramPacket RPack = new DatagramPacket(RData,RData.length);

CliSoc.receive(RPack);

String Echo = new String(RPack.getData()) ;

Echo = Echo.trim();

System.out.println("From Server <<< " + Echo);

CliSoc.close();

SAMPLE INPUT AND SAMPLE OUTPUT :

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:

// UDP DNS Server -- UDPDomainServer.java

import java.io.*;

import java.net.*;

public class UDPDomainServer

private static int indexOf(String[] array, String str) { str = str.trim();

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

{
if (array[i].equals(str))

return i;

return -1;

public static void main(String arg[])throws IOException

String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"};

String[] ip = {"68.180.206.184", "209.85.148.19","80.168.92.140", "69.63.189.16"};

System.out.println("Press Ctrl + C to Quit");

while (true)

DatagramSocket serversocket=new DatagramSocket(1362);

byte[] senddata = new byte[1021];

byte[] receivedata = new byte[1021];

DatagramPacket recvpack = new DatagramPacket(receivedata, receivedata.length);

serversocket.receive(recvpack);

String sen = new String(recvpack.getData());

InetAddress ipaddress = recvpack.getAddress();

int port = recvpack.getPort();

String capsent;

System.out.println("Request for host " + sen);

if(indexOf (hosts, sen) != -1)

capsent = ip[indexOf (hosts, sen)];

else

capsent = "Host Not Found";

senddata = capsent.getBytes();

DatagramPacket pack = new DatagramPacket(senddata, senddata.length,ipaddress,port);

serversocket.send(pack);

serversocket.close();
}

//UDP DNS Client -- UDPDomainClient.java

import java.io.*;

import java.net.*;

public class UDPDomainClient

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

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


DatagramSocket

clientsocket = new DatagramSocket();

InetAddress ipaddress;

if (args.length == 0)

ipaddress = InetAddress.getLocalHost();

else

ipaddress = InetAddress.getByName(args[0]);

byte[] senddata = new byte[1024];

byte[] receivedata = new byte[1024];

int portaddr = 1362;

System.out.print("Enter the hostname : ");

String sentence = br.readLine();

senddata = sentence.getBytes();

DatagramPacket pack = new DatagramPacket(senddata,senddata.length,


ipaddress,portaddr);

clientsocket.send(pack);

DatagramPacket recvpack =new DatagramPacket(receivedata,receivedata.length);

clientsocket.receive(recvpack);

String modified = new String(recvpack.getData());

System.out.println("IP Address: " + modified);


clientsocket.close();

SAMPLE INPUT AND SAMPLE OUTPUT :


Server
$ javac udpdnsserver.java
$ java udpdnsserver
Press Ctrl + C to Quit
Request for host yahoo.com
Request for host cricinfo.com
Request for host youtube.com
Client
$ javac udpdnsclient.java
$ java udpdnsclient
Enter the hostname : yahoo.com
IP Address: 68.180.206.184
$ java udpdnsclient
Enter the hostname : cricinfo.com
IP Address: 80.168.92.140
$ java udpdnsclient
Enter the hostname : youtube.com
IP Address: Host Not Found

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

5(a). IMPLEMENTATION OF PING PROGRAM USING RAW SOCKETS


AIM:
To write a java program to implement a ping using raw sockets.

ALGORITHM:

1.Start the program.

2.Include necessary package in Java.

3.To create a process object p to implement the ping command.

4.Declare one (1)BufferedReader stream class object.

5.Get the details of the server.

(i) Length of the IP address.

(ii) Time required to get the details.

(iii) Send packets , receive packets and lost packets.

(iv) Minimum ,maximum and arrange times.

6.Print the results.

7.Stop the program.

SOURCE CODE:

//PingWebsite

// sub-process

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.ArrayList;

public class PingWebsite

// method for finding the ping statics of website

static void commands(ArrayList<String> commandList)

throws Exception

{
// creating the sub process, execute system command

ProcessBuilder build = new ProcessBuilder(commandList);

Process process = build.start();

// to read the output

BufferedReader input = new BufferedReader(new


InputStreamReader(process.getInputStream()));

BufferedReader Error = new BufferedReader(new


InputStreamReader(process.getErrorStream()));

String s = null;

System.out.println("Standard output: ");

while((s = input.readLine()) != null)

System.out.println(s);

System.out.println("error (if any): ");

while((s = Error.readLine()) != null)

System.out.println(s);

// Driver method

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

// creating list for commands

ArrayList<String> commandList = new ArrayList<String>();

commandList.add("ping");

// can be replaced by IP

commandList.add("www.google.com");
PingWebsite.commands(commandList);

SAMPLE INPUT AND SAMPLE OUTPUT :

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:

1.Start the program.

2.Include necessary package in Java.

3.To create a process object p to implement the traceroute command.

4.Declare one (1)BufferedReader stream class object.

5.Get the details of the route to reach specific destination address .

(i) Details of the intermediate nodes such as IP address that lies between source to
destination.

(ii) Number of hops to reach destination.

(iii) Time taken for reachiing the each and every intermediate nodes .

(iv) Minimum ,maximum and arrange times.

6.Print the results.

7.Stop the program.

SOURCE CODE:

//Traceroute

import java.io.*;

import java.net.*;

import java.lang.*;

class Traceroute

public static void main(String args[])

BufferedReader in;

try{

Runtime r=Runtime.getRuntime();
Process p=r.exec("tracert www.google.com");

in=new BufferedReader(new InputStreamReader(p.getInputStream()));

String line;

if(p==null)

System.out.println("could not connect");

while((line=in.readLine())!=null)

System.out.println(line);

catch(IOException e)

System.out.println(e.toString());

SAMPLE INPUT AND SAMPLE OUTPUT :

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

6 (a). ADDRESS RESOLUTION PROTOCOL (ARP) USING TCP SOCKETS


Aim: To write a java program for simulating ARP protocols using TCP sockets.

ALGORITHM:

Client:

1. Start the program

2. Using socket connection is established between client and server.

3. Get the IP address to be converted into MAC address.

4. Send this IP address to server.

5. Server returns the MAC address to client.

Server:

1. Start the program

2. Accept the socket which is created by the client.

3. Server maintains the table in which IP and corresponding MAC addresses are stored.

4. Read the IP address which is send by the client.

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

public static void main(String args[])

try

{
ServerSocket obj=new ServerSocket(138);

Socket obj1=obj.accept();

while(true)

DataInputStream din=new DataInputStream(obj1.getInputStream());

DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());

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

public static void main(String args[])

try

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

Socket clsct=new Socket("127.0.0.1",138);

DataInputStream din=new DataInputStream(clsct.getInputStream());

DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());

System.out.println("Enter the Logical address(IP):");

String str1=in.readLine();

dout.writeBytes(str1+'\n');

String str=din.readLine();

System.out.println("The Physical Address is: "+str);

clsct.close();

catch (Exception e)

System.out.println(e);

SAMPLE INPUT AND SAMPLE OUTPUT:

Server:

javac Serverarp.java

java Serverarp

Client:

javac Clientarp.java

java Clientarp
Enter the Logical address(IP):

165.165.80.80

The Physical Address is: 6A:08:AA:C2

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:

1.Start the program.

2. Using datagram sockets UDP function is established.

3.Get the MAC address to be converted into IP address.

4.Send this MAC address to server.

5.Server returns the IP address to client.

Server:

1. Start the program.

2. Server maintains the table in which IP and corresponding MAC addresses are stored.

3. Read the MAC address which is send by the client.

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

public static void main(String args[])

try

DatagramSocket server=new DatagramSocket(1309);

while(true)

{
byte[] sendbyte=new byte[1024];

byte[] receivebyte=new byte[1024];

DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);

server.receive(receiver);

String str=new String(receiver.getData());

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();

DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);

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

public static void main(String args[])

try

DatagramSocket client=new DatagramSocket();

InetAddress addr=InetAddress.getByName("127.0.0.1");

byte[] sendbyte=new byte[1024];

byte[] receivebyte=new byte[1024];

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

System.out.println("Enter the Physical address (MAC):");

String str=in.readLine();

sendbyte=str.getBytes();

DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309);

client.send(sender);

DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);

client.receive(receiver);

String s=new String(receiver.getData());

System.out.println("The Logical Address is(IP): "+s.trim());

client.close();

catch(Exception e)

System.out.println(e);

}
}

SAMPLE INPUT AND SAMPLE OUTPUT:

Server:

javac Serverrarp.java

java Serverrarp

Client:

javac Clientrarp.java

java Clientrarp

Enter The Physical Address(MAC):

6A:08:AA:C2

The Logical Address is(IP): 165.165.80.80

RESULT:

Thus, the java program for simulating RARP protocols using UDP socket is executed.
EXP .NO : 7 IMPLEMENTATION OF SLIDING WINDOW PROTOCOL

7 (a). STOP AND WAIT PROTOCOL


Aim: To write a java program to implement the Stop and Wait Sliding Window protocol .

ALGORITHM :

Sender:

1. Sequence of code is started.

2. Accept new packet and assign sequence to it.

3. Send packet sequence with the sequence number.

4. Set timer for recently sent packets.

5. If error free acknowledgement from receiver is recieved and next frame expected→sequence
comes, then sequence's next frame is expected.

6. If time out then it goes to the step 3.

7. Stop.

Receiver:

1. Start.

2. Next frame expected.

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.*;

public class Sender

Socket sender;

ObjectOutputStream out;

ObjectInputStream in;

String packet,ack,str, msg;


int n,i=0,sequence=0;

Sender(){}

public void run()

try{

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

System.out.println("Waiting for Connection....");

sender = new Socket("localhost",2005);

sequence=0;

out=new ObjectOutputStream(sender.getOutputStream());

out.flush();

in=new ObjectInputStream(sender.getInputStream());

str=(String)in.readObject();

System.out.println("reciver > "+str);

System.out.println("Enter the data to send....");

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();

System.out.println("waiting for ack.....\n\n");

if(ack.equals(String.valueOf(sequence)))

i++;

System.out.println("receiver > "+" packet recieved\n\n");

else

System.out.println("Time out resending data....\n\n");

sequence=(sequence==0)?1:0;

}catch(Exception e){}

}while(i<n+1);

System.out.println("All data sent. exiting.");

}catch(Exception e){}

finally{

try{

in.close();

out.close();

sender.close();

catch(Exception e){}

}
public static void main(String args[])

Sender s=new Sender();

s.run();

//Client : Receiver.java

import java.io.*;

import java.net.*;

public class Receiver

ServerSocket reciever;

Socket connection=null;

ObjectOutputStream out;

ObjectInputStream in;

String packet,ack,data="";

int i=0,sequence=0;

Receiver(){}

public void run()

try{

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

reciever = new ServerSocket(2005,10);

System.out.println("waiting for connection...");

connection=reciever.accept();

sequence=0;

System.out.println("Connection established :");

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

System.out.println("\n\nreceiver >"+packet +" duplicate


data");

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){}

public static void main(String args[]){

Receiver s=new Receiver();

while(true){

s.run();

SAMPLE INPUT AND SAMPLE OUTPUT:

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

Aim: To develop a program in Java to implement Go Back ‘N‘ algorithm.

Problem definition:

The Program sends the frames from the Client to the Server with checking for missing frames via
sending an acknowledgement.

Algorithm:

Server:

1.Start the program with appropriate header file.

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.

4.Otherwise, receive acknowledge n then, send base*n+1.

5.If send_base : next seqn then stop time or else start.

6.If time out then start timer again send packets send base, and base+1... send packet next seqn-1.

7.Repeat step 3 to 6 until ACR Complete.

8.Stop the return.

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.

3.Otherwise, send ACR next days –Lj

4.Repeat step 2 and step 3 until all the ACR complete.

5. Stop the receiver /client program.

SOURCE CODE:
//Server:ARQ_Server.java

import java.net.*;

import java.io.*;

import java.util.*;

public class ARQ_Server

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

ServerSocket server=new ServerSocket(6262);

System.out.println("Server established.");

Socket client=server.accept();

ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());

ObjectInputStream ois=new ObjectInputStream(client.getInputStream());

System.out.println("Client is now connected.");

int x=(Integer)ois.readObject();

int k=(Integer)ois.readObject();

int j=0;

int i=(Integer)ois.readObject();

boolean flag=true;

Random r=new Random(6);

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)

System.out.println("Frame "+k+" recieved"+"\n"+"Data:"+j);

j++;

System.out.println();

else

System.out.println("Frames recieved not in correct order"+"\n"+"


Expected frame:" + j +"\n"+ " Recieved frame no :"+ k);

System.out.println();

if(j%mod==0 && flag)

{
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();

System.out.println("Client finished sending data. Exiting");

oos.writeObject(-1);

//Client:ARQ_Client.java
import java.util.*;

import java.net.*;

import java.io.*;

public class ARQ_Client

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

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

System.out.print("Enter the value of m : ");

int m=Integer.parseInt(br.readLine());

int x=(int)((Math.pow(2,m))-1);

System.out.print("Enter no. of frames to be sent:");

int count=Integer.parseInt(br.readLine());

int data[]=new int[count];

int h=0;

for(int i=0;i<count;i++)

System.out.print("Enter data for frame no " +h+ " => ");

data[i]=Integer.parseInt(br.readLine());

h=(h+1)%x;

Socket client=new Socket("localhost",6262);


ObjectInputStream ois=new ObjectInputStream(client.getInputStream());

ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());

System.out.println("Connected with server.");

boolean flag=false;

GoBackNListener listener=new GoBackNListener(ois,x);

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("No reply from server in 3.5 seconds. Resending data


from frame no " + (listener.reply+1));

System.out.println();

strt=listener.reply+1;

flag=false;

else

System.out.println("All elements sent successfully. Exiting");

flag=true;

}while(!flag);
oos.writeObject(-1);

class GoBackNListener implements Runnable

Thread t;

ObjectInputStream ois;

int reply,x;

GoBackNListener(ObjectInputStream o,int i)

t=new Thread(this);

ois=o;

reply=-2;

x=i;

@Override

public void run()

try

int temp=0;

while(reply!=-1)
{

reply=(Integer)ois.readObject();

if(reply!=-1 && reply!=temp+1)

reply=temp;

if(reply!=-1)

temp=reply;

System.out.println("Acknowledgement of frame no " + (reply%x) + "


recieved.");

System.out.println();

reply=temp;

catch(Exception e)

System.out.println("Exception => " + e);

SAMPLE INPUT AND SAMPLE OUTPUT:

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

Enter the value of m : 7


Enter no. of frames to be sent:5
Enter data for frame no 0 => 1
Enter data for frame no 1 => 2
Enter data for frame no 2 => 3
Enter data for frame no 3 => 4
Enter data for frame no 4 => 5
Connected with server.
|0||1||2||3||4|

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.

3.Accept the window size from the client (should be <=40).

4.Accept the packets from the network layer.

5.Calculate the total frames/windows required.

6.Send the details to the client (total packets/total frames).

7.Initialize the transmit buffer.

8.Built the frame/window depending on the window size.

9.Tansmit the frame.

10.Wait for the acknowledgement frame.

11.Wait for the acknowledgement of each packet and repeat the process for the packet for which
the negative acknowledgement is received.

12. Or else continue as usual.

13. Increment the frame count and repeat steps to 13 until all packets are transmitted.

14. Close the connection.

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;

public class RepeatARQserver


{

static ServerSocket Serversocket;

static DataInputStream dis;

static DataOutputStream dos;

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

try

int a[] = { 30, 40, 50, 60, 70, 80, 90, 100 };

Serversocket = new ServerSocket(8011);

System.out.println("waiting for connection");

Socket client = Serversocket.accept();

dis = new DataInputStream(client.getInputStream());

dos = new DataOutputStream(client.getOutputStream());

System.out.println("The number of packets sent is:" + a.length);

int y = a.length;

dos.write(y);

dos.flush();

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

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.*;

public class RepeatARQclient {


static Socket connection;

public static void main(String a[]) throws SocketException {

try {

int v[] = new int[10];

int n = 0;

Random rands = new Random();

int rand = 0;

InetAddress addr = InetAddress.getByName("Localhost");

System.out.println(addr);

connection = new Socket(addr, 8011);

DataOutputStream out = new DataOutputStream(

connection.getOutputStream());

DataInputStream in = new DataInputStream(

connection.getInputStream());

int p = in.read();

System.out.println("No of frame is:" + p);

for (int i = 0; i < p; i++) {

v[i] = in.read();

System.out.println(v[i]);

//g[i] = v[i];

rand = rands.nextInt(p);//FRAME NO. IS RANDOMLY GENERATED

v[rand] = -1;

for (int i = 0; i < p; i++)

System.out.println("Received frame is: " + v[i]);


}

for (int i = 0; i < p; i++)

if (v[i] == -1) {

System.out.println("Request to retransmit from packet no "

+ (i+1) + " again!!");

n = i;

out.write(n);

out.flush();

System.out.println();

v[n] = in.read();

System.out.println("Received frame is: " + v[n]);

System.out.println("quiting");

} catch (Exception e) {

System.out.println(e);

SAMPLE INPUT AND SAMPLE OUTPUT:

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:

Remote Command Execution is when a process on a host causes a program to be executed on


another host. Usually the invoking process wants to pass data to the remote program,capture its
output also.

Problem Description:

The problem can be implemented using sockets General implementation steps are as follows.

ALGORITHM :

Server:

1. Create a socket using socket () system call.

2. Bind server's address and port using bind () system call.

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).

6. The command is interpreted and executed.

7. On successful execution the result is passed back to the client by the server.

Client:

1. Create a socket.

2. File in the Internet socket address structure (with server information).

3. Connect to the server using connect system call.

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.

6. Close the socket connection.

SOURCE CODE:

//Server: RemoteServer.java

import java.io.*;

import java.net.*;
class RemoteServer

public static void main(String args[])

try

int Port;

BufferedReader Buf =new BufferedReader(new

InputStreamReader(System.in));

System.out.print(" Enter the Port Address : " );

Port=Integer.parseInt(Buf.readLine());

ServerSocket ss=new ServerSocket(Port);

System.out.println(" Server is Ready To Receive a Command. ");

System.out.println(" Waiting ..... ");

Socket s=ss.accept();

if(s.isConnected()==true)

System.out.println(" Client Socket is Connected Succecfully. ");

InputStream in=s.getInputStream();

OutputStream ou=s.getOutputStream();

BufferedReader buf=new BufferedReader(new

InputStreamReader(in));

String cmd=buf.readLine();

PrintWriter pr=new PrintWriter(ou);

pr.println(cmd);

Runtime H=Runtime.getRuntime();

Process P=H.exec(cmd);

System.out.println(" The " + cmd + " Command is Executed Successfully. ");

pr.flush();

pr.close();

ou.close();
in.close();

catch(Exception e)

System.out.println(" Error : " + e.getMessage());

//Client: RemoteClient.java

import java.io.*;

import java.net.*;

class RemoteClient

public static void main(String args[])

try

int Port;

BufferedReader Buf =new BufferedReader(new

InputStreamReader(System.in));

System.out.print(" Enter the Port Address : " );

Port=Integer.parseInt(Buf.readLine());

Socket s=new Socket("localhost",Port);

if(s.isConnected()==true)

System.out.println(" Server Socket is Connected Succecfully. ");

InputStream in=s.getInputStream();

OutputStream ou=s.getOutputStream();

BufferedReader buf=new BufferedReader(new

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

InputStreamReader(in));

PrintWriter pr=new PrintWriter(ou);

System.out.print(" Enter the Command to be Executed : " );

pr.println(buf.readLine());

pr.flush();

String str=buf1.readLine();

System.out.println(" " + str + " Opened Successfully. ");

System.out.println(" The " + str + " Command is Executed Successfully. ");

pr.close();

ou.close();

in.close();

catch(Exception e)

System.out.println(" Error : " + e.getMessage());

SAMPLE INPUT AND SAMPLE OUTPUT:

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.

3. Perform Java compilation on all the files.

4. Perform the RMI compilation for the implementation file to create sub and skeleton by using rmic
command.

5. Start the RMI registry.

6. Display the result.

7.Stop.

SOURCE CODE:

//Server : rmiserver.java

import java.net.*;

import java.rmi.*;

public class rmiserver

public static void main(String args[])

try

serverimpl m=new serverimpl();

Naming.rebind("rmi://localhost:5000/abc",m);

catch(Exception e)

System.out.println("Exception"+e);

}
}

//Client : rmiclient.java

import java.io.*;

import java.rmi.*;

public class rmiclient

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

try

serverint f=(serverint)Naming.lookup("rmi://localhost:5000/abc");

DataInputStream m=new DataInputStream(System.in);

System.out.println("Enter the number\n");

int n1=Integer.parseInt(m.readLine());

System.out.println("The factorial number is "+f.fact(n1));

catch(Exception e)

System.out.println(e);

//Implementation code: serverimpl.java

import java.rmi.*;

import java.rmi.server.*;

public class serverimpl extends UnicastRemoteObject implements serverint

public serverimpl()throws Exception{

}
public int fact(int n)

int i,c=1;

for(i=1;i<=n;i++)

c=i*c;

return c;

//Interface code: serverint.java

import java.rmi.*;

public interface serverint extends Remote

int fact(int n)throws Exception;

SAMPLE INPUT AND SAMPLE OUTPUT:

Server:

javac serverint. java

javac serverimpl.java

start rmiregistry 5000

java rmiserver

Client:

javac rmiclient.java

java rmiclient

Enter the number

The factorial number is 720


RMI Registry:

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

2. Import necessary packages like io,net awt and swing.

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.

3. Create a client socket using IP address and port number.

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.

9. Close the connection of input stream and output stream class.


10.Stop.

SOURCE CODE:

//Downloading code: Download.java

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.URL;

public class Download {

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

try{

String fileName = "Image-1-1-1.jpg";

String website =

"https://images.financialexpress.com/2021/07/"+fileName;

System.out.println("Downloading File From: " + website);

URL url = new URL(website);

InputStream inputStream = url.openStream();

OutputStream outputStream = new FileOutputStream(fileName);

byte[] buffer = new byte[2048];

int length = 0;

while ((length = inputStream.read(buffer)) != -1) {

System.out.println("Buffer Read of length: " + length);

outputStream.write(buffer, 0, length);

inputStream.close();

outputStream.close();

}catch(Exception e){

System.out.println("Exception: " + e.getMessage());

}
}

//Uploading Code:

//Server: updownserver.java

import java.net.*;

import java.io.*;

import java.awt.image.*;

import javax.imageio.*;

import javax.swing.*;

class updownserver{

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

ServerSocket server=null;

Socket socket;

server=new ServerSocket(4000);

System.out.println("Server waiting for image");

socket=server.accept();

System.out.println("Client connected. ");

InputStream in=socket.getInputStream();

DataInputStream dis=new DataInputStream(in);

int len=dis.readInt();

System.out.println("Image Size:"+ len/1024 +"KB");

byte[] data=new byte[len];

dis.readFully(data);

dis.close();

in.close();

InputStream ian = new ByteArrayInputStream(data);

BufferedImage bImage=ImageIO.read(ian);

JFrame f= new JFrame("Server");

ImageIcon icon=new ImageIcon(bImage);


JLabel l=new JLabel();

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;

public class updownclient{

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

Socket soc;

BufferedImage img=null;

soc=new Socket("localhost",4000);

System.out.println("Client is runnimg");

try{

System.out.println("Reading image from disk.");

img=ImageIO.read(new File("Image-1-1-1.jpg"));

ByteArrayOutputStream baos=new ByteArrayOutputStream();

ImageIO.write(img,"jpg",baos);
baos.flush();

byte[] bytes=baos.toByteArray();

baos.close();

System.out.println("Sending image to server.");

OutputStream out=soc.getOutputStream();

DataOutputStream dos=new DataOutputStream(out);

dos.writeInt(bytes.length);

dos.write(bytes,0,bytes.length);

System.out.println("Image sent to server. ");

dos.close();

out.close();

catch(Exception e)

System.out.println("Exception : " +e.getMessage());

soc.close();

soc.close();

SAMPLE INPUT AND SAMPLE OUTPUT:

Server:

javac updownserver.java

java updownserver.java

Server waiting for image

Client connected

Image Size:60KB
Client:

javac updownclient.java

java updownclient

Client is running

Reading image from disk.

Sending image to server.

Image sent to server.

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

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

ServerSocket server=null;

Socket socket;

server=new ServerSocket(4000);

System.out.println("Server Waiting for image");

socket=server.accept();

System.out.println("Client connected...");

InputStream in=socket.getInputStream();

DataInputStream dis=new DataInputStream(in);

int len=dis.readInt();

byte[] data=new byte[len];

dis.readFully(data);

dis.close();

in.close();

InputStream ian=new ByteArrayInputStream(data);

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;

public class screenclient{

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

Socket soc;

BufferedImage img=null;

soc=new Socket("localhost",4000);

System.out.println("Client is running...");

try{

System.out.println("Reading image from disk...");

Robot robot=new Robot();

String format="jpg";

Rectangle screenRect=new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());

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"));

ByteArrayOutputStream baos=new ByteArrayOutputStream();

ImageIO.write(img,"jpg",baos);

baos.flush();

byte[] bytes=baos.toByteArray();

baos.close();

System.out.println("Sending image to server...");

OutputStream out = soc.getOutputStream();

DataOutputStream dos=new DataOutputStream(out);

dos.writeInt(bytes.length);

dos.write(bytes,0,bytes.length);

System.out.println("Image sent to server....");

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

Server waiting for image

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....

Captured Image of Screen:

RESULT:

Thus, the java program to implement remote screen capture is executed.


EXP.NO:12 REMOTE MOUSE CONTROL

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

JPanel mousepanel=new JPanel();

public Moveserver()

super("server");

mousepanel.setBackground(Color.BLACK);

setLayout(new GridLayout(1,1));

mousepanel.setSize(300,100);

add(mousepanel);

public static void main(String arg[])

String a,b;

Integer x,y;

boolean flag=true;

try{

ServerSocket ss=new ServerSocket(8500);

System.out.println("Server Listening.........");

Socket s=ss.accept();

System.out.println("Connection Established.....");

BufferedReader in =new BufferedReader(new InputStreamReader(s.getInputStream()));

Moveserver m=new Moveserver();


m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

m.setSize(300,100);

m.setVisible(true);

Robot robot=new Robot();

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{

JPanel mousepanel=new JPanel();

static Socket s;

static PrintWriter out;

int x,y;

String xs,ys;

public Moveclient()

super("Move the mouse over it");

mousepanel.setBackground(Color.BLACK);

setLayout(new GridLayout(1,1));

mousepanel.setSize(300,100);

add(mousepanel);

mousepanel.addMouseMotionListener(this);

public static void main(String args[])

try

s=new Socket("127.0.0.1",8500);

System.out.println("Connection Established");

out=new PrintWriter(s.getOutputStream(),true);

Moveclient m=new Moveclient();


m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

m.setSize(300,100);

m.setVisible(true);

catch(Exception e)

System.out.println("Exception: "+e);

public void mouseMoved(MouseEvent event)

x=event.getX();

y=event.getY();

xs=String.valueOf(x);

ys=String.valueOf(y);

out.println(xs);

out.println(ys);

public void mouseDragged(MouseEvent event)

}
}
SAMPLE INPUT AND SAMPLE OUTPUT:

Server:

javac Moveserver.java

java Moveserver

Server Listening......

Connection Established......

Client:

javac Moveclient.java
java Moveclient
Conncection Established

Move the Mouse over it screen:

Server:

RESULT:

Thus, the java program to implement remote mouse control is executed.


EXP.NO:13 REMOTE KEYBOARD CONTROL

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

public static void main(String arg[])

String is;

String word;

boolean done = false;

try

ServerSocket serv=new ServerSocket(3333);

Socket sock=serv.accept();

System.out.println("Server started");

BufferedReader in=new BufferedReader(new InputStreamReader(sock.getInputStream()));

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

PrintWriter out=new PrintWriter(sock.getOutputStream(),true);

System.out.println("hai the program 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.*;

public class keyclient extends Frame

Label label;

static Socket s;

static PrintWriter out;

TextField txtField;

public static void main(String[] args)

try

s=new Socket("127.0.0.1",3333);

System.out.println("Connection Established");

out =new PrintWriter(s.getOutputStream(), true);

keyclient k =new keyclient();

catch(Exception e)

{
System.out.println("Exception:"+e);

public keyclient()

super(" Key Press Event Frame");

Panel panel=new Panel();

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() {

public void windowClosing(WindowEvent we)

System.exit(0);

);

setSize(400,400);

setVisible(true);

public class MyKeyListener extends KeyAdapter

{
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

hai the program started

Client:

javac keyclient.java
java keyclient
Conncection Established

Key Press Event Frame:

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:

Step 1: All nodes should be marked as unvisited.


Step 2: All the nodes must be initialized with the "infinite" (a big number) distance. The starting node
must be initialized with zero.
Step 3: Mark starting node as the current node.
Step 4: From the current node, analyze all of its neighbors that are not visited yet, and compute their
distances by adding the weight of the edge, which establishes the connection between the current
node and neighbor node to the current distance of the current node.
Step 5: Now, compare the recently computed distance with the distance allotted to the neighboring
node, and treat it as the current distance of the neighboring node,
Step 6: After that, the surrounding neighbors of the current node, which has not been visited, are
considered, and the current nodes are marked as visited.
Step 7: When the ending node is marked as visited, then the algorithm has done its job; otherwise,
Step 8: Pick the unvisited node which has been allotted the minimum distance and treat it as the new
current node.
Step 9: After that, start again from step4.

Implementation of Dijkstra 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.*;

public class Dijkstra

// 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

static final int totalVertex = 9;

int minimumDistance(int distance[], Boolean spSet[])

// Initialize min value

int m = Integer.MAX_VALUE, m_index = -1;

for (int vx = 0; vx < totalVertex; vx++)

if (spSet[vx] == false && distance[vx] <= m)

{ m = distance[vx];

m_index = vx;

}
return m_index;

// A utility method to display the built distance array

void printSolution(int distance[], int n)

System.out.println("The shortest Distance from source 0th node to all other nodes are: ");

for (int j = 0; j < n; j++)

System.out.println("To " + j + " the shortest distance is: " + distance[j]);

// method that does the implementation of Dijkstra's shortest path algorithm

// for a graph that is being represented using the adjacency matrix representation

void dijkstra(int graph[][], int s)

int distance[] = new int[totalVertex]; // The output array distance[i] holds the shortest dist
ance from source s to j

// spSet[j] will be true if vertex j is included in the shortest

// path tree or the shortest distance from the source s to j is finalized

Boolean spSet[] = new Boolean[totalVertex];

// Initializing all of the distances as INFINITE

// and spSet[] as false

for (int j = 0; j < totalVertex; j++)

distance[j] = Integer.MAX_VALUE;
spSet[j] = false;

// Distance from the source vertex to itself is always 0

distance[s] = 0;

// compute the shortest path for all the given vertices

for (int cnt = 0; cnt < totalVertex - 1; cnt++)

// choose the minimum distance vertex from the set of vertices

// not yet processed. ux is always equal to source s in the first

// iteration.

int ux = minimumDistance(distance, spSet);

// the choosed vertex is marked as true

// it means it is processed

spSet[ux] = true;

// Updating the distance value of the neighboring vertices

// of the choosed vertex.

for (int vx = 0; vx < totalVertex; vx++)

// Update distance[vx] if and only if it is not in the spSet, there is an

// edge from ux to vx, and the total weight of path from source s to

// vx through ux is lesser than the current value of distance[vx]

if (!spSet[vx] && graph[ux][vx] != -1 && distance[ux] != Integer.MAX_VALUE && distance[ux]


+ graph[ux][vx] < distance[vx])
{

distance[vx] = distance[ux] + graph[ux][vx];

// display the build distance array

printSolution(distance, totalVertex);

// main method

public static void main(String argvs[])

// 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 },

{ 3, -1, 7, -1, -1, -1, -1, 10, 4 },

{ -1, 7, -1, 6, -1, 2, -1, -1, 1 },

{ -1, -1, 6, -1, 8, 13, -1, -1, 3 },

{ -1, -1, -1, 8, -1, 9, -1, -1, -1 },

{ -1, -1, 2, 13, 9, -1, 4, -1, 5 },

{ -1, -1, -1, -1, -1, 4, -1, 2, 5 },

{ 7, 10, -1, -1, -1, -1, 2, -1, 6 },

{ -1, 4, 1, 3, -1, 5, 5, 6, -1 } };

// creating an object of the class Dijkstra


Dijkstra obj = new Dijkstra();

obj.dijkstra(grph, 0);

SAMPLE INPUT AND SAMPLE OUTPUT:

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

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

try

ServerSocket ss=new ServerSocket(9000);

Socket s=ss.accept();

PrintStream ps=new PrintStream(s.getOutputStream());

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

int i=0,k;

String s2="";

System.out.println("\n ENTER A STRING:");

String s1=br.readLine();

System.out.print(" \n ENTER THE KEY:");

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;

System.out.println("ENCRYPTED STRING IS:"+s2);

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

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

Socket s=new Socket("LocalHost",9000);

BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));

int i=0,k1;

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

String s3=" ";

String s2=br.readLine();

int k=Integer.parseInt(br.readLine());

System.out.println("RECEIVED MSG:"+s2);

System.out.println ("\n ENTER THE KEY:");

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;

System.out.println("DECRYPTED STRING IS:"+s3);

s.close();

}}}

SAMPLE INPUT AND SAMPLE OUTPUT:

Server:

javac SecurityServer.java

java SecurityServer

ENTER A STRING:

computer

ENTER THE KEY:2

ENCRYPTED STRING IS: frpswhu

Client:

javac SecurityClient.java

java SecurityClient

RECEIVED MSG: frpsxwhu

ENTER THE KEY:

DECRYPTED STRING IS : computer

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);

System.out.println("Decrypted String in Bytes: " + bytesToString(decrypted));


System.out.println("Decrypted String: " + new String(decrypted));
}
private static String bytesToString(byte[] encrypted){
String test = "";
for (byte b : encrypted) {
test+= Byte.toString(b);
}
return test;}

//Encrypt message
public byte[] encrypt(byte[] message) {
return (new BigInteger(message)).modPow(e,N).toByteArray();
}
// Decrypt message
public byte[] decrypt(byte[] message) {
return (new BigInteger(message)).modPow(d,N).toByteArray();
}
}
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.

..........................................

You might also like