You are on page 1of 49

EX.

NO:1 IMPLEMENTATION OF STOP AND WAIT PROTOCOL AND SLIDING WINDOW PROTOCOL

Aim:
To write a C program to perform Stop and Wait Protocol and Sliding Window
Protocol.
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

Program :
//SENDER//

import java.io.*;
import java.net.*;
import java.util.Scanner;
class stopwaitsender

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

stopwaitsender sws = new stopwaitsender();

sws.run();
}

public void run() throws Exception

Scanner sc=new Scanner(System.in);


System.out.println(“Enter no of frames to be sent:”);
int n=sc.nextInt();
Socket myskt=new Socket(“localhost”,9999);

PrintStream myps=new PrintStream(myskt.getOutputStream());

for(int i=0;i<=n;)

if(i==n)

myps.println(“exit”);

break;

System.out.println(“Frame no “+i+” is sent”);


myps.println(i);

BufferedReader bf=new BufferedReader(new InputStreamReader(myskt.getInputStream()));

String ack=bf.readLine();

if(ack!=null)

System.out.println(“Acknowledgement was Received from receiver”);


i++;

Thread.sleep(4000);
}

else

myps.println(i);

}
}

//RECEIVER//

import java.io.*;
import java.net.*;
class stopwaitreceiver

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

stopwaitreceiver swr = new stopwaitreceiver();

swr.run();
}

public void run() throws Exception

String temp=”any message”,str=”exit”;

ServerSocket myss=new ServerSocket(9999);

Socket ss_accept=myss.accept();

BufferedReader ss_bf=new BufferedReader(new


InputStreamReader(ss_accept.getInputStream()));

PrintStream myps=new PrintStream(ss_accept.getOutputStream());

while(temp.compareTo(str)!=0)

Thread.sleep(1000);
temp=ss_bf.readLine();

if(temp.compareTo(str)==0)
{ break;}

System.out.println(“Frame “+temp+” was received”);


Thread.sleep(500);
myps.println(“Received”);

System.out.println(“ALL FRAMES WERE RECEIVED SUCCESSFULLY”);


}

}
OUTPUT FOR SENDER:
C:\javaprog>javac stopwaitsender.java
C:\javaprog>java stopwaitsender
Enter no of frames to be sent:
4
Frame no 0 is sent
Acknowledgement was Received from receiver
Frame no 1 is sent
Acknowledgement was Received from receiver
Frame no 2 is sent
Acknowledgement was Received from receiver
Frame no 3 is sent
Acknowledgement was Received from receiver

OUTPUT FOR RECEIVER:


C:\javaprog>javac stopwaitreceiver.java
C:\javaprog>java stopwaitreceiver
Frame 0 was received
Frame 1 was received
Frame 2 was received
Frame 3 was received

}
2. STUDY OF SOCKET PROGRAMMING AND CLIENT – SERVER MODEL

Socket Programming
Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that
socket to a server.

When the connection is made, the server creates a socket object on its end of the
communication. The client and the server can now communicate by writing to and reading
from the socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.

The following steps occur when establishing a TCP connection between two computers
using sockets −

 The server instantiates a ServerSocket object, denoting which port number communication is to
occur on.

 The server invokes the accept() method of the ServerSocket class. This method waits until a client
connects to the server on the given port.

 After the server is waiting, a client instantiates a Socket object, specifying the server name and
the port number to connect to.

 The constructor of the Socket class attempts to connect the client to the specified server and the
port number. If communication is established, the client now has a Socket object capable of
communicating with the server.

 On the server side, the accept() method returns a reference to a new socket on the server that is
connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each
socket has both an OutputStream and an InputStream. The client's OutputStream is
connected to the server's InputStream, and the client's InputStream is connected to the
server's OutputStream.

TCP is a two-way communication protocol, hence data can be sent across both streams at
the same time. Following are the useful classes providing complete set of methods to
implement sockets.

ServerSocket Class Methods


The java.net.ServerSocket class is used by server applications to obtain a port and listen
for client requests.

The ServerSocket class has four constructors −

Sr.No. Method & Description

public ServerSocket(int port) throws IOException


1
Attempts to create a server socket bound to the specified port. An exception occurs if the port
is already bound by another application.

public ServerSocket(int port, int backlog) throws IOException

2 Similar to the previous constructor, the backlog parameter specifies how many incoming
clients to store in a wait queue.

public ServerSocket(int port, int backlog, InetAddress address) throws IOException

Similar to the previous constructor, the InetAddress parameter specifies the local IP address to
3
bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the
server to specify which of its IP addresses to accept client requests on.

public ServerSocket() throws IOException

4 Creates an unbound server socket. When using this constructor, use the bind() method when
you are ready to bind the server socket.
If the ServerSocket constructor does not throw an exception, it means that your application
has successfully bound to the specified port and is ready for client requests.

Following are some of the common methods of the ServerSocket class −

Sr.No. Method & Description

public int getLocalPort()


1
Returns the port that the server socket is listening on. This method is useful if you passed in 0
as the port number in a constructor and let the server find a port for you.

public Socket accept() throws IOException

Waits for an incoming client. This method blocks until either a client connects to the server on
2
the specified port or the socket times out, assuming that the time-out value has been set using
the setSoTimeout() method. Otherwise, this method blocks indefinitely.

public void setSoTimeout(int timeout)


3
Sets the time-out value for how long the server socket waits for a client during the accept().

public void bind(SocketAddress host, int backlog)

4 Binds the socket to the specified server and port in the SocketAddress object. Use this method
if you have instantiated the ServerSocket using the no-argument constructor.

When the ServerSocket invokes accept(), the method does not return until a client connects.
After a client does connect, the ServerSocket creates a new Socket on an unspecified port
and returns a reference to this new Socket. A TCP connection now exists between the client
and the server, and communication can begin.

Socket Class Methods


The java.net.Socket class represents the socket that both the client and the server use to
communicate with each other. The client obtains a Socket object by instantiating one,
whereas the server obtains a Socket object from the return value of the accept() method.

The Socket class has five constructors that a client uses to connect to a server −
Sr.No. Method & Description

public Socket(String host, int port) throws UnknownHostException, IOException.

1 This method attempts to connect to the specified server at the specified port. If this constructor
does not throw an exception, the connection is successful and the client is connected to the
server.

public Socket(InetAddress host, int port) throws IOException

2 This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object.

public Socket(String host, int port, InetAddress localAddress, int localPort) throws
IOException.
3
Connects to the specified host and port, creating a socket on the local host at the specified
address and port.

public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws
IOException.
4
This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object instead of a String.

public Socket()
5
Creates an unconnected socket. Use the connect() method to connect this socket to a server.

When the Socket constructor returns, it does not simply instantiate a Socket object but it
actually attempts to connect to the specified server and port.

Some methods of interest in the Socket class are listed here. Notice that both the client and
the server have a Socket object, so these methods can be invoked by both the client and the
server.

Sr.No. Method & Description


public void connect(SocketAddress host, int timeout) throws IOException
1
This method connects the socket to the specified host. This method is needed only when you
instantiate the Socket using the no-argument constructor.

public InetAddress getInetAddress()


2
This method returns the address of the other computer that this socket is connected to.

public int getPort()


3
Returns the port the socket is bound to on the remote machine.

public int getLocalPort()


4
Returns the port the socket is bound to on the local machine.

public SocketAddress getRemoteSocketAddress()


5
Returns the address of the remote socket.

public InputStream getInputStream() throws IOException

6 Returns the input stream of the socket. The input stream is connected to the output stream of the
remote socket.

public OutputStream getOutputStream() throws IOException

7 Returns the output stream of the socket. The output stream is connected to the input stream of the
remote socket.

public void close() throws IOException

8 Closes the socket, which makes this Socket object no longer capable of connecting again to any
server.
InetAddress Class Methods
This class represents an Internet Protocol (IP) address. Here are following usefull methods
which you would need while doing socket programming −

Sr.No. Method & Description

static InetAddress getByAddress(byte[] addr)


1
Returns an InetAddress object given the raw IP address.

static InetAddress getByAddress(String host, byte[] addr)


2
Creates an InetAddress based on the provided host name and IP address.

static InetAddress getByName(String host)


3
Determines the IP address of a host, given the host's name.

String getHostAddress()
4
Returns the IP address string in textual presentation.

String getHostName()
5
Gets the host name for this IP address.

static InetAddress InetAddress getLocalHost()


6
Returns the local host.

String toString()
7
Converts this IP address to a String.
Fig: Socket System Calls in UNIX based Environment
Ex. No: 3 Simulating ARP /RARP protocols

Aim: To write a java program for simulating ARP / RARP protocols.

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
Client Program – ARP

import java.io.*;
import java.net.*;
importjava.util.*;
classClientarp
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",9999);
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);
}
}
}

Server Program – ARP

import java.io.*;
import java.net.*;
import java.util.*;
class Serverarp
{
public static void main(String args[])
{
try
{
ServerSocketobj=new ServerSocket(9999);
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(inti=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);
}
}
}

Ex.No:8(a) ECHO CLIENT AND ECHO SERVER USING TCP SOCKETS

AIM:
To implementation of echo client server using TCP/IP

ALGORITHM:
1. Start the program
2. Include necessary package in java
3. To create a socket in client to server.
4. The client establishes a connection to the server.
5. The client accept the connection and send data to server and the server to replay the echo
message to the client
6. The client communicate the server to send the end of the message
7. Stop the program.
Program :
EServer.java
import java.net.*;
import java.io.*;
public class EServer
{
public static void main(String args[])
{
ServerSocket s=null;
String line;
DataInputStream is;
PrintStream ps;
Socket c=null;
try
{
s=new ServerSocket(9999);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
c=s.accept();
is=new DataInputStream(c.getInputStream());
ps=new PrintStream(c.getOutputStream());
while(true)
{
line=is.readLine();
ps.println(line);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}

EClient.java

import java.net.*;
import java.io.*;
public class EClient
{
public static void main(String arg[])
{
Socket c=null;
String line;
DataInputStream is,is1;
PrintStream os;
try
{
c=new Socket("10.0.200.43",9999);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
os=new PrintStream(c.getOutputStream());
is=new DataInputStream(System.in);
is1=new DataInputStream(c.getInputStream());
while(true)
{
System.out.println("Client:");
line=is.readLine();
os.println(line);
System.out.println("Server:" + is1.readLine());
}

}
catch(IOException e)
{
System.out.println("Socket Closed!");
}
}
}
Ex.No:8 (b) Chat using TCP sockets

AIM:
To write a client-server application for chat using TCP

ALGORITHM: CLIENT
1.start the program
2. Include necessary package in java
3. To create a socket in client to server.
4. The client establishes a connection to the server.
5. The client accept the connection and to send the data from client to server and vice versa
6. The client communicate the server to send the end of the message
7. Stop the program.

ALGORITHM: SERVER
1.start the program
2. Include necessary package in java
3. To create a socket in server to client
4. The server establishes a connection to the client.
5. The server accept the connection and to send the data from server to client and vice versa
6. The server communicate the client to send the end of the message
7. Stop the program.
Client:
import java.net.*;
public class GossipClient
{
public static void main(String[] args) throws Exception
{
Socket sock = new Socket("127.0.0.1", 3000);
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);

// receiving from server ( receiveRead object)


InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

System.out.println("Start the chitchat, type and press Enter key");

String receiveMessage, sendMessage;


while(true)
{
sendMessage = keyRead.readLine(); // keyboard reading
pwrite.println(sendMessage); // sending to server
pwrite.flush(); // flush the data
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
}
}
}
}

Server:
import java.io.*;
import java.net.*;
public class GossipServer
{
public static void main(String[] args) throws Exception
{
ServerSocket sersock = new ServerSocket(3000);
System.out.println("Server ready for chatting");
Socket sock = sersock.accept( );
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(newInputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);

// receiving from server ( receiveRead object)


InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

String receiveMessage, sendMessage;


while(true)
{
if((receiveMessage = receiveRead.readLine()) != null)
{
System.out.println(receiveMessage);
}
sendMessage = keyRead.readLine(); pwrite.println(sendMessage);
pwrite.flush(); }
}
}

8(c) FILE TRANSFER USING TCP

TCPFile Server:

import java.io.*;
import java.net.*;
public class server1
{
public static void main(String args[])throws IOException
{

ServerSocket ServerSocket=null;

try
{
ServerSocket=new ServerSocket(95);
}
catch(IOException e)
{
System.err.println("couldnt listen to port 95");
System.exit(1);
}
Socket clientsocket=null;
try
{
clientsocket=ServerSocket.accept();
System.out.println("connect to:"+clientsocket);
}catch(IOException e)
{
System.err.println("accept failed");
System.exit(1);
}

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


String userinput=null;
while((userinput=din.readLine())==null)
{
System.out.println(userinput);
}
System.out.println("hai"+userinput);
din.close();
try
{
clientsocket=ServerSocket.accept();
System.out.println("connect to"+clientsocket);

}catch(IOException e)
{
System.err.println("accept failed");
System.exit(1);
}
PrintWriter out=new PrintWriter(clientsocket.getOutputStream(),true);
File f=new File(userinput);
if(f.exists());
{
BufferedReader d=new BufferedReader(new FileReader(userinput));
String line;
while((line=d.readLine())!=null)
{
out.write(line+'\n');
out.flush();
}
d.close();
}
out.close();
clientsocket.close();
ServerSocket.close();
}
}

TCP File Client


import java.io.*;
import java.net.*;
import java.util.*;
public class t1
{
public static void main(String args[])throws IOException
{
Socket echosocket=null;
DataInputStream din=null;
try
{
echosocket =new Socket(InetAddress.getLocalHost(),95);
}
catch(UnknownHostException e)
{
System.err.println("Dont know about host");
System.exit(1);
}
String str;
PrintWriter out=new PrintWriter(echosocket.getOutputStream(),true);
DataInputStream in=new DataInputStream(System.in);
System.out.println("enter file name");
String s=in.readLine();
System.out.println("Enter the name to save the file");
String st=in.readLine();
File f=new File(st);
FileWriter fw=new FileWriter(st);
out.write(s);
out.close();
try
{
echosocket=new Socket(InetAddress.getLocalHost(),95);
din=new DataInputStream(echosocket.getInputStream());
}
catch(UnknownHostException e)
{
System.err.println("dont know about host");
System.exit(1);
}
catch(IOException e )
{
System.err.println("couldnt get i/o for the connection");
System.exit(1);
}
String userinput;
while((userinput=din.readLine())!=null)
{
System.out.println(userinput);
str=userinput+'\n';
fw.write(str);
}
fw.close();
din.close();
in.close();
echosocket.close();
}
}
Ex No: 7 Implementation of Subnetting

Aim
To write a program in Java to implement the concept of Subnetting

Algorithm
1. Start the program
2. Read the IP address and Subnet mask
3. Create a subnet by logically grabbing the last bit from the network component of the
address
4. Stop the program

Program

import java.net.*;
import java.util.*;
class IpConverter
{
public static String toHex(String ipAddress)
{
return Long.toHexString(IpConverter.ipToLong(ipAddress));
}

public static long ipToLong(String ipAddress)


{
long result = 0;
String[] atoms = ipAddress.split("\\.");

for (int i = 3; i >= 0; i--)


{
result |= (Long.parseLong(atoms[3 - i]) << (i * 8));
}

return result & 0xFFFFFFFF;


}

public static String longToIp(long ip)


{
StringBuilder sb = new StringBuilder(15);

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


{
sb.insert(0, Long.toString(ip & 0xff));

if (i < 3)
{
sb.insert(0, '.');
}

ip >>= 8;
}

return sb.toString();
}
}
public class subnet
{
public static void main(String[] args)
{
String ip="192.168.0.42";
System.out.println("IP Address : "+ip);
String mask="255.255.255.192";
System.out.println("Mask : "+mask);
long ipL = IpConverter.ipToLong(ip);
long maskL = IpConverter.ipToLong(mask);
System.out.println("Subnetting " + IpConverter.longToIp(ipL & maskL));
}
}

Output

F:\Lab>javac subnet.java
F:\Lab>java subnet
IP Address : 192.168.0.42
Mask : 255.255.255.192
Subnetting 192.168.0.0
Ex.No:6 REMOTE PROCEDURE CALL

Client program

import java.io.*;
import java.net.*;
class cli
{
public static void main(String[] args) throws Exception
{
Socket sock = new Socket("127.0.0.1", 3000);
BufferedReaderkeyRead = new BufferedReader(new InputStreamReader(System.in));
OutputStreamostream = sock.getOutputStream();
PrintWriterpwrite = new PrintWriter(ostream, true);
InputStreamistream = sock.getInputStream();
BufferedReaderreceiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Client ready, type and press Enter key");
String receiveMessage, sendMessage,temp;
while(true)
{
System.out.println("\nEnter operation to perform(add,sub,mul,div)....");
temp = keyRead.readLine();
sendMessage=temp.toLowerCase();
pwrite.println(sendMessage);
System.out.println("Enter first parameter :");
sendMessage = keyRead.readLine();
pwrite.println(sendMessage);
System.out.println("Enter second parameter : ");
sendMessage = keyRead.readLine();
pwrite.println(sendMessage);
System.out.flush();
if((receiveMessage = receiveRead.readLine()) != null)
System.out.println(receiveMessage);
}
}
}

Server program

import java.io.*;
import java.net.*;
classser
{
public static void main(String[] args) throws Exception
{
ServerSocketsersock = new ServerSocket(3000);
System.out.println("Server ready");
Socket sock = sersock.accept( );
BufferedReaderkeyRead = new BufferedReader(new InputStreamReader(System.in));
OutputStreamostream = sock.getOutputStream();
PrintWriterpwrite = new PrintWriter(ostream, true);
InputStreamistream = sock.getInputStream();
BufferedReaderreceiveRead = new BufferedReader(new InputStreamReader(istream));
String receiveMessage, sendMessage,fun;
inta,b,c;
while(true)
{
fun = receiveRead.readLine();
if(fun != null)
System.out.println("Operation : "+fun);
a = Integer.parseInt(receiveRead.readLine());
System.out.println("Parameter 1 : "+a);
b = Integer.parseInt(receiveRead.readLine());
if(fun.compareTo("add")==0)
{
c=a+b;
System.out.println("Addition = "+c);
pwrite.println("Addition = "+c);
}
if(fun.compareTo("sub")==0)
{
c=a-b;
System.out.println("Substraction = "+c);
pwrite.println("Substraction = "+c);
}
if(fun.compareTo("mul")==0)
{
c=a*b;
System.out.println("Multiplication = "+c);
pwrite.println("Multiplication = "+c);
}
if(fun.compareTo("div")==0)
{
c=a/b;
System.out.println("Division = "+c);
pwrite.println("Division = "+c);
}
System.out.flush();
}
}
}

Ex. No: 5 Create a socket for HTTP for web page upload and download

Aim:
To Create a socket for HTTP for web page upload and download by using java
coding.

Algorithm:

Uploading

1. Now we are going to upload an image to a webserver. We will convert a


BufferedImage to byte array in order to send it to server.
2. We are going to use java ByteArrayOutputStream class which can be found under
java.io package. Its syntax is given below:
3. ByteArrayOutputStream baos = new ByteArrayOutputStream();
4. ImageIO.write(image, "jpg", baos);
5. In order to convert the image to byte array , we are going to use toByteArray()
method of ByteArrayOutputStream class. Its syntax is given below:
6. byte[] bytes = baos.toByteArray();
7. Apart from the above method, there are other methods available in the
ByteArrayOutputStream class which are listed below:

Upload

Client.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 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();
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();
}
}

Server.java
import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class Server {
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);
}
}

Output:
CLIENT SIDE OUTPUT
When you execute the client code, the following output appears on client side:

SERVER SIDE OUTPUT


When you execute the server code, the following ouptut apppears on server side:
After receiving the image, the server displays the image as shown below:

Download.java
Algorithm:
Downloading

1. In order to download an image, we are going to use java URL class which can be
found under java.net package. Its syntax is given below:
2. String website = "http://tutorialspoint.com";
3. URL url = new URL(website);
4. Apart from the above method , there are other methods available in URL class which
are listed below:

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 = "digital_image_processing.jpg";
String website ="http://tutorialspoint.com/java_dip/images/"+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());
}
}
}

Output:
When you execute the given above, the following output is seen.

It would download the following image from the server.


Result:
Thus the java program for implementation of RMI has been executed successfully and
the output was verified.

Ex. No: 9(a) Program for Domain Name System (DNS) using UD P

Aim:
To write a java program for Domain Name System (DNS) using UD P

Algorithm:
1. Create a new file. Enter the domain name and address in that file.
2. Establish the connection between client and server.
3. Enter the domain name as input.
4. The IP address corresponding to the domain name will be displayed on the screen
5. Enter the IP address on the screen.
6. The domain name corresponding to the IP address is display on the screen.
7. Stop the program.

Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientdns12
{
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 DOMAIN NAME or IP adress:");
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("IP address or DOMAIN NAME: "+s.trim());
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}Server:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverdns12
{
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();
//System.out.println(s);
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1"};
String
name[]={"www.aptitudeguru.com","www.downloadcyclone.blogspot.com"};
for(int i=0;i<ip.length;i++)
{
if(s.equals(ip[i]))
{
sendbyte=name[i].getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
else if(s.equals(name[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);
}
}
}
Output
I:\ex>java Serverdns12
I:\ex>java Clientdns12
Enter the DOMAIN NAME or IP adress:
165.165.80.80
IP address or DOMAIN NAME: www.aptitudeguru.com

I:\ex>java Clientdns12
Enter the DOMAIN NAME or IP adress:
www.downloadcyclone.blogspot.com
IP address or DOMAIN NAME: 165.165.79.1
Ex.NO:9(b) SMTP(SIMPLE MAIL TRANSFER PROTOCOL)

import javax.mail.internet.*;
import javax.mail.*;
import java.util.*;
public class Smtpass {
public static void main(String[] args) {
try {
Properties props = new Properties( );
props.put("mail.host", "mail.studentwebsite.org");
Session mailConnection =
Session.getInstance(props, null);
Message msg = new MimeMessage(mailConnection);
Address programer = new
InternetAddress("programer@student.com",
"Bill Gates");
Address bhuvangates = new
InternetAddress("webadmin@studentwebsite.org"
);
msg.setContent("Wish You a Happy Christmas
2008", "text/plain");
msg.setFrom(programer);
msg.setRecipient(Message.RecipientType.TO,
bhuvangates);
msg.setSubject("Greetings");
Transport.send(msg);
}
catch (Exception er) {
er.printStackTrace( );
}
}
}

C:\IPLAB>javac Smtpass.java
C:\IPLAB>java Smtpass
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

1. Introduction

Simulation is a very important modern technology. It can be applied to different science,


engineering, or other application fields for different purposes. Computer simulation can be
used to assist the modeling and analysis in many natural systems. Typical application areas
include physics, chemistry, biology, and human-involved systems in economics, finance or
even social science. Other important applications are in the engineering such as civil
engineering, structural engineering, mechanical engineering, and computer engineering.
2. Basic concepts in network simulation

2.1. Simulation and emulation

Simulation is a useful technique since the behavior of a network can be modeled by


calculating the interaction between the different network components using mathematical
formulas.

Network emulation, however, means that network under planning is simulated in order to
assess its performance or to predict the impact of possible changes, or optimizations. The
major difference lying between them is that a network emulator means that end-systems such
as computers can be attached to the emulator and will act exactly as they are attached to a real
network.

2.2 Type of network simulators

Different types of network simulators can be categorized and explained based on some
criteria such as if they are commercial or free, or if they are simple ones or complex ones.

2.3 Commercial and open source simulators

Network simulators name


Commercial OPNET, QualNet
Open source NS2, NS3, OMNeT++, SSFNet, J-Sim

2.4 Overview of current developments

Currently there are many network simulators that have different features in different aspects.
A short list of the current network simulators include OPNET, NS-2, NS-3,
OMNeT++ [OMNeT], REAL[REAL], SSFNet [SSFNet], J-Sim [J-Sim], and
QualNet [QualNet].

2.5 Network Simulator 2 (NS2)

NS2 is one of the most popular open source network simulators. The original NS is a discrete
event simulator targeted at networking research. In this section, we will give a brief
introduction to the NS2 system.

Figure 1: Simplified User's View of NS2


Another feature of NS2 is the event scheduler. In NS2, the event scheduler keeps track of
simulation time and release all the events in the event queue by invoking appropriate network
components. All the network components use the event scheduler by issuing an event for the
packet and waiting for the event to be released before doing further action on the packet.

Steps:
After login into terminal, follow step given below

1. vi filename.tcl
It will open page, there you can write tcl scripts.

2. save file
Press esc-> colon (shift + semicolon) ->wq (save and quit)
It saves the file

3. To run tcl script


ns filename.tcl

Basically NS 2 programming contains the following Steps

1.Create the event scheduler

2.Turn on tracing

3.Creating network

a) Computing setup routing - rtproto


b) Creating transport connection-Agents
c) Creating traffic-Applications

4. Monitoring

a) Visualization using nam

Example1:( CBR over UDP)

set ns [new Simulator] Creatingns simulator object


set tracefile [open out.tr w]
Open trace file
$ns trace-all $tracefile
set nf [open out.nam w]
Open the nam trace file
$ns namtrace-all $nf
proc finish {}
{
global ns tracefilenf
$ns flush-trace
close $nf 'finish' procedure
close $tracefile
exec namout.nam&
exit 0
}
set n0 [$ns node] Create your topology
set n1 [$ns node] - set n0 nodes….
$ns simplex-link $n0 $n1 1Mb 10ms DropTail - $ns duplex-links…
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
set cbr[new Application/Traffic/CBR] Create your agents
$cbr attach-agent $udp0 -transport layer and application layers
set null0 [new Agent/Null] stuff
$ns attach-agent $n1 $null0
$ns connect $udp0 $null0
Scheduling Events
$ns at 1.0 "$cbr start"
- $ns at 1.0 start
$ns at 3.0 "finish"
and at 3.0 finish
$ns run starts the simulation.

Result

Before 1.0ms
After 1.0ms

Result:
Thus we have studied about the Network Simulator.

Ex.No.11a. Perform a case study about the different routing algorithms to select the
network path with its optimum and economical during data transfer

(a) Link State routing

Aim:
To study the link state routing.

Link State routing

Routing is the process of selecting best paths in a network. In the past, the term
routing was also used to mean forwarding network traffic among networks.
In packet switching networks, routing directs packet forwarding through intermediate
nodes. Intermediate nodes are typically network hardware devices such as routers, bridges,
gateways, firewalls, or switches.
The routing process usually directs forwarding on the basis of routing tables which
maintain a record of the routes to various network destinations.
Thus, constructing routing tables, which are held in the router's memory, is very
important for efficient routing.
1. Prefix-Length: where longer subnet masks are preferred (independent of whether it is
within a routing protocol or over different routing protocol)
2. Metric: where a lower metric/cost is preferred (only valid within one and the same routing
protocol)
3. Administrative distance: where a lower distance is preferred (only valid between different
routing protocols)

ii. Flooding

Flooding s a simple routing algorithm in which every incoming packet is sent through
every outgoing link except the one it arrived on Flooding is used in bridging and in systems
such as Usenet and peer-to-peer file sharing and as part of some routing protocols, including
OSPF, DVMRP, and those used in ad-hoc wireless networks.

Algorithm
There are several variants of flooding algorithm. Most work roughly as follows:
1. Each node acts as both a transmitter and a receiver.
2. Each node tries to forward every message to every one of its neighbours except the source
node.

Advantages
 If a packet can be delivered, it will (probably multiple times).
 Since flooding naturally utilizes every path through the network, it will also use the
shortest path.
 This algorithm is very simple to implement.

Disadvantages
 Flooding can be costly in terms of wasted bandwidth. While a message may only have
one destination it has to be sent to every host. In the case of a ping flood or a denial of
service attack, it can be harmful to the reliability of a computer network.
 Messages can become duplicated in the network further increasing the load on the
networks bandwidth as well as requiring an increase in processing complexity to
disregard duplicate messages.
 Duplicate packets may circulate forever, unless certain precautions are taken:
 Use a hop count or a time to live count and include it with each packet. This value
should take into account the number of nodes that a packet may have to pass through
on the way to its destination.
 Have each node keep track of every packet seen and only forward each packet once
 Enforce a network topology without loops

iii . Distance vector

A distance-vector routing protocol requires that a router informs its neighbors of topology
changes periodically. Compared to link-state protocols, which require a router to inform all
the nodes in a network of topology changes, distance-vector routing protocols have less
computational complexity and message overhead.

The term distance vector refers to the fact that the protocol manipulates vectors (arrays) of
distances to other nodes in the network.

Result

Thus The Perform a case study about the different routing algorithms to select the
network path with its optimum and economical during data transfer Was complicated .

Ex. No: 11(b) Distance Vector Routing Algorithm

Aim
To simulate a link failure and to observe distance vector routing protocol in action.

Algorithm:

1. Create a simulator object


2. Set routing protocol to Distance Vector routing
3. Trace packets on all links onto NAM trace and text trace file
4. Define finish procedure to close files, flush tracing and run NAM
5. Create eight nodes
6. Specify the link characteristics between nodes
7. Describe their layout topology as a octagon
8. Add UDP agent for node n1
9. Create CBR traffic on top of UDP and set traffic parameters.
10. Add a sink agent to node n4
11. Connect source and the sink
a. Schedule events as follows:
b. Start traffic flow at 0.5
c. Down the link n3-n4 at 1.0
d. Up the link n3-n4 at 2.0
e. Stop traffic at 3.0
f. Call finish procedure at 5.0
12. Start the scheduler
13. Observe the traffic route when link is up and down
14. View the simulated events and trace file analyze it
15. Stop

PROGRAM:-

set ns [ new Simulator ]


$ns rtproto DV
set nf [ open out.nam w ]
$ns namtrace-all $nf
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam -a out.nam &
exit 0
}
for {set i 0} {$i < 7} {incr i} {

set n($i) [ $ns node ]


}
for {set i 0} {$i < 7} {incr i} {
$ns duplex-link $n($i) $n([expr ($i+1)%7 ]) 1Mb 10ms DropTail
}
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(3) $null0
$ns connect $udp0 $null0
$ns at 0.0 "$n(0) label source"
$ns at 0.0 "$n(3) label destination"
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n(1) $n(2)
$ns rtmodel-at 2.0 up $n(1) $n(2)
$ns at 4.4 "$cbr0 stop"
$ns at 5.0 "finish"
$ns run

OUTPUT:-

You might also like