Beruflich Dokumente
Kultur Dokumente
Kovilvenni-614 403
Department of Information Technology
LAB MANUAL
Faculty : M.C.Jayaprasanna
SYLLABUS FOR THE COURSE
LIST OF EXPERIMENTS
TOTAL: 45 PERIODS
OBJECTIVE OF THE COURSE
Client
Client Server
Client
4. The upper three layers of OSI model are combined into a single layer called the application.
This is the Web Client (Browser), Telnet client, Web Server, FTP server or whatever
application we are using.
5. The transport layer comprises of TCP and UDP.
6. There is a gap between TCP and UDP in figure to indicate that it is possible for an
application to bypass the transport layer and use IPv4 and IPv6 directly. This is called raw
socket.
7. The two programming interfaces are sockets and XTI(X/Open Transport Interface). It is
intended to study: how to write applications using either Sockets that use either TCP or UDP.
8. Upper three layers handle all the details of the application (FTP, Telnet or HTTP etc) and
know little about the communication details. Whereas the lower four layers know little about
the application but handle all communication details: sending data, waiting for an
acknowledgements, sequencing data that arrives out of order , calculating and verifying the
checksums and so on.
9. Upper three layers often form what is called a user process while the lower 4 layers are
normally provided as part of the operating system kernel.
Port Number
1. Port is an application-specific or process-specific software construct serving as a
communications endpoint in a computer's host operating system.
2. A port is associated with an IP address of the host, as well as the type of protocol used for
communication.
3. A port is identified for each address and protocol by a 16-bit number, commonly known
as the port number.
4. Port Numbers: At any given time multiple processes can use either UDP or TCP. Both
use 16 bit integer port numbers to differentiate between these processes.
5. TCP and UDP define a group of well-known ports that to identity well known services.
FTP assigns the well-known ports of 21 to the FTP server .Trivial FTP servers are
assigned the UDP port of 69.
6. Clients use ephemeral ports that are short lived ports. These port numbers are manually
assigned by TCP or UDP to the client.
7. The port numbers are divided into three categories
Well known ports: 0 through 1023 .These port numbers are controlled and
assigned by the IANA. When possible same port number is assigned to a given
service of both TCP and UDP.
The Registered Ports: 1024 through 49151.These are not controlled by the IANA,
(Internet Assigned Numbers Authority) but the IANA registers and lists the uses
of these ports as a convenience to the community.
Dynamic private ports: 49152 through 65535. These are what we call as
ephemeral ports. It is also called Short lived transport protocol port that is created
by OS when a program requests any available user ports.
Allocation of Port Numbers
Socket Pair
1. Socket is a method for communication between a client program & a server program in a
network. A socket is defined as “the endpoint in a connection”.
2. The two values that identify each endpoint, an IP address and a port number, are called a
socket.
3. The socket pair for a TCP connection is the 4-tuple that defined the two end points of the
connection:
i) The local IP address ii) local TCP port,
ii) Foreign IP address iv) foreign TCP port.
Types of Sockets
There are 3 types of sockets
1. Stream Socket (designed to be used with a connection-oriented protocol such as TCP)
2. Datagram Socket (designed to be used with a connectionless protocol such as UDP)
3. Raw Socket (provide access to ICMP to move esoteric (secret) facilities of an existing
protocol)
EX.NO:1 Implementation of Stop and Wait Protocol and Sliding Window Protocol
AIM
To write a java program to perform stop & wait and sliding window protocols.
CONCEPT
1. Stop-and-Wait Protocol means that the sender sends one frame, stops until it receives
confirmation from the receiver (okay to go ahead), and then sends the next frame.
2. If data frames arrive at the receiver site faster than they can be processed, the frames must be
stored until their use.
3. Normally, the receiver does not have enough storage space, especially if it is receiving data
from many sources. This may result in either the discarding of frames or denial of service.
4. To prevent the receiver from becoming over-whelmed with frames, we need to tell the sender
to slow down.
5. A sliding window protocol is a feature of packet-based data transmission protocols.
conceptually, each portion of the transmission is assigned a unique consecutive sequence
number, and the receiver uses the numbers to place received packets in the correct order.
6. Sliding window protocol allows an unlimited number of packets to be communicated using
fixed-size sequence numbers.
7. The term "window" on transmitter side represents the logical boundary of the total number of
packets yet to be acknowledged by the receiver.
SOURCE CODE
Stop & wait protocol
\\Sender Program
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",2004);
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();
}
}
//Receiver Program
import java.io.*;
import java.net.*;
public class Reciever{
ServerSocket reciever;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,data="";
int i=0,sequence=0;
Reciever(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
reciever = new ServerSocket(2004,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 received="+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[]){
Reciever s=new Reciever();
while(true){
s.run();
}}}
SAMPLE INPUT& OUTPUT
Sender
C:\>javac Sender.java
C:\>java Sender
Waiting for Connection....
reciver > connected .
Enter the data to send....
hi
data sent>0h
waiting for ack.....
receiver > packet recieved
data sent>1i
waiting for ack.....
receiver > packet recieved
All data sent. exiting.
Receiver
C:\>javac Reciever.java
C:\>java Reciever
Waiting for connection …
Connection established:
receiver > 0h
receiver > 1i
Data received=hi
Waiting for connection…
Receiver
import java.net.*;
import java.io.*;
class slidreceiver
{
public static void main(String a[])throws Exception
{
Socket s=new Socket(InetAddress.getLocalHost(),10);
DataInputStream in=new DataInputStream(s.getInputStream()); PrintStream p=new
PrintStream(s.getOutputStream());
int i=0,rptr=-1,nf,rws=8; String rbuf[]=new String[8]; String
ch; System.out.println(); do
{
nf=Integer.parseInt(in.readLine()); if(nf<=rws-1)
{
for(i=1;i<=nf;i++)
{
rptr=++rptr%8;
rbuf[rptr]=in.readLine();
System.out.println("The received Frame " +rptr+" is : "+rbuf[rptr]);
}
rws-=nf; System.out.println("\nAcknowledgment
sent\n"); p.println(rptr+1); rws+=nf; }
else break;
ch=in.readLine();
}
while(ch.equals("yes"));
}
}
//RECEIVER OUTPUT
C:\>javac slidreceiver.java
Note: slidreceiver.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
C:\>java slidreceiver
The received Frame 0 is : hi
The received Frame 1 is : how are u?
The received Frame 2 is: fine
The received Frame 3 is : thank u
Acknowledgment sent
RESULT
Thus the program for implementing Stop and Wait Protocol and Sliding Window
Protocol was executed successfully and output verified.
EX.NO:2 Study of Socket Programming and Client – Server model
AIM
To implement socket programming date and time display from client to server using TCP
Sockets.
CONCEPT
Socket Programming
1. Sockets provide the communication mechanism between two computers using TCP. A
client program creates a socket on its end of the communication and attempts to connect
that socket to a server.
2. When the connection is made, the server creates a socket object on its end of the
communication. The client and server can now communicate by writing to and reading
from the socket.
Client–server model
1. The client–server model of computing is a distributed application structure that partitions
tasks or workloads between the providers of a resource or service, called servers, and
service requesters, called clients.
2. Often clients and servers communicate over a computer network on separate hardware,
but both client and server may reside in the same system.
3. A server host runs one or more server programs which share their resources with clients.
A client does not share any of its resources, but requests a server's content or service
function.
4. Clients therefore initiate communication sessions with servers which await incoming
requests. Examples of computer applications that use the client–server model are Email,
network printing, and the World Wide Web.
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);
}
}
}
Client:
C:\>javac tcpdateclient.java
C:\>java tcpdateclient
THE EXCEPTION is: java.net.ConnectException: Connection refused: connect
C:\>java tcpdateclient
The date/time on server is: Tue May 19 20:19:23 IST 2015
RESULT
Thus the program for implementing to display date and time from client to server using
TCP Sockets was executed successfully and output verified using various samples.
EX.NO:3 Simulation of ARP /RARP protocols
AIM
To write a java program for simulating arp/rarp protocols
CONCEPT
ARP (Address Resolution Protocol)
The logical (IP) address is obtained from the DNS if the sender is the host or it is found
in a routing table if the sender is a router. But the IP datagram must be encapsulated in a
frame to be able to pass through the physical network.
The host or the router sends an ARP query packet. The packet includes the physical and
IP addresses of the sender and the IP address of the receiver.
Because the sender does not know the physical address of the receiver, the query is
broadcast over the network.
Every host or router on the network receives and processes the ARP query packet, but
only the intended recipient recognizes its IP address and sends back an ARP response
packet.
The response packet contains the recipient's IP and physical addresses.
RARP (Reverse Address Resolution Protocol
RARP finds the logical address for a machine that knows only its physical address.
Each host or router is assigned one or more logical (IP) addresses, which are unique and
independent of the physical (hardware) address of the machine.
To create an IP datagram, a host or a router needs to know its own IP address or
addresses.
ALGORITHM
SERVER
Step1: Create a server socket and client socket.
Step2: Create a process.
Step3: Get request from client.
Step4: Send the physical address to the client.
Step5: Close server socket and client socket connection.
CLIENT
Step1: Create a client socket connection with specified port.
Step2: Read the message from the client.
Step3: Send the System name to the server.
Step4: Read the message from the server. Print the message.
Step5: Close the client connection.
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n');
break;
}
}
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrarp12
{
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,receive
byte.length);
server.receive(receiver);
String str=new String(receiver.getData());
String s=str.trim(); //System.out.println(s);
InetAddress addr=receiver.getAddress(); int port=receiver.getPort();
}
}
RESULT
Thus the program for simulating ARP /RARP protocols was executed.
EX.NO: 4 Simulation of PING and TRACEROUTE commands
AIM
To write the java program for simulating ping and trace route commands
CONCEPT
PING Command
1. The ping command is a very common method for troubleshooting the accessibility of
devices. It uses a series of Internet Control Message Protocol (ICMP) Echo messages to
determine:
Whether a remote host is active or inactive.
The round-trip delay in communicating with the host.
Packet loss.
2. The ping command first sends an echo request packet to an address, and then waits for a
reply. The ping is successful only if:
the echo request gets to the destination, and
the destination is able to get an echo reply back to the source within a
predetermined time called a timeout. The default value of this timeout is two
seconds on Cisco routers.
TRACEROUTE Command
1. The trace route command is used to discover the routes that packets actually take when
traveling to their destination. The device (for example, a router or a PC) sends out a
sequence of User Datagram Protocol (UDP) data grams to an invalid port address at the
remote host.
2. Three data grams are sent, each with a Time-To-Live (TTL) field value set to one. The
TTL value of 1 causes the datagram to "timeout" as soon as it hits the first router in the
path; this router then responds with an ICMP Time Exceeded Message (TEM) indicating
that the datagram has expired.
3. Another three UDP messages are now sent, each with the TTL value set to 2, which
causes the second router to return ICMP TEMs. This process continues until the packets
actually reach the other destination.
4. Since these data grams are trying to access an invalid port at the destination host, ICMP
Port Unreachable Messages are returned, indicating an unreachable port; this event
signals the Trace route program that it is finished.
ALGORITHM
Ping Server
1. Start the program.
2. Import necessary packages.
3. Initialize the ping server with both sockets as null value.
4. Start the server socket.
5. At the client give the IP address of the server.
6. The client program is then started by starting socket.
7. At the receiver end, the client is pinged.
8. Stop the program.
Ping Client
1. Start the program.
2. Import necessary packages.
3. Initialize the ping client with both sockets as null value.
4. Start the socket.
5. Get the IP address of the server.
6. Ping the server.
7. At the receiver end, the server is pinged.
8. Stop the program.
SOURCE CODE
//pingclient.java
import java.io.*;
import java.net.*;
import java.util.Calendar;
class pingclient
{
public static void main(String args[])throws Exception
{
String str;
int c=0;
long t1,t2;
Socket s=new Socket("127.0.0.1",5555);
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
while(c<4)
{
t1=System.currentTimeMillis();
str="Welcome to network programming world";
out.println(str);
System.out.println(dis.readLine());
t2=System.currentTimeMillis();
System.out.println(";TTL="+(t2-t1)+"ms"); c++;
}
s.close();
}
//pingserver.java
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
class pingserver
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(5555); Socket
s=ss.accept();
int c=0;
while(c<4)
{
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
String str=dis.readLine();
out.println("Reply from"+InetAddress.getLocalHost()+";Length"+str.length()); c++;
}
s.close();}}
C:\>java pingclient
Reply from welcome-PC/192.168.1.100;Length36; TTL=50ms
Reply from welcome-PC/192.168.1.100;Length36; TTL=0ms
Reply from welcome-PC/192.168.1.100;Length36; TTL=0ms
Reply from welcome-PC/192.168.1.100;Length36; TTL=0ms
RESULT
Thus the program for simulating ping and trace route commands were executed.
EX.NO:5 Creation of sockets for HTTP web page upload and download
AIM
To write a java program for creating socket for HTTP web page upload and download.
CONCEPT
HTTP
1. The Hypertext Transfer Protocol (HTTP) is a protocol used mainly to access data on the
World Wide Web.
2. HTTP functions as a combination of FTP and SMTP.
3. SMTP messages are stored and forwarded, but HTTP messages are delivered
immediately.
4. The commands from the client to the server are embedded in a request message. The
contents of the requested file or other information are embedded in a response message.
ALGORITHM
Step1: Set a server port as 80.
Step2: Using HTTP services create a Socket for server by specifying the server port
Step3: Use HTTP socket for connecting the client to the URL.
Step4: Use BufferedReader to output stream to place the response from the server by the client.
Step5: Close the Connection as soon the request is been serviced. Use Malformed URL
exception If any errors in grabbing the server
SOURCE CODE
client
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 Client{
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. ");
img = ImageIO.read(new File("digital_image_processing.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
After receiving the image, the server displays the image as shown below:
RESULT
Thus the program for creating sockets for HTTP web page upload and download was
implemented.
EX.NO:6 Implementation of RPC (Remote Procedure Call)
AIM
To write a java program to implement RPC (remote procedure call
CONCEPT
1. RPC is a powerful technique for constructing distributed, client-server based applications,
based on extending the notion of conventional or local procedure calling.
2. The transport independence of RPC isolates the application n from the physical and logical
elements of the data communications mechanism and allows the application to use a variety of
transports.
3. When an RPC is made, the calling arguments are passed to the remote procedure and the caller
waits for a response to be returned from the remote procedure.
4. RPC specifically supports network applications.
ALGORITHM
1. Start.
2. Create a server socket at the server side.
3. Create a socket at the client side and the connection is set to accept by the server socket using
the accept () method.
4. In the client side the command to be executed is given as input.
5. The command is obtained using the readLine () method of Buffer Reader.
6. Get the runtime object of the runtime class using getruntime ().
7. Execute the command using the exec () method of runtime.
8. Stop.
SOURCE CODE
Client
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrpc
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter String");
String str=in.readLine();
dout.writeBytes(str+'\n'); clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Server
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrpc
{
public static void main(String args[])
{
try
{
ServerSocket obj=new
ServerSocket(139); while(true)
{
Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
Process p=Runtime.getRuntime().exec(str);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
RESULT
Thus the RPC program was implemented.
EX.NO:7 Implementation of Sub netting
AIM
To write a program to implement sub netting and find the subnet masks.
CONCEPT
If an organization was granted a large block in class A or B, it could divide the addresses
into several contiguous groups and assign each group to smaller networks (called subnets) or, in
rare cases, share part of the addresses with neighbors.
ALGORITHM
1. Start the program.
2. Get the frame size from the user
3. To create the frame based on the user request.
4. To send frames to server from the client side.
5. If your frames reach the server it will send ACK signal to client otherwise it will send NACK
signal to client.
6. Stop the program
SOURCE CODE
import java.util.Scanner;
class Subnet{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the ip address: ");
String ip = sc.nextLine();
String split_ip[] = ip.split("\\."); //SPlit the string after every .
String split_bip[] = new String[4]; //split binary ip
String bip = "";
for(int i=0;i<4;i++){
split_bip[i] = appendZeros(Integer.toBinaryString(Integer.parseInt(split_ip[i]))); // “18” => 18
=> 10010 => 00010010
bip += split_bip[i];
}
System.out.println("IP in binary is "+bip);
System.out.print("Enter the number of addresses: ");
int n = sc.nextInt();
//Calculation of mask
int bits = (int)Math.ceil(Math.log(n)/Math.log(2)); /*eg if address = 120, log 120/log 2 gives log
to the base 2 => 6.9068, ceil gives us upper integer */
System.out.println("Number of bits required for address = "+bits);
int mask = 32-bits;
System.out.println("The subnet mask is = "+mask);
RESULT
Thus the program for sub netting was implemented.
EX.NO: 8a Applications using TCP Sockets (like Echo client and echo server)
AIM
To write a java program for Echo client and echo server using TCP Sockets.
CONCEPT
1. The Echo server simply receives data from its client and echoes it back.
2. The Echo server is a well-known service that clients can rendezvous with on port 7.EchoClient
creates a socket thereby getting a connection to the Echo server.
3. It reads input from the user on the standard input stream, and then forwards that text to the
Echo server by writing the text to the socket.
4. The server echoes the input back through the socket to the client. The client program reads and
displays the data passed back to it from the server.
ALGORITHM
1. Create two programs one for the server side and one for the client side
2. In the server side, create a server socket.
3. The return value of the accept () method is assigned to a new socket created.
4. Send the input received from the client at the server side back to the client.
5. In the client side, create a socket to connect to the server.
6. Create the object of DataInputStream to accept input from the server
7. Display the input received from the server.
8. Stop the program.
SOURCE CODE
//echo client.java
import java.io.*;
import java.net.*;
import java.util.*;
public class echoclient
{
public static void main(String args[])throws Exception
{
Socket c=null; DataInputStream
usr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStream dout=null;
try
{
c=new Socket("127.0.0.1",5678);
usr_inp=new DataInputStream(c.getInputStream()); dout=new
DataOutputStream(c.getOutputStream());
}
catch(IOException e)
{
}
if(c!=null || usr_inp!=null || dout!=null)
{
String unip; while((unip=din.readLine())!=null)
{
dout.writeBytes(""+unip);
dout.writeBytes("\n"); System.out.println("\n the echoed message");
System.out.println(usr_inp.readLine()); System.out.println("\n enter your
message");
}
System.exit(0);
}
din.close(); usr_inp.close(); c.close();
}
}
//echoserver.java
import java.io.*;
import java.net.*;
public class echoserver
{
public static void main(String args[])throws Exception
{
ServerSocket m=null; Socket c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in); DataOutputStream dout=null;
try
{
m=new ServerSocket(5678); c=m.accept();
usr_inp=new DataInputStream(c.getInputStream()); dout=new
DataOutputStream(c.getOutputStream());
}
catch(IOException e) {}
if(c!=null || usr_inp!=null)
{
String unip;
while(true)
{
System.out.println("\nMessage from Client..."); String m1=(usr_inp.readLine());
System.out.println(m1); dout.writeBytes(""+m1); dout.writeBytes("\n");
}
}
dout.close(); usr_inp.close(); c.close();
}
}
SAMPLE INPUT & OUTPUT
C:\>java echoserver
Message from Client...
hi
Message from Client...
how are u?
C:\>java echoclient
hi
the echoed message
hi
enter your message
how are u?
the echoed message
how are u?
RESULT
Thus the java program for Echo client and echo server using TCP Sockets was created.
EX.NO: 8b Applications using TCP Sockets (like Chat)
AIM
To write a java program for chat using TCP Sockets.
CONCEPT
1. It uses TCP socket communication .We have a server as well as a client.
2. Both can be run in the same machine or different machines. If both are running in the
machine, the address to be given at the client side is local host address.
3. If both are running in different machines, then in the client side we need to specify the ip
address of machine in which server application is running.
ALGORITHM
Server
1. Start the program
2. Create server and client sockets.
3. Use input streams to get the message from user.
4. Use output streams to send message to the client.
5. Wait for client to display this message and write a new one to be displayed by the
server.
6. Display message given at client using input streams read from socket.
7. Stop the program.
Client
1. Start the program
2. Create a client socket that connects to the required host and port.
3. Use input streams read message given by server and print it.
4. Use input streams; get the message from user to be given to the server.
5. Use output streams to write message to the server.
6. Stop the program.
SOURCE CODE
Client
/talkclient.java
import java.io.*; import java.net.*; public class talkclient
{
public static void main(String args[])throws Exception
{
Socket c=null; DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in); DataOutputStream dout=null;
try
{
c=new Socket("127.0.0.1",1234);
usr_inp=new DataInputStream(c.getInputStream()); dout=new
DataOutputStream(c.getOutputStream());
}
catch(IOException e) {}
if(c!=null || usr_inp!=null || dout!=null)
{
String unip;
System.out.println("\nEnter the message for server:"); while((unip=din.readLine())!=null)
{
dout.writeBytes(""+unip);
dout.writeBytes("\n");
System.out.println("reply"); System.out.println(usr_inp.readLine());
System.out.println("\n enter your message:");
}
System.exit(0);
}
din.close(); usr_inp.close(); c.close();
}
}
Server
//talkserver.java import java.io.*; import java.net.*; public
class talkserver
{
public static void main(String args[])throws Exception
{
ServerSocket m=null; Socket c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in); DataOutputStream dout=null;
try
{m=new ServerSocket(1234);
c=m.accept();
usr_inp=new DataInputStream(c.getInputStream()); dout=new
DataOutputStream(c.getOutputStream());
}
catch(IOException e) {}
if(c!=null||usr_inp!=null)
{
String unip; while(true)
{
System.out.println("\nmessage from client:"); String m1=usr_inp.readLine();
System.out.println(m1); System.out.println("enter your message:");
unip=din.readLine(); dout.writeBytes(""+unip); dout.writeBytes("\n");
}
}
dout.close(); usr_inp.close(); c.close();
}
}
SAMPLE INPUT & OUTPUT
C:\>javac talkserver.java
Note: talkserver.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
C:\>java talkserver
message from client:
hi
enter your message:
hi
RESULT
Thus the java program for chat using TCP Sockets was executed.
EX.NO: 8c Applications using TCP Sockets (like file transfer)
AIM
To write a java program for file transfer using TCP Sockets.
CONCEPT
Our application has a client and a server. Our aim is to send a file from the client
machine to the server machine.
ALGORITHM
Server
1. Import java packages and create class file server.
2. Create a new server socket and bind it to the port.
3. Accept the client connection
4. Get the file name and stored into the BufferedReader.
5. Create a new object class file and realine.
6. If file is exists then FileReader read the content until EOF is reached.
7. Stop the program.
Client
1. Import java packages and create class file server.
2. Create a new server socket and bind it to the port.
3. Now connection is established.
4. The object of a BufferReader class is used for storing data content which has been retrieved
from socket object.
5. The content of file is displayed in the client window and the connection is closed.
6. Stop the program.
SOURCE CODE
Client
import java.io.*; import java.net.*;
import java.util.*; class Clientfile
{
public static void main(String args[])
{
Try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); Socket clsct=new
Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream()); DataOutputStream
dout=new DataOutputStream(clsct.getOutputStream()); System.out.println("Enter the file
name:");
String str=in.readLine(); dout.writeBytes(str+'\n');
System.out.println("Enter the new file name:");
String str2=in.readLine();
String str1,ss;
FileWriter f=new FileWriter(str2); char buffer[];
while(true)
{ str1=din.readLine(); if(str1.equals("-1")) break;
System.out.println(str1); buffer=new
char[str1.length()];
str1.getChars(0,str1.length(),buffer,0);
f.write(buffer);
}
f.close();
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Server
import java.io.*;
import java.net.*;
import java.util.*;
class Serverfile
RESULT
Thus the java program file transfer application using TCP Sockets was executed.
EX.NO:9a Applications using TCP and UDP Sockets (like DNS)
AIM
To write a java program for DNS application.
CONCEPT
1. The DNS client program sends a request to a DNS server to map the e-mail address to the
corresponding IP address.
2. When the Internet was small, mapping was done by using a host file. The host file had
only two columns: name and address.
3. The host that needs mapping can contact the closest computer holding the needed
information. This method is used by the Domain Name System (DNS).
ALGORITHM
Server
Step1: Start the program.
Step2: Create the socket for the server.
Step3: Bind the socket to the port.
Step4: Listen for the incoming client connection.
Step5: Receive the IP address from the client to be resolved.
Step6: Get the domain name for the client.
Step7: Check the existence of the domain in the server.
Step8: If domain matches then send the corresponding address to the client.
Step9: Stop the program execution
Client
Step1: Start the Program.
Step2: Create the socket for the client.
Step3: Connect the socket to the Server.
Step4: Send the host name to the server to be resolved.
Step5: If the server corresponds then print the address and terminate the process
SOURCE CODE
// UDP DNS Server
Udpdnsserver.java
import java.io.*;
import java.net.*;
public class udpdnsserver
{
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
Udpdnsclient.java
import java.io.*; import java.net.*;
public class udpdnsclient
{
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();
}}
RESULT
AIM
To write a java program for SNMP application.
CONCEPT
1. Simple Network Management Protocol (SNMP) is a framework for managing devices in
an internet using TCP/IP.
2. It provides a set of fundamental operations for monitoring and maintaining an internet.
3. SNMP uses the concept of manager and agent
– A manager is a host that runs the SNMP client program.
– A managed station called an agent, is a router that runs the SNMP server
program
ALGORITHM
1.Start the program.
2.Get the frame size from the user
3.To create the frame based on the user request.
4.To send frames to server from the client side.
5.If your frames reach the server it will send ACK signal to client otherwise it will send NACK
signal to client.
6.Stop the program
SOURCE CODE
import java.io.IOException;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
public class SNMPManager {
Snmp snmp = null;
String address = null;
* Constructor
* @param add
*/
public SNMPManager(String add)
{
address = add;
public static void main(String[] args) throws IOException { /**
* Port 161 is used for Read and Other operations
* Port 162 is used for the trap generation */
SNMPManager client = new SNMPManager("udp:127.0.0.1/161");
client.start();
/**
* OID - .1.3.6.1.2.1.1.1.0 => SysDec
RESULT
Thus the SNMP application was implemented.
EX.NO:9c Applications using TCP and UDP Sockets (like file transfer)
AIM
To write a java program for SNMP application.
CONCEPT
Our application has a client and a server. Our aim is to send a file from the client
machine to the server machine.
ALGORITHM
Server
1. Import java packages and create class file server.
2. Create a new server socket and bind it to the port.
3. Accept the client connection
4. Get the file name and stored into the BufferedReader.
5. Create a new object class file and realine.
6. If file is exists then FileReader read the content until EOF is reached.
7. Stop the program.
Client
1. Import java packages and create class file server.
2. Create a new server socket and bind it to the port.
3. Now connection is established.
4. The object of a BufferReader class is used for storing data content which has been retrieved
from socket object.
5. The content of file is displayed in the client window and the connection is closed.
6. Stop the program.
SOURCE CODE
Client
import java.io.*; import java.net.*; import java.util.*; class Clientfile
{ public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); Socket clsct=new
Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream()); DataOutputStream
dout=new DataOutputStream(clsct.getOutputStream()); System.out.println("Enter the file
name:");
String str=in.readLine(); dout.writeBytes(str+'\n'); System.out.println("Enter the new file
name:"); String str2=in.readLine();
String str1,ss;
FileWriter f=new FileWriter(str2); char buffer[];
while(true)
{ str1=din.readLine(); if(str1.equals("-1")) break; System.out.println(str1); buffer=new
char[str1.length()];
str1.getChars(0,str1.length(),buffer,0);
f.write(buffer);
} f.close();
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}}
Server
import java.io.*;
import java.net.*;
import java.util.*;
class Serverfile
{
public static void main(String args[])
{
try
{
ServerSocket obj=new ServerSocket(139);
while(true)
{
Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
FileReader f=new FileReader(str);
BufferedReader b=new BufferedReader(f);
String s;
while((s=b.readLine())!=null)
{
System.out.println(s);
dout.writeBytes(s+'\n');
}
f.close(); dout.writeBytes("-1\n");
} }
catch(Exception e)
{ System.out.println(e);
}
}
}
SAMPLE INPUT & OUTPUT
C:\>java Clientfile
Enter the file name:
copy.txt
Enter the new file name:
new
hiiiiiiiiiiiiiiiiii
C:\>java Serverfile
hiiiiiiiiiiiiiiiiii
RESULT
Thus the file transfer application was executed.
EX.NO: 10 Study of Network simulator (NS) and Simulation of Congestion
Control Algorithms using NS
AIM
To Study of Network simulator (NS) and Simulation of Congestion Control Algorithms
using NS.
RESULT
Thus the study of Network simulator (NS2) was studied.
EX.NO:11 Case study on routing algorithms
AIM
To study the link state routing algorithm.
RESULT
Thus the case study about the different routing algorithms to select the network path with
its optimum and economical during data transfer was performed.