0% found this document useful (0 votes)
2 views64 pages

Networking Lab

The document outlines a Networking Lab that includes various topics such as identifying well-known ports, one-to-one and many-to-many chatting applications, and data retrieval from a remote database. It provides detailed descriptions of Java programs for implementing chat applications and managing socket connections, as well as a brief overview of remote database operations. Each section includes problem descriptions, program structures, and code examples for practical implementation.

Uploaded by

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

Networking Lab

The document outlines a Networking Lab that includes various topics such as identifying well-known ports, one-to-one and many-to-many chatting applications, and data retrieval from a remote database. It provides detailed descriptions of Java programs for implementing chat applications and managing socket connections, as well as a brief overview of remote database operations. Each section includes problem descriptions, program structures, and code examples for practical implementation.

Uploaded by

rahulspidy906
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Networking Lab

INDEX

CONTENTS PAGE NO

 Identifying well know ports 2-4


 One – one chatting 5-10
 Many to many chatting 11-17
 Data Retrieval from Database 18-23
 FTP without protocol 24-28
 TFTP 29-34
 Telnet 35-43
 HTTP 44-51
 POP & SMTP 52-56

1
[Link] IDENTIFY WELL KNOWN PORTS

Problem Description:

By trying to listen to the various well known ports


by opening client connections. If the exception
does not occur then the remote port is active else
the remote port is inactive.

Each application program has a unique port


number that distinguishes it from other programs
running at the same time one the same machine. The
client is assigned a random port number called the
ephemeral port number. The server program is
assigned a universal port number called a well known
port number. The port numbers are divided into 3
ranges:

Well known Ports:


The ports ranging from to 1023 are assigned
and controlled by IANA.

Registered Ports:
The ports ranging from 1-24 to 49151 are
not assigned or controlled by IANA. They can only be
registered with IANA to prevent duplication.

Dynamic Ports:
The ports ranging from 49152 to 65535 are
neither controlled nor registered. They can be used by
any process. These are ethereal ports.

Remote system:
Any other computer in the network with
which the local computer can communicate.

2
Program:

/* This program will identify the ports which are active also
shows host name and address of active ports
Filename : [Link]
variables :i
Methods :
getLocalHost(),getHostName(),getHostAddress()
Classes used : InetAddress ,port1
Objects used : se,e,host,haddr,s,h
Ports : 1 to 1024
Loops used : for
Exception handlers : throws,try..catch */

import [Link].*; // java networking package


import [Link].*; // java input output package

class ports // class name : ports


{
public static void main(String []args) throws
Exception //main throws any exception
{
/* InetAddress is a class in [Link] package public final
class InetAddress extends Object implements
Serializable getHostAddress() , getHostName() returns
a string i.e, host name and host address
getLocalHost() : is static method returns InetAddress */

InetAddress h=[Link]();// h has


localhost id
String host = [Link](); // host contains host
name
String haddr=[Link](); // haddr contains
host address
[Link]("\n Host Name : : "+host);

3
[Link]("\n Host Address :: "+haddr);

for(int i=0;i<1024;i++) // repeating for 0 to 1024 ports


{
Socket s=null; // socket object assigned as null
try
{
/* Socket class is designed to connect to the server
Socket(String
hostname,int port) throws unknownHostException
or IOException */

s=new Socket((host),i); // type casting i to host type


[Link]("Port "+ i +" Active"); // prints
active port
} // try close
catch(SocketException se)
{
// object se holds any socket exception
} // catch close
catch(Exception e) // e holds any type of exception
{
[Link]("ERROR.....");
} // catch close
} // for close
} // end main
} // end class

Output Screen:

4
2. PROGRAMS FOR CHAT APPLICATION

Problem Description:

i). One-One: By opening socket connection and


displaying what is written by one party to the
other.
ii). Many-Many (Broad cast): Each client opens a
socket connection to the chat server and writes to
the socket. Whatever is written by one party can
be seen by all other parties.

Client:
A program that initiates communication with
another program called a server.

Server:

5
A program that can provide services to other
programs called clients.

Socket:
A socket is a software endpoint that establishes
bi-directional communication between a server
program and one or more client programs. The socket
associates the server program with a specific hardware
port on the machine where it runs so that any program
anywhere in the network with a socket associated with
that same port can communicate with the server
program.
In one-one chat one party can communicate with
another party and exchange information.
In many- many chat each client opens a socket
connection to the chat server and writes to the socket.
This is seen by all other parties connected to the
server.

2a. ONE TO ONE CHAT APPLICATION

/* SERVER SIDE PROGRAM */


/*
This program is used to perform one to one [Link]
needs two java programs i.e. ., server program and client
program.
The server program accepts connection with client to
perform chatting, it also reads the data at server side and
sends that data to client using output stream, accepts the
data from client using input stream

6
Filename : [Link]
variables : --
Methods : readLine() , accept() ,getInputStream(),
getOutputStream, print(), println() ,outputStreamWriter(),
flush()
Socket classes used : BufferedReader , InputStreamReader
PrintWriter(), Socket() ,ServerSocket () , chats
Objects used : s,ss,in ,br,e,msg,pw
Ports : clientport , serverport
Loops used : while
Exception handlers :try..catch */

import [Link].*; // i/o package


import [Link].*; // java networking package
import [Link].*; // java lang package

/*class extending to [Link] class */

public class chats extends Thread


{
public static void main(String args[])
{
try
{
/* ServerSocket is used to create servers that listen
for local or remote clients ServerSocket(int port) :
takes port number to accept connection with the
client */

ServerSocket ss= new ServerSocket (111);


[Link]("server ready"); // prints
serverready

/* Socket accept (): used to establish a full connection


between client and server */

Socket s=[Link]();

7
/* [Link] is an object which is wrapped up in to
inputStreamReader , this converts bytes to
characters. To obtain a character based stream it is
attached to BufferedReader in : reads the data from
keyboard and br reads from socket object */

BufferedReader in=new BufferedReader( new


InputStreamReader([Link]));
BufferedReader br = new BufferedReader( new
InputStreamReader([Link]()));

/* getInputStream() is a method of socket class that


reads clients data and getOutputStream() is used to
send the data to client .PrintWriter is an outputstream
that contains print() and println() methods */

PrintWriter pw=new PrintWriter(new


OutputStreamWriter([Link]()));
while(true) // infinte loop
{
String msg=[Link](); // reads the client
message
[Link]("from client:"+msg);
if([Link]("quit"))
{
[Link]("disabled");
break; // if quit break the loop
} // end if
[Link]("server ");
msg=[Link](); // reads data from server
[Link](msg); // passess message in to the
stream
[Link](); // flushes print writer
} // end while
} // end try
catch(IOException e) // holds the exception in object e
{
[Link](" error");
} // end catch

8
} // end main
} // end class

/* CLIENT SIDE PROGRAM */

/* This a client program to run with [Link], It reads


client data and sends to server and accepts server data to
print . on the screen

Filename : [Link]
variables : --
Methods : readLine() , getInputStream(),
getOutputStream ,print(), println() ,outputStreamWriter(),
flush()
Socket classes used : BufferedReader , InputStreamReader
PrintWriter(), Socket() , chats
Objects used : in,pw,msg,from,br,e
Ports : clientport , serverport
Loops used : while
Exception handlers : try..catch */

import [Link].*;// io package


import [Link].*; // java networking package
import [Link].*; // java lang package

public class chatc // chatc class


{
public static void main(String args[])
{
try
{
// in : reads from keyboard
BufferedReader in=new BufferedReader( new
InputStreamReader([Link]));
// creating Socket object
Socket s= new Socket("localhost",111); // connects to
localhost
// br to read server data

9
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]()));
// pw : to write the client data into output stream
PrintWriter pw=new
PrintWriter([Link]());
while(true) // infinite loop
{
[Link]("client");
String msg=[Link](); // reads client data from
key boards
[Link](msg); // sends msg through output
stream
[Link](); // flushes print writer
String from = [Link]();// reads server data
from stream
[Link]("from server="+from);
if([Link]("quit")) // if quit
{
[Link]("Disconnect");
[Link](0);
} // end if
} // end while
} // end try

catch(IOException e) // holding io exception in the


object e
{
[Link]("ending");
} // end catch
} // end main
} // end class

10
Output screen:

11
2b. MANY TO MANY CHATTING

/* SERVER SIDE PROGRAM */

/* this program performs multi chatting: many servers can


chat with many clients. It is server program uses array of
sockets to connect.
Filename : [Link]
variables : i,total,n,k
Methods : readLine() , getInputStream(),
getOutputStream ,print(), println() ,outputStreamWriter(),
flush() , Socket(),reqhandler(),run()
classes used BufferedReader , InputStreamReader
PrintWriter(), Socket() , mserver,reqhandler
Objects used : s[],user[],ss,br,msg,req,t,e,s,pw
Ports : clientport , serverport
Loops used : while ,for,
Condition structures : if
Exception handlers : try..catch */

import [Link].*; // importing java io package


import [Link].*; // importing network package

public class mserver // class mserver


{// creating array of sockets, strings of static type
public static Socket s[]=new Socket[10];
public static String user[]=new String[10];
public static int total;
public static void main(String a[ ])
{
int i=0;
try
{
ServerSocket ss=new ServerSocket(118); // creating
server socket
while(true) // infinite loop
{
s[i]=[Link](); // accepting connection for all
sockets

12
BufferedReader br=new BufferedReader(new
InputStreamReader(s[i].getInputStream()));
String msg=[Link](); // reads client data
user[i]=msg;
[Link](msg+" connected");
try
{
reqhandler req=new reqhandler(s[i],i);
total=i;
i++;
Thread t=new Thread(req); // thread object
[Link]();
}// end inner try
catch(Except ion e)
{
[Link](e);
} // end catch
}// end while
} // end outer try
catch(Exception e)
{
[Link](e);
} // end outer catch
} // end main
} // end catch

class reqhandler implements Runnable // thread class


{
public int n;
public Socket s;
public reqhandler(Socket soc,int i) // constructor
{
s=soc; // initializing socket object
n=i;
}
public void run() // overriding run() method in Runnable
interface
{

13
String msg=" ";
BufferedReader br;
PrintWriter pw;
try
{
while(true)
{
br=new BufferedReader(new
InputStreamReader([Link]()));
msg=[Link]();
if([Link]("quit"))
[Link]--;
else
[Link]([Link][n]+"->"+msg);
if([Link]==-1)
{ // if -1 server gets disconnected
[Link]("server Disconnected..");
[Link](0);
} // end if
for(int k=0;k<=[Link];k++)
{
if(![Link][k].equals([Link][n])&&(!
[Link]("quit")))
{
pw=new PrintWriter(new
OutputStreamWriter(mserver.s[k].getOutputStr
eam()));
[Link]([Link][n]+":"+msg+"\n);
[Link]();
} // end if
} // end for
} // end while
} //end try
catch(Exception e) // holding exception object
{ } // end catch
} // end method run
} // end class req handler

14
/* CLIENT SIDE PROGRAM */

/* client program to run with [Link] , it connects to


the localhost with port no 118 and sends message to server
to which it is connected
Filename : [Link]
variables : --
Methods : readLine() , getInputStream(),
getOutputStream ,print(), println() ,outputStreamWriter(),
flush() , Socket(),run() ,readdata()
classes used BufferedReader , InputStreamReader
PrintWriter(), Socket() , mclient
Objects used : in,s,msg,t,rd
Ports : clientport , serverport
Loops used : while
Condition structures : if
Exception handlers : try..catch */

import [Link].*; // io package


import [Link].*; // java net package
public class mclient
{
public static void main(String a[])
{
BufferedReader in; // BufferedReader object - in
PrintWriter pw; // Printwriter object - pw
try
{
Socket s=new Socket("localhost",118);

15
[Link]("Enter name:");
in =new BufferedReader(new
InputStreamReader([Link]));
String msg=[Link](); // reading string
pw=new PrintWriter(new
OutputStreamWriter([Link]()));
[Link](msg+"\n");
[Link](); // flush the stream
while(true)
{
readdata rd=new readdata(s); // invoking readdata()
Thread t=new Thread(rd); // creating thread
[Link]();
msg=[Link]();
if([Link]("quit"))
{
[Link](0);
} // end if
[Link](msg); // sending message to the stream
[Link]();
} // end while
} // end try
catch(Exception e)
{
[Link](e);
} // end catch
} // end main
} // end class

class readdata implements Runnable


{
public Socket s;
public readdata(Socket s) // constructor for readdata
{
this.s=s;
} // end read data
public void run()
{
BufferedReader br;

16
try
{
while(true)
{
br= new BufferedReader(new
InputStreamReader([Link]()));
String msg=[Link]();
[Link](msg);
} // end while
} // end try
catch(Exception e)
{
[Link](e);
} // end catch
} // end run method
} // end class

17
Output Screen:

18
[Link] RETRIEVAL FROM REMOTE
DATABASE

19
Problem Description:

At the remote database a server listens for client


connections. This server accepts SQL queries
from the client, executes it on the database and
sends the response to the client.

Remote database:
A database to which a connection is made using a
database link which is connected to a local database.
Remote database access is a protocol
standard for database access. It describes the
connection of a database client to a database server. It
includes features for:
o communicating database operations and
parameters from the client to the server.
o in return transporting result data from the server
to the client.
o Database transaction management.

A remote database client is an application process


within an open system that requests database
services from another application process called a
database server.
A database server is an application process within
the same or another open system that supplies
database storage facilities and provides through OSI
communication, database services to remote
database clients.
A client requests services from database, the
remote database at the server accepts the request,
executes the command and sends the response to
the client.

20
/* SERVER SIDE PROGRAM */

/* server program that sends database requested by the


client.
Program name : [Link]
Packages used : [Link].*,[Link].*,[Link].*;
Objects used : con,rs,s,rm,ss,soc,br,pw,qry
Methods : getInputStream(),
getOutputStream ,print(), println() ,outputStreamWriter(),
flush() , accept(), ServerSocket(), readLine()
Classes used : DBServer
Interfaces
:Connection ,ResultSet,ResultSetMetaData,Statement
Conditional structures : if
Loops used : while, for
Exceptions used : try catch , throws */

import [Link].*; // java sql package


import [Link].*; // java network package
import [Link].*; // java io package
class dbserver // dbserver class
{
public static void main(String args[]) throws Exception
{
Connection con; // Connection interface
ResultSet rs; //Result Set interface
Statement s;
ResultSetMetaData rm=null; //Setting the
ResultsetMetaData to Null
ServerSocket ss; // server socket object
Socket soc;
BufferedReader br;
PrintWriter pw;
// Used to Load a jdbc driver

21
[Link]("[Link]");
// Obtain database connection , remotedb is data source
name registered at 32 // bit odbc , scott and tiger are
username ,password to log in to sql
con =
[Link]("jdbc:odbc:remotedb","sco
tt","tiger");
// used to create statement to run sql query
s = [Link]();
ss = new ServerSocket(8504);
while(true)
{
try
{
soc = [Link]();
[Link]("Connected........");
pw = new PrintWriter([Link]());
br = new BufferedReader(new
InputStreamReader([Link]()));
String qry = [Link]();
rs = [Link](qry); // executes the query and
stores the records in rs
if(rs!=null)
rm = [Link]();
int cnt = [Link](); // returns [Link]
columns in the database
for(int i=1;i<=cnt;i++)
[Link]([Link](i)+" | "); // sending
columns names in output stream
[Link]("\n");
[Link](); // flushes stream
int ct=0;
while([Link]()) // repeats till end of the record
{
for(int i=1;i<=cnt;i++)
[Link]([Link](i)+" | ");
[Link]("\n"); //Printing Line By Line
[Link]();// flushes stream
++ct;

22
} //while rs()
[Link]("\n\n" +ct+" Row(s) Selected");
[Link]();
[Link]("end#");
[Link]();
[Link](); //Closing the PrintWrite
[Link](); //Closing the br
[Link](); //Closing the socket
[Link]("Service Complete...");
} // end try
catch(Exception e)
{ } // end catch
}//while
}//main
}//class

23
/* CLIENT SIDE PROGRAM */

/* client program for [Link]

This program connects to dbserver and request the data


base from the server in the form of sql query .To connect to
the server it asks to enter server id and then query
Program name : [Link]
Packages used : [Link].*,[Link].*,[Link].*;
Objects used : con,rs,s,rm,ss,soc,br,pw,qry
Methods : getInputStream(),
getOutputStream ,print(), println() ,outputStreamWriter(),
flush() , accept(), ServerSocket(), readLine()
Classes used : DBServer
Interfaces
:Connection ,ResultSet,ResultSetMetaData,Statement
Conditional structures : if
Loops used : while, for
Exceptions used : try catch , throws */

import [Link].*;
import [Link].*;
import [Link].*;

class dbclient
{
public static void main(String args[]) throws Exception
{
Socket soc;
BufferedReader br,keyin;
PrintWriter pw;
String name,data;
keyin = new BufferedReader(new
InputStreamReader([Link]));
// host id reading
[Link]("Enter Remote Server ID: ");
name = [Link]();
[Link]("Enter U R Query");
while(true)

24
{
[Link]("Sql>");
String sql=[Link](); // input query like select
* from emp
if([Link]("quit"))
break;
soc = new
Socket([Link](name),8504);
pw = new PrintWriter([Link]());
br = new BufferedReader(new
InputStreamReader([Link]()));
[Link](sql);
[Link]();
while(true)
{
data=[Link]();
if ([Link]("end#"))
break;
[Link](data);
}
}//outer while
}//main
}//class

25
Output Screen:

26
27
4. FTP CLIENT SERVER PROGRAM

Problem Description:

By opening socket connection to our server on


one system and sending a file from one system to
another.

File transfer protocol is the standard mechanism


provided by TCP/IP for copying a file from one host to
another. FTP establishes two connections between the
hosts. One connections is used for data transfer; the
other for control information (commands& responses).
Separation of commands & data transfer makes FTP
more efficient.
Control connection uses may simple rules of
communication. We need to transfer only a line of
command or a line of response at a time. The data
connection needs more complex rules due to the
various data types transferred. FTP uses two well-
known TCP ports. Port 21 is used for the control
connection and well known port 20 for the data
connection.
There are 3 types of file transfer:
1. a file is copied from the server to the client.
2. a file is copied from the client to the server.
3. a list of directories of filenames is sent from the
server to the client.

28
/* SERVER SIDE PROGRAM */

/* This program is ftpserver which creates a url connection


to copy a file from remote location , it takes the source and
target file path from the client.
Program name : [Link]
Packages used : [Link].*,[Link].*
Objects used : ps,s,ss,st,temp,u,dil
Metho ds : DataInputStream(), getInputStream(),
getOutputStream(), PrintStream(), accept(), url(),
FileInputStream()
Classes used : ftpserver
Loops used : while
Exceptions used : try catch , throws */

import [Link].*; // importing io package


import [Link].*; // importing java networking package
public class ftpserver // class ftpserver
{
public static void main(String args[]) throws Exception
{
ServerSocket ss = new ServerSocket(9000);
[Link]("Server Strated");
try
{
while(true)
{
Socket s=[Link](); // accepting connection
// created data input stream
DataInputStream di=new
DataInputStream([Link]());

29
PrintStream p=new
PrintStream([Link]());
String st=[Link]();
String temp=st;
temp= "[Link]
// url object creation
URL u=new URL(temp);
// opening connection to download the file
URLConnection uc = [Link]();
// creates file input stream to copy source to target
FileInputStream dil = new FileInputStream(st);
int ch;
while((ch=[Link]())!=-1) // repeat till not equal to -
1
{
[Link]((char)ch); // print on the screen
[Link](ch);
} // end inner while
[Link]();
} // end outer while
} // end try
catch(Exception e)
{
} // end catch
} // end main
} // end class

30
/* CLIENT SIDE PROGRAM */

/* This program is ftpclient which connects to ftpserver to


get the file copied from source to target remote location ,*/
Program name : [Link]
Packages used : [Link].*,[Link].*
Objects used : s,d1,in,di,file,p,st,fos
Methods : Socket(), BuferedReader, getInputStream(),
getOutputStream(), readLine(), PrintStream(), write(),
FileOutputStream()
Classes used : ftpclient
Loops used : while
Exceptions used : try catch , throws */

import [Link].*; // importing io package


import [Link].*; // java networking package
public class ftpclient // ftpclient
{
public static void main(String args[]) throws Exception
{
Socket s=new Socket("localhost",9000); // socket object
BufferedReader d1=new BufferedReader(new
InputStreamReader([Link]()));
InputStream in=[Link]();
DataInputStream di= new DataInputStream([Link]);
PrintStream p=new PrintStream([Link]());
[Link]("Enter [Link]");
// enter complete file path with drive and dir
String st=[Link]();
[Link](st);
// enter compete destination path to copy the file
contents
[Link]("enter destination");
String file=[Link]();
// create output stream to copy contents
FileOutputStream fos=new FileOutputStream(file);
int ch; // copying contents till it is not eof
while((ch=[Link]())!=-1)
{[Link]((char)ch);

31
[Link](ch);
} // end while
}// end main
}// end class
Output Screen:

32
5. TRIVIAL FILE TRANSFER PROTOCOL

Problem Description:

To develop a TFTP client for file transfer.

TFTP is a simple software package that can fit


into the read only memory of a diskless workstation. It
can be used at bootstrap time. TFTP can read or write a
file for the client.
Reading means copying a file from the server site
to the client site.
Writing means copying a file from the client site to the
server site.
A client uses the services of TFTP to retrieve a
copy of a file or send a copy of a file to a server.
TFTP is an application that uses UDP for its
transport mechanism. It uses RRQ, WRQ, ACK and
ERROR to establish connection. A DATA message with a

33
block of data less than 512 bytes terminates connection.
Each DATA message, except the last, carries 512 bytes
of data from the file. FTP uses stop-and-wait protocol for
flow control.

/* SERVER SIDE PROGRAM */

/* this tftpserver program copies the source file to target file


using datagram packets the tftpserver class is extended to
thread class.
Program name : [Link]
Packages used : [Link].*,[Link].*
Objects used : t,fis,ds,filename,dp
Variables used :buff[],pos,buff_size
Methods : Thread(), Start(), DatagramPacket(),
receive(), String(), FileInputStream(), getLocalHost(),
DatagramSocket()
Classes used : tftpclient

34
Loops used : while
Exceptions used : try catch , throws */

import [Link].*; // importing io package


import [Link].*; // importing networking package
class tftpms extends Thread // tftpms subclass for Thread
{
Thread t; // t - thread object
DatagramSocket ds;
tftpms(DatagramSocket ds)
{
try
{
t=new Thread(this);
[Link]=ds;
[Link]();
} // try
catch(Exception e)
{
} // end catch
} // end constructor
public void run()
{ // begin run method
try
{
int pos=0;
int buff_size=2000;
byte buff[]=new byte[buff_size];
DatagramPacket dp=new
DatagramPacket(buff,[Link]);
[Link](dp);
String filename=new
String([Link](),0,[Link]());
FileInputStream fis=new FileInputStream(filename);
int c;
while((c=[Link]())!=-1)
{
buff[pos++]=(byte)c;
if(pos%2000==0)

35
{
[Link](new
DatagramPacket(buff,pos,[Link]
(),50));
pos=0;
} // end if
} // end while
[Link](new
DatagramPacket(buff,pos,[Link](),5
0));
} // end try
catch(Exception e)
{
} // end catch
} // end run
} // end class

public class tftpserver


{
public static void main(String args[]) throws Exception
{
DatagramSocket ds;
[Link]("server ready");
ds=new DatagramSocket(69);
tftpms ms=new tftpms(ds);
} // end main
} // end tftpserver

36
/* CLIENT SIDE PROGRAM */

/* this tftpclient program responds to tftpserver it enters


absolute path and target file path which is sent to server
Program name : [Link]
Packages used : [Link].*,[Link].*
Objects used : ds,stt,fos
Variables used :buff[],pos,buff_size,j,g
Methods : DatagramSocket(), DataInputStream(),
readLine(), length(), DatagramPacket(), getLocalhost(),
readLine(), FileOutputStream(), DatagramPacket(),
receive(), getData(), getLength(), Write()
Classes used : tftpclient
Loops used : while
Exceptions used : try catch */

import [Link].*; // importing java io package


import [Link].*; // importing net package
class tftpclient // class tftpclient
{
public static void main(String args[])
{
tftpc c=new tftpc();
}
}

class tftpc
{
DatagramSocket ds;
int buff_size=2000;
byte buff[]=new byte[buff_size];
tftpc() // constructor
{
try
{
ds=new DatagramSocket(50);
} // end try
catch (Exception e)
{

37
[Link](0);
} // end catch
DataInputStream in=new DataInputStream([Link]);
try
{
// reading absolute file path
[Link]("Enter absolute path of file:");
String str=[Link]();
int pos=[Link]();
// creates byte array
byte buf[]=new byte[pos];
for(int i=0;i<pos;i++)
buf[i]=(byte)[Link](i);
[Link](new
DatagramPacket(buf,pos,[Link](),69
));
[Link]("enter the name to be saved");
String stt=[Link]();
// creates file output stream
FileOutputStream fos=new FileOutputStream(stt);
while(true)
{
DatagramPacket dp=new
DatagramPacket(buff,[Link]);
[Link](dp);
String file=new
String([Link](),0,[Link]());
int g=[Link]();
for(int j=0;j<g;j++)
[Link]((char)[Link](j));
} // while
}// end try
catch(Exception e)
{
} // end catch
}// end method
} // end class

38
Output Screen:

39
6. SIMULATION OF TELNET(Remote Login)

Problem Description:

Provide a user interface to contact well-known


ports, so that client-server interaction can be
seen by the user.

TELNET is and abbreviation for Terminal Network. It


is the standard TCP/IP Protocol for virtual terminal service
proposed by ISO.
Telnet enables the establishment of a connection to a
remote system in such a way that the local terminal appears
to be a terminal at the remote system.
Telnet is a client server application that allows a user
to log on to a remote machine giving the user access to the
remote system. When a user access a remote system via
the TELNET purees, this is comparable to a timesharing
environment.
Telnet uses Network Virtual Terminal system to
encode characters on the local system. On the server
machine, NVT decodes the characters to a form acceptable
to the remote machine.
In Telnet, control characters are embedded in the data
stream and preceded by the interpret as control (IAC)
control character.
Telnet allows negotiation to set transfer conditions
between the client & server before and during the use of
service.

40
Program :

/* It is a gui program to perform telnet , it is a menu driven


program which has options connect – to connect ,
disconnect and exit , the objects such as text
area ,textbox ,scroll pane , menu and buttons of swing class
are used
Program name : [Link]
Packages used :
[Link].*,[Link].*,[Link].*,[Link].*
Interfaces :ActionListener,KeyListener
Objects used : ta, jm, conmenu, conhost, discon, exit,
edtied, sco, br, pw, t, command
Variables used :off
Methods : keyPressed(), keytyped(),
actionPerformed(), makeConnection, setTitle(), setSize(),
String(), JTextArea(), addKeyListener, getcontrolPane(),
JScrollpane(), JKmenuBar(), setJmenuBar(), Jmenu(),add(),
JMenuItem(), addactionListener(), setMnemonic(),
setVisible(), getKeyChar(), getSource(), close(), Socket,
getText(), trim(), ParseInt(), showMessageDialog(),
BufferedReader(), InputStreamReader(), append(),
setCharAtPostition(), readthread(), readLine(), exit(),
getLineCount(), getLineStartOffset(), JDialog(), JTextField(),
JButton(), setBounds, setLayout, JLabel(), getSource(),
dispose(), makeConnection()
Classes used : telnet, readthread, condialog
Conditions :if
Loops used : while
Exceptions used : try catch */

41
import [Link].*; // importing io package
import [Link].*; // importing net package
import [Link].*; // swing package
import [Link].*; // awt packages
import [Link].*;

public class telnet extends JFrame implements


ActionListener,KeyListener
{
// object & variable declarations
public static JTextArea ta;
// creating objects for all gui components
JMenuBar jm;
JMenu conmenu;
JMenuItem conhost,discon,exit;
boolean edited=false;
Socket soc;
BufferedReader br;
PrintWriter pw;
public static telnet t;
String command;
// constructor that builds gui
public telnet()
{
setTitle(" Telnet "); // frame title
setSize(400,400); // frame size
command=new String();
ta=new JTextArea();
[Link](this);
getContentPane().add(new JScrollPane(ta));
jm=new JMenuBar(); // sets up menubar
setJMenuBar(jm);
conmenu=new JMenu("Connect");
[Link](conmenu); // adds menu to menubar
conhost=new JMenuItem("Connect");
[Link](this);
discon=new JMenuItem("Disconnect");
[Link](this);

42
exit=new JMenuItem("Exit");
[Link](this);
[Link]('C');
[Link](conhost);
[Link](discon);
[Link](exit);
setVisible(true); // displays frame
new condialog();
}
public void keyPressed(KeyEvent ke)
{ // no code required
}
public void keyReleased(KeyEvent ke)
{// no code required

}
public void keyTyped(KeyEvent ke)
{
// [Link]([Link]());
if([Link]()==KeyEvent.VK_ENTER)
{
[Link](command);
[Link](command);
command="";
}
else
if([Link]()!=KeyEvent.VK_SHIFT)
command=command+[Link]();
}

public void actionPerformed(ActionEvent ae)


{ // this method is executed when a button is pressed
Object ob=[Link]();
if(ob==exit)
// if exit button quit
[Link](0);
else
if(ob==conhost)
new condialog();

43
if(ob==discon)
if(!(soc==null))
{
[Link]("Connection closed");
try
{
[Link]();
soc=null;
}catch(Exception e)
{
[Link](e);
}// end catch
} // end if
} // end method
void makeconnection()
{
try
{
soc=new
Socket([Link]().trim(),[Link](con
[Link]().trim()));
[Link](null,"Connection
established");
[Link]("Connection established ");
br=new BufferedReader(new
InputStreamReader([Link]()));
pw=new PrintWriter([Link](),true);
/* String reply=[Link]();
[Link](reply+"\n");
[Link]([Link]()); */
new readthread().start();
}

catch(Exception e)
{
[Link](e);
[Link](null,"Connection
to host lost");
}

44
}
// class that reads responses from server

class readthread extends Thread


{
public void run() // run method
{
try
{
int off=0;
while(true)
{

String reply=[Link](); //reads response


if(reply==null) [Link](1);
[Link](reply+"\n"); // appends response to
textarea

int lc=[Link]();
off=[Link](lc);
[Link](off); // places cursor at the
end
} // end while
} // end try
catch(Exception e)
{
[Link](e);
[Link](null,"Connection
To Host Lost");
} // end catch
} // end run
} // end class
public static void main(String a[])
{
t=new telnet();
// [Link]();
}
}
// class that creates connection dialog
class condialog implements ActionListener
45
{
JDialog jd;
public static JTextField host,port;
JButton connect,cancel;
public condialog()
{
jd=new JDialog();
host=new JTextField(40);
port=new JTextField(40);
connect=new JButton("CONNECT");
cancel=new JButton("CANCEL");
[Link](this);
[Link](this);
[Link](200,300,300,150);
[Link]().setLayout(new GridLayout(3,2));
// adding components to content pane
[Link]().add(new JLabel("Remote
Host :"));
[Link]().add(host);
[Link]().add(new JLabel("Port
Number :"));
[Link]().add(port);
[Link]().add(connect);
[Link]().add(cancel);
[Link](true);
}// end method condialog constructor
public void actionPerformed(ActionEvent ae)
{
Object ob=[Link]();
if(ob==cancel)
[Link]();
else
if(ob==connect)
{
[Link]();
[Link]();
} // end if
} // end action performed

46
}// end class condialog

Output Screen :

47
48
7: HYPER TEXT TRANSFER PROTOCOL

Problem Description:

Develop a HTTP server to implement the following


commands.
GET, POST, HEAD, DELETE.

The server must handle multiple clients.


Hypertext transfer protocol is a communication
protocol for the transfer of information on the intranet
and the World Wide Web. Its original purpose was to
provide a way to publish and retrieve hypertext pages
over the Internet.
HTTP is a request/response standard between a client
& a server. A client is the end user, the server is the
website.

49
The client makes a HTTP request using a web-browser
is referred as user agent. The responding server which
stores or creates resources such as HTML files and
images is called the origin server.

HTTP methods:
GET:
Requests a representation of the specified resource.

POST:
Submits data to be processed to the identified
resource. The data is included in the body of the
request. This may result in the creation of a new
resource or the updates of existing resources or both.

HEAD:
Asks for the response identical to the one that would
correspond to a GET request, but without the response
body. This is useful for retrieving meta info. Written in
response header, without having to transport entire
content.

DELETE:
Deletes the specified resource.

/* SERVER SIDE PROGRAM */


// A server side program for implementing HTTP
protocol
Program name : [Link]
Packages used : [Link].*,[Link].*,[Link].*,
Objects used : s1, con1, commandsfromclient,
responsetoclient, input, f, file, line[], fis,
Variables used :length,index

50
Methods : ServerSocket(), accept(), BufferedReader(),
InutStreamReader(), getInputStream(), getOutputStream(),
PrintWriter(), lastindexof(), subString(), readLine(),
FileInputStream(), available(), String(), Close(), delete(),
exit()
Classes used : htps
Loops used : do..while
Condition :if,switch
Exceptions used : try catch , throws */

import [Link].*; // io package


import [Link].*; // java networking package
import [Link].*; // java language

public class htps


{
public static void main(String args[]) throws Exception
{
ServerSocket s1=new ServerSocket(2000);
Socket con1=[Link](); // accepting connection
[Link]("Connected to Server");
//create input stream for receiving commands
BufferedReader commandsFromClient=new
BufferedReader(new
InputStreamReader([Link]()));
//create output stream for sending responses
PrintWriter responseToClient=new
PrintWriter([Link](),true);
BufferedReader input=new BufferedReader(new
InputStreamReader([Link]));
int choice;
do
{

choice=[Link]([Link]());
String file;
byte line[]=null;
File f;

51
switch(choice)
{
//head method to get the header details of a
resource
case 1:[Link]("[Link]");
file=[Link]();
f=new File(file);
int index=[Link](".");
String type=[Link](index+1);
[Link](type);
long length=[Link]();
[Link](length);
break;
//receiving the message that has been
posted
case 2:[Link]("[Link]");
file=[Link]();
[Link]("MESSAGE POSTED FROM
CLIENT:");
[Link](file);
break;
//reading the file contents and
//printing the contents of the resource
case 3:[Link]("[Link]");
file=[Link]();
FileInputStream fis=new
FileInputStream(file);
while([Link]()!=0)
{
if([Link]()<1024)
line=new byte[[Link]()];
else
line=new byte[1024];
[Link](line);
file=new String(line);
[Link](file);
} // end while
[Link]("***");
[Link]();

52
break;
//deleting the resource from the
server
case 4:[Link]("[Link]");

file=[Link]();
f=new File(file);
[Link]();
break;
default:[Link]("[Link]");
[Link](0);
} // end switch
} // end do while
while(choice<=4);
[Link]();
[Link]();
} // end method
} // end class

53
/* CLIENT SIDE PROGRAM */
// A client program for implementing http
Program name : [Link]
Packages used : [Link].*,[Link].*,[Link].*,
Objects used :
s1,con1,commandstoserver,input,f,file,line[],fos
Variables used :length,index
Methods : Socket(),accept(), BufferedReader(),
InutStreamReader(), getInputStream(), getOutputStream(),
PrintWriter(), readLine(), FileOutputStream(), available(),
String(),Close(),delete(),exit(),parseInt(), length(),
getBytes(), write()
Classes used : htps
Loops used : do..while
Condition : if,switch
Exceptions used : try catch , throws */

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class htpc


{
public static void main(String args[]) throws Exception
{
Socket con1=new Socket("localhost",2000);
BufferedReader responseFromServer=new
BufferedReader(new
InputStreamReader([Link]()));

54
PrintWriter commandsToServer=new
PrintWriter([Link](),true);
BufferedReader input=new BufferedReader(new
InputStreamReader([Link]));
[Link]("CONNECTED TO SERVER");
int choice;
do
{
[Link]("COMMANDS");
[Link]("[Link] [Link] [Link]
[Link] [Link]");
[Link]("ENTER YOUR CHOICE:");
choice=[Link]([Link]());
byte line[]=null;
String file;
switch(choice)
{
case 1:[Link]("1");
[Link]("ENTER FILE NAME TO
GET THE HEADER:");
file=[Link]();
[Link](file);
String type=[Link]();
String
length=[Link]();

[Link]("FILE:"+file+"TYPE:"+type+"LENHTH:"
+length);
break;
case 2:[Link]("2");
[Link]("ENTER TEXT TO POST:");
file=[Link]();
[Link](file);
break;
case 3:[Link]("3");
[Link]("ENTER FILE NAME TO
GET:");
file=[Link]();
[Link](file);

55
[Link]("ENTER FILE NAME TO
SAVE:");
file=[Link]();
FileOutputStream fos=new
FileOutputStream(file);
while(true)
{
String s=[Link]();
if([Link]("***"))
break;
int count=[Link]();
if(count<1024)
line=new byte[count];
else
line=new byte[1024];
line=[Link]();
[Link](line);
}
[Link]();
break;
case 4:[Link]("4");
[Link]("ENTER FILE NAME TO
DELETE:");
file=[Link]();
[Link](file);
break;
default:[Link]("5");
[Link](0);
}
}
while(choice<=4);
[Link]();
}
}

56
Output Screen:

57
8. MAIL CLIENTS- POST OFFICE PROTOCOL
(POP)
&

58
SIMPLE MAIL TRANSFER PROTOCOL
(SMTP)

Problem Description:

i). POP Client : Gives the server name , user name


and password retrieve the mails and allow
manipulation of mail box using POP commands.
ii). SMTP Client : Gives the server name, send e-
mail to the recipient using SMTP commands.

POP (Post Office Protocol) mail client programs


(ex:Eudora, Netscape Communicator, MicrosoftExchange,
Microsoft Outlook) allow us to retrieve our email from the
central server to your local computer. When someone sends
us an email message, the message is received, processed
and stored in your mail file on the central mail server.

We can access our email


1. locally by logging onto the mail server and using a mail
client program (or)
2. remotely by using a POP/IMAP client program.

With a POP client our email is copied/retrieved from the


mail sever to a local computer. With an IMAP client our
email is accessible remotely, but is stored and managed on
the server.
SMTP client transmits a mail to an SMTP server which
does the delivery. It is a simple, text based protocol in
which one or more recipients of a message are specified
along with message text and other encoded objects. The
message is then transferred to a remote server using a
procedure of queries and responses between a client and a
server. Either an end user’s email client Mail User Agent or
a relaying server’s Mutual Transport Agents can act as an
SMTP Client.

59
8.1. MAIL CLIENT- POP ( COMMAND
PROMPT)

//pop mail

Program name : [Link]


Packages used : [Link].*,[Link].*,[Link].*,
Objects used :
connecttoserver,isfromserver,osToserver,br,c,s,e
Methods : Socket(), BufferedReader(),
InputStreamReader(), getInputStream(),
getOutputStream(), PrintWriter(), readLine(), close()
Classes used : POPMAIL
Loops used : while
Condition : if
Exceptions used : try catch */

import [Link].*; // importing io package


import [Link].*; // importing net package
import [Link].*; // util package
public class POPMail
{
public static void main(String args[])
{
try
{
Socket connectToServer=new
Socket("[Link]",110);
BufferedReader isFromServer=new
BufferedReader(new
InputStreamReader([Link]
tream()));

60
PrintWriter osToServer=new
PrintWriter([Link](
),true);
BufferedReader br=new
BufferedReader(new
InputStreamReader([Link]));
[Link]("user "+"user1");
[Link]("USER RESPONSE
IS:"+[Link]());
[Link]("pass "+"user1");
[Link]("PASSWORD
RESPONSE IS:"+[Link]());

[Link]([Link]());
while(true)
{
[Link]("ENTER THE POP
COMMAND:");
String c=[Link]();
if([Link]()==0) break;
[Link](c);
String s=[Link]();
while(![Link]("."))
{
[Link](s);
s=[Link]();
}
}
[Link]();
}
catch(Exception e)
{
[Link]("ERROR:"+e);
}
}
}

61
8.2. MAIL CLIENT- SMTP ( COMMAND
PROMPT)

// smtp client
Program name : [Link]
Packages used : [Link].*,[Link].*,[Link].*,
Objects used :
connecttoserver,isfromserver,osToserver,br,c,s,e
Methods : Socket(), BufferedReader(),
InputStreamReader(), getInputStream(),
getOutputStream(), PrintWriter(), readLine(), close()
Classes used : POPMAIL
Loops used : while
Condition : if
Exceptions used : try catch */

import [Link].*;
import [Link].*;
import [Link].*;

62
public class SMTPClient
{

public static void main(String args[])


{
Socket s;
PrintWriter pw;
BufferedReader br,fromkb;
try
{
s=new Socket("localhost",25);
br=new BufferedReader(new
InputStreamReader ([Link]()));
pw=new
PrintWriter([Link](),true);
fromkb=new BufferedReader(new
InputStreamReader([Link]));
int ch;
String msg=null;
do
{
[Link](" SMTP COMMANDS");
[Link]("[Link] ");
[Link]("[Link]
USERNAME");
[Link]("[Link] USERNAME");
[Link]("[Link] & SEND");
[Link]("[Link]");
[Link]("ENTER YOUR CHOICE:");
ch=[Link]([Link]());
switch(ch)
{
case 1: [Link]("HELO"); break;
case 2: [Link]("Enter Senders
address");
msg=[Link]();
[Link]("MAIL FROM: "+ msg);break;

63
case 3: [Link]("Enter receivers
address");
msg=[Link]();
[Link]("RCPT TO: "+
msg);break;
case 4:[Link]("Enter data to
send");

msg=[Link]();[Link]("DATA");
[Link](msg);[Link](".");
[Link]("QUIT");break;
default :[Link](0);
}
}while(ch<5);
}
catch(Exception e)
{
[Link](e);
}
}
}

64

You might also like