Академический Документы
Профессиональный Документы
Культура Документы
COIMBATORE - 32
NAME :
REGISTER NO :
CLASS :
2
COIMBATORE 32
_____________________________________________
Place: COIMBATORE
Date:
Submitted for the practical examination of the Anna University conducted on ____________
7 Implementation of Subnetting
AVERAGE MARKS
Staff - In charge
Ex.No:1 Implementation of Stop and Wait Protocol and Sliding Window Protocol
4
AIM
To implement Stop and Wait Protocol and Sliding Window Protocol using Java.
STOP AND WAIT PROTOCOL
ALGORITHM
Step 1: Start.
Step 2 : Invoke the classes ObjectOutputStream and ObjectInputStream with an object to get the input and to
project the output between the sender and receiver
Step 3: Create the socket class for both sender and receiver
Step 4: Split the messages sent from the sender and write on the receiver using writeobj
Step 5: the packets are created by partitioning the messages
Step 6: Terminate the program
PROGRAM
Sender:
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("receiver > "+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();
5
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:
import java.io.*;
import java.net.*;
public class Receiver{
ServerSocket reciever;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,data="";
int i=0,sequence=0;
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());
6
out.writeObject("connected .");
do{
try{
packet=(String)in.readObject();
if(Integer.valueOf(packet.substring(0,1))==sequence){
data+=packet.substring(1);
sequence=(sequence==0)?1:0;
System.out.println("\n\nreceiver >"+packet);
}
else
{
System.out.println("\n\nreceiver>"+packet +" duplicate data");
}
if(i<3){
out.writeObject(String.valueOf(sequence));i++;
}
else{
out.writeObject(String.valueOf((sequence+1)%2));
i=0;
}
}
catch(Exception e){}
}while(!packet.equals("end"));
System.out.println("Data recived="+data);
out.writeObject("connection ended .");
}
catch(Exception e){}
finally{
try{
in.close();
out.close();
reciever.close();
}
catch(Exception e){}
}
}
public static void main(String args[]){
Reciever s=new Reciever();
while(true){
s.run();
}}}
OUTPUT
Sender:
Waiting for Connection....
reciver > connected .
Enter the data to send....
myname
data sent>0m
waiting for ack.....
receiver > packet recieved
7
data sent>1y
waiting for ack.....
receiver > packet recieved
data sent>0n
waiting for ack.....
receiver > packet recieved
data sent>1a
waiting for ack.....
Time out resending data....
data sent>1a
waiting for ack.....
receiver > packet recieved
data sent>0m
waiting for ack.....
receiver > packet recieved
data sent>1e
waiting for ack.....
receiver > packet recieved
All data sent. exiting.
Receiver:
waiting for connection...
Connection established :
receiver >0m
receiver >1y
receiver >0n
receiver >1a
receiver >1a duplicate data
receiver >0m
receiver >1e
Data recived=myname
waiting for connection...
SLIDING WINDOW PROTOCOL
ALGORITHM
Step 1:Start the program.
Step 2:Get the frame size from the user
Step 3:To create the frame based on the user request.
Step 4:To send frames to server from the client side.
Step 5:If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to
client.
Step 6:Stop the program
PROGRAM
Sender:
import java.net.*;
import java.io.*;
import java.rmi.*;
public class slidsender
{
8
AIM
To study about 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.
10
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.
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 port
number to connect to.
The constructor of the Socket class attempts to connect the client to the specified server and 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 twoway communication protocol, so data can be sent across both streams at the same time. There are
following usefull 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:
public ServerSocket(int port) throws IOException-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-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 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-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.
Here are some of the common methods of the ServerSocket class:
public int getLocalPort()- 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 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)- 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)- Binds the socket to the specified server
and port in the SocketAddress object. Use this method if you instantiated the ServerSocket
using the no-argument constructor.
11
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 server, and communication can begin.
Socket Class Methods:
The java.net.Socket class represents the socket that both the client and 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:
public Socket(String host, int port) throws UnknownHostException, IOException
public Socket(InetAddress host, int port) throws IOException
public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException
public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException
public Socket()
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 server
have a Socket object, so these methods can be invoked by both the client and server.
public void connect(SocketAddress host, int timeout) throws IOException-connects the socket to the
specified host.
public InetAddress getInetAddress()- returns the address of the other computer that this socket is
connected to.
public int getPort()-Returns the port the socket is bound to on the remote machine.
public int getLocalPort()-Returns the port the socket is bound to on the local machine.
public SocketAddress getRemoteSocketAddress()-Returns the address of the remote socket.
public InputStream getInputStream() throws IOException- Returns the input stream of the socket.
public OutputStream getOutputStream() throws IOException-Returns the output stream of the socket.
public void close() throws IOException-Closes the socket
InetAddress Class Methods:
This class represents an Internet Protocol (IP) address. Here are following usefull methods which you would
need while doing socket programming:
static InetAddress getByAddress(byte[] addr)
static InetAddress getByAddress(String host, byte[] addr)
static InetAddress getByName(String host)
String getHostAddress()
String getHostName()
static InetAddress InetAddress getLocalHost()
String toString()
Telnet
Clients include Web browsers, chat applications, and email software, among others. Servers include Web,
database, application, chat and email, etc.
A server manages most processes and stores all data. A client requests specified data or processes. The server
relays process output to the client. Clients sometimes handle processing, but require server data resources for
completion.
Computer running a program that makes a request for services is called client machine. A computer running a
program that offers requested services from one or more clients is called server machine. The media for
communication can be wired or wireless network.
Programs running on client machines make requests to a program (often called as server program) running on
a server machine. They involve networking services provided by the transport layer, which is part of the
Internet software stack, often called TCP/IP (Transport Control Protocol/Internet Protocol) stack.
The transport layer comprises two types of protocols,
TCP (Transport Control Protocol) and
UDP (User Datagram Protocol).
The most widely used programming interfaces for these protocols are sockets.
TCP is a connection-oriented protocol that provides a reliable flow of data between two computers. Example
applications that use such services are HTTP, FTP, and Telnet.
UDP is a protocol that sends independent packets of data, called datagrams, from one computer to another
with no guarantees about arrival and sequencing. Example applications that use such services include Clock
server and Ping.
The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.
Port is represented by a positive (16-bit) integer value.
Every computer on the Internet is identified by a unique, 4-byte IP address. This is typically written in dotted
quad format like 128.250.25.158 where each byte is an unsigned value between 0 and 255. This
representation is clearly not user-friendly because it does not tell us anything about the content and then it is
difficult to remember. Hence, IP addresses are mapped to names like www.google.com, which are easier to
remember. Internet supports name servers that translate these names to IP addresses
Sockets and Socket-based Communication
Sockets provide an interface for programming networks at the transport layer. Network communication using
Sockets is very much similar to performing file I/O. In fact, socket handle is treated like file handle.
The streams used in file I/O operation are also applicable to socket-based I/O.
Socket-based communication is independent of a programming language used for implementing it. That
means, a socket program written in Java language can communicate to a program written in non-Java (say C
or C++) socket program.
A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server
listens to the socket for a client to make a connection request. If everything goes well, the server accepts the
connection. Upon acceptance, the server gets a new socket bound to a different port. It needs a new socket
(consequently a different port number) so that it can continue to listen to the original socket for connection
requests while serving the connected client
RESULT
Thus the Socket Programming and Client Server model is clearly analyzed and studied
Ex.No:3
Implementation of simulation of ARP/RARP protocols
AIM
To write a java program for simulating ARP/RARP protocols
ADDRESS RESOLUTION PROTOCOL
ALGORITHM
Step 1: Create a server socket and bind it to port.
Step 2: Listen for new connection and when a connection arrives, accept it.
Step 3: Send servers date and time to the client.
Step 4: Read clients IP address sent by the client.
Step 5: Display the client details.
Step 6: Repeat steps 2-5 until the server is terminated.
Step 7: Create a client socket and connect it to the servers port number.
14
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{ if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n');
break;
}
}
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT
Enter the Logical address(IP):
165.165.80.80
The Physical Address is: 6A:08:AA:C2
REVERSE ADDRESS RESOLUTION PROTOCOL
ALGORITHM
Step 1: Create a server socket and bind it to port.
Step 2: Listen for new connection and when a connection arrives, accept it.
Step 3: Send servers date and time to the client.
Step 4: Read clients physical address sent by the client.
Step 5: Display the client details.
Step 6: Repeat steps 2-5 until the server is terminated.
Step 7: Create a client socket and connect it to the servers port number.
Step 8: Retrieve its IP address using built-in function.
Step 9: Send its address to the server.
Step 10: Display the date & time sent by the server.
Step 11: Close the input and output streams.
Step 12: Close the client socket.
Step 13: Stop.
PROGRAM
Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrarp12
{
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];
16
break;
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT
Enter the Physical address (MAC):
6A:08:AA:C2
The Logical Address is(IP): 165.165.80.80
RESULT
Thus the program for simulating ARP/RARP protocols has been created and the outputs have been verified.
Ex.No:4
Implementation of simulation of PING and TRACEROUTE commands
Aim
To implement the simulation of PING and TRACEROUTE commands using Java.
PING
ALGORITHM
Step 1: start the program.
Step 2: Include necessary package in java.
Step 3: To create a process object p to implement the ping command.
Step 4: declare one BufferedReader stream class object.
Step 5: Get the details of the server
5.1: length of the IP address.
5.2: time required to get the details.
5.3: send packets, receive packets and lost packets.
5.4: minimum ,maximum and average times.
Step 6: print the results.
Step 7: Stop the program
PROGRAM
Client:
import java.io.*;
import java.net.*;
18
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(); }
}
Server:
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();
}
}
OUTPUT
Enter the IP address to the ping:192.168.0.1
Pinging 192.168.0.1: with bytes of data =32
Reply from 192.168.0.11:bytes=32 time<1ms TTL =128
Reply from 192.168.0.11:bytes=32 time<1ms TTL =128
19
RESULT
Thus the implementation for PING and TRACEROUTE has been done and verified successfully.
Ex.No:5
Implementation of socket creation for HTTP for web page upload and download
AIM
To implement socket creation for HTTP for web page upload and download using Java
ALGORITHM
Step 1: Start.
Step 2: Import http web oriented packages.
Step 3: Give the sample html tags for starting page with title
Step 4: Create the objects for the classes socket, BufferedReader and DataOutputStream
Step 5: Get the internet address and port using the Inetaddress and port functions
Step 6: GET and POST methods are used to download and upload the contents
Step 7: Terminate the program
PROGRAM
import java.io.*;
import java.net.*;
import java.util.*;
public class myHTTPServer extends Thread {
static final String HTML_START =
"<html>" +
"<title>HTTP Server in java</title>" +
"<body>";
static final String HTML_END =
"</body>" +
"</html>";
Socket connectedClient = null;
BufferedReader inFromClient = null;
21
RESULT
Thus the program is done for web page upload download and the output has been verified.
Ex.No:6
Implementation of RPC (Remote Procedure Call)
AIM
To implement Remote Procedure Call using Java
ALGORITHM
Step 1: Start.
Step 2: Initialize the BufferedReader class to read the input.
Step 3: Create the Client and Server socket with the address and port number.
Step 4: Get the input words to open the certain application.
Step 5: Exec command to open the respective application from the client side
Step 6: Stop
PROGRAM
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();
}
24
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);
}
}
}
OUTPUT
C:\>java Serverrpc
Client
C:\>java Clientrpc
Enter String
Calc
25
RESULT
Thus the Java program to implement Remote Procedure Call has been executed and the output was verified
successfully.
Ex.No:7
Implementation of Subnetting
AIM
To write a Java program to implement subnetting and find the subnet masks.
ALGORITHM
Step 1: Start the program.
Step 2: calculates the mask using match functions ceil() and log()
Step 3: using the AND and OR operation the addresses and its binary values are obtained.
Step 4: By using appendzero() and substring() function the continuous addresses are found
Step 5: Terminate the program
PROGRAM
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(\\.);
String split_bip[] = new String[4];
String bip = ;
26
for(int i=0;i<4;i++){
split_bip[i] = appendZeros(Integer.toBinaryString(Integer.parseInt(split_ip[i])));
bip += split_bip[i]; }
System.out.println(IP in binary is +bip);
System.out.print(Enter the number of addresses: );
int n = sc.nextInt();
int bits = (int)Math.ceil(Math.log(n)/Math.log(2));
System.out.println(Number of bits required for address = +bits);
int mask = 32-bits;
System.out.println(The subnet mask is = +mask);
int fbip[] = new int[32];
for(int i=0; i<32;i++)
fbip[i] = (int)bip.charAt(i)-48; //convert cahracter 0,1 to integer 0,1
for(int i=31;i>31-bits;i)//Get first address by ANDing last n bits with 0
fbip[i] &= 0; String fip[] = {,,,};
for(int i=0;i<32;i++)
fip[i/8] = new String(fip[i/8]+fbip[i]);
System.out.print(First address is = );
for(int i=0;i<4;i++){
System.out.print(Integer.parseInt(fip[i],2));
if(i!=3)
System.out.print(.); }
System.out.println();
int lbip[] = new int[32];
for(int i=0; i<32;i++)
lbip[i] = (int)bip.charAt(i)-48; //convert cahracter 0,1 to integer 0,1
for(int i=31;i>31-bits;i)//Get last address by ORing last n bits with 1
lbip[i] |= 1;
String lip[] = {,,,};
for(int i=0;i<32;i++)
lip[i/8] = new String(lip[i/8]+lbip[i]);
System.out.print(Last address is = );
for(int i=0;i<4;i++){
System.out.print(Integer.parseInt(lip[i],2));
if(i!=3) System.out.print(.); }
System.out.println(); }
static String appendZeros(String s){
String temp = new String(00000000);
return temp.substring(s.length())+ s; } }
OUTPUT
Enter the ip address: 100.110.150.10
IP in binary is 01100100011011101001011000001010
Enter the number of addresses: 7
Number of bits required for address = 3
The subnet mask is = 29
First address is = 100.110.150.8
Last address is = 100.110.150.15
27
RESULT
Thus a Java program to implement subnetting and find the subnet masks has been executed and the output
was verified successfully.
Ex.No:8 Implementation TCP socket applications Echo client and echo server, Chat and File
Transfer
AIM
To implement TCP socket applications Echo client and echo server, Chat and File Transfer using Java
ECHO CLIENT AND SERVER
ALGORITHM
Step 1: start
Step 2: Include the necessary packages
Step 3: Create the socket for client and server with port number
Step 4: the message is sent from the server
Step 5: the client reads the message using the function readline() and echoes the message
Step 6: Terminate the program
PROGRAM
Client:
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;
28
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);
}
Server:
import java.io.*;
import java.net.*;
public class echoserver1
{
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);
29
dout.writeBytes(""+m1);
dout.writeBytes("\n");
}
}
dout.close();
usr_inp.close();
c.close();
}
}
OUTPUT
Server
C:\Program Files\Java\jdk1.5.0\bin>java echoserver1
C:\Program Files\Java\jdk1.5.0\bin>
Client
C:\Program Files\Java\jdk1.5.0\bin>java echoclient
Client:
Hai Server
Server:Hai Server
Client:
Hello
Server:Hello
Client:
end
Server:end
Client:
ds
CHAT CLIENT AND CHAT SERVER
ALGORITHM
Step 1: Start
Step 2: initiate the classes Socket, DataInputStream and DataOutputStream with an object
Step 3: connect the client and server sockets through the address and the port number
Step 4: Writebytes() is used for writing the data parallel to client and the server
Step 5: readline() used fot reading the input data being communicated
Step 6: Terminate the program
PROGRAM
Client:
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());
30
}
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:
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);
31
f.close();
dout.writeBytes("-1\n");
}}
catch(Exception e)
{ System.out.println(e);}
}
}
OUTPUT
File content
Computer networks
Transmission
Security
cryptosystems
client
Enter the file name:
sample.txt
server
Computer networks
Transmission
Security
cryptosystems
client
Enter the new file name:
net.txt
Computer networks
Transmission
Security
cryptosystems
Destination file
Computer networks
Transmission
Security
cryptosystems
34
RESULT
Thus the program for implementing TCP socket applications Echo client and echo server, Chat and File
Transfer using Java have been done successfully.
Ex.No:9
Implementation of TCP and UDP sockets applications DNS, SNMP and File Transfer
AIM
To implement TCP and UDP sockets applications DNS, SNMP and File Transfer.
DOMAIN NAME SERVICE
ALGORITHM
Step 1: Start the program
Step 2: import the package net.*
Step 3: give the host names and assigns the address virtually
Step 4: Create the datagramsocket for client and server
Step 5: Returns the host name with respect to host address assigned to them
Step 6: Terminate the program
PROGRAM
Server:
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) {
35
OUTPUT
$ javac udpdnsserver.java
$ java udpdnsserver
Press Ctrl + C to Quit
Request for host yahoo.com
Request for host cricinfo.com
Request for host youtube.com
Client
$ javac udpdnsclient.java
$ java udpdnsclient
Enter the hostname : yahoo.com
IP Address: 68.180.206.184
$ java udpdnsclient
Enter the hostname : cricinfo.com
IP Address: 80.168.92.140
$ java udpdnsclient
Enter the hostname : youtube.com
IP Address: Host Not Found
SIMPLE NETWORK MANAGEMENT PROTOCOL
ALGORITHM
Step 1: Start
Step 2: include the necessary packages for snmp
Step 3: Create object for snmpmanager with port number and address
Sep 4: Obatin the system anme and description with respect to OID value given
Step 5: Listen() method is used for listening to the users when communication takes place
Step 6: Responseevent() method is used to handle the arrival of multiple OIDs
Step 7: Target() method is used to identify that where the data should be fetched
Step 8: Obtain the answer and terminate the program
PROGRAM
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;
public SNMPManager(String add)
{
address = add;
public static void main(String[] args) throws IOException {
SNMPManager client = new SNMPManager("udp:127.0.0.1/161");
37
client.start();
String sysDescr = client.getAsString(new OID(".1.3.6.1.2.1.1.1.0"));
System.out.println(sysDescr);
}
private void start() throws IOException {
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new
Snmp(transport);
transport.listen();
}
public String getAsString(OID oid) throws IOException {
ResponseEvent event = get(new OID[] { oid });
return event.getResponse().get(0).getVariable().toString();
}
public ResponseEvent get(OID oids[]) throws IOException {
PDU pdu = new PDU();
for (OID oid : oids) {
pdu.add(new VariableBinding(oid));
}
pdu.setType(PDU.GET);
ResponseEvent event = snmp.send(pdu, getTarget(), null);
if(event != null) {
return event;
}
throw new RuntimeException("GET timed out");
}
private Target getTarget() {
Address targetAddress = GenericAddress.parse(address);
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
return target;
}}
OUTPUT
Hardware: x86 Family 6 Model 23 Stepping 10 AT/AT COMPATIBLE Software:
Windows 2007 Version 5.1 (Build 2600 Multiprocessor Free)
FILE TRANSFER
ALGORITHM
Step 1: Start
Step 2: Create the client and server socket with address and port numbers
Step 3: readline() is used to read the input file data
Step 4: writebytes() is used to write the data from one file to another file
Step 5: File Reader class is used to create the file to the specific folder
Step 6: Terminate the program
PROGRAM
Client:
Import java.io.*;
38
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);
39
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);}
}
}
OUTPUT
File content
Computer networks
client
Enter the file name: sample.txt
server
Computer networks
client
Enter the new file name: net.txt
Computer networks
Destination file
Computer networks
40
RESULT
Thus the Java program is done to create TCP and UDP sockets applications DNS, SNMP and File Transfer
and verified successfully
Ex.No:10 Study of Network Simulator and simulation of congestion Control Algorithms using
NS
AIM
To Study of Network simulator (NS).and Simulation of Congestion Control
Algorithms using network simulator.
NET WORK SIMULATOR (NS2)
Ns overview
Ns programming: A Quick start
Case study I: A simple Wireless network
Case study II: Create a new agent in Ns
Ns overview
Ns Status
Periodical release (ns-2.26, Feb 2003)
Platform support
FreeBSD, Linux, Solaris, Windows and Mac
Ns functionalities
Routing, Transportation, Traffic sources,Queuing disciplines, QoS
Wireless
Ad hoc routing, mobile IP, sensor-MAC Tracing, visualization and various utilities NS(Network
Simulators)
Most of the commercial simulators are GUI driven, while some network simulators are CLI driven. The
network model / configuration describes the state of the network (nodes,routers, switches, links) and the
events (data transmissions, packet error etc.). An important output of simulations are the trace files. Trace
files log every packet, every event that occurred in the simulation and are used for analysis. Network
simulators can also provide other tools to facilitate visual analysis of trends and potential trouble spots.
Most network simulators use discrete event simulation, in which a list of pending "events" is stored, and
those events are processed in order, with some events triggering future events such as the event of the
arrival of a packet at one node triggering the event of the arrival of that packet at a downstream node.
Simulation of networks is a very complex task. For example, if congestion is high, then estimation of the
average occupancy is challenging because of high variance. To estimate the likelihood of a buffer
overflow in a network, the time required for an accurate answer can be extremely large. Specialized
techniques such as "control variates" and "importance sampling" have been developed to speed
simulation.
41
the total data received to the end to end delay. Throughput is an important factor which directly impacts
the network performance
Delay
Delay is the time elapsed while a packet travels from one point e.g., source premise or network ingress to
destination premise or network degrees. The larger the value of delay, the more difficult it is for transport
layer protocols to maintain high bandwidths. We will calculate end to end delay
Queue Length
A queuing system in networks can be described as packets arriving for service, waiting for service if it is
not immediate, and if having waited for service, leaving the system after being served. Thus queue length
is very important characteristic to determine that how well the active queue management of the
congestion control algorithm has been working.
NS2 Execution
The overall simulation procedure in NS is shown below. NS is composed of OTcl Script and Interpreter. NS
simulation results can be observed through graphs by analyzing the trace file or viewing animations with
NAM.
$ ns filename.tcl
NS2 Program Elements
Event Scheduler
a Creating event scheduler
set ns [new Simulator]
b Schedule events
$ns at time " event"
c Start scheduler
$ns run
Creating Network
a Create set of Nodes
set n0 [$ns node]
set n1 [$ns node]
b Create links and queuing
$ns duplex-link $n0 $n1 bandwidth delay queue_type
Bandwidth is generally in MB
Delay is generally in ms
Queue type is either DropTail, RED, CBQ, FQ, SFQ, etc
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
c Layout
$ns duplex-link-op $n0 $n2 orient position
where position is either right, right-up, right-down, left, leftup, left-down, up, down
d Marking flows
$ns color 1 Blue
$ns color 2 Red
$udp0 set class_ 1
$udp1 set class_ 2
Tracing
a NAM Trace all links (must succeed scheduler creation)
set nf [open out.nam w]
$ns namtrace-all $nf
b Trace all links (must succeed scheduler creation)
set tf [open out.tr w]
$ns trace-all $tf
43
RESULT
Thus the study of network simulator and simulation of TCP congestion control algorithm is done and verified
successfully.
Ex.No:11 Case study of Routing Algorithms Link State Routing, Flooding and Distant Vector
Routing
AIM
To make a case study of of Routing Algorithms Link State Routing, Flooding and Distant Vector Routing and
implement using NS2 Network Simulator .
LINK STATE ROUTING
ALGORITHM
Step 1: Create a simulator object
Step 2: Set routing protocol to Link State routing
Step 3: Trace packets on all links onto NAM trace and text trace file
Step 4: Define finish procedure to close files, flush tracing and run NAM
Step 5: Create eight nodes
Step 6: Specify the link characteristics between nodes
Step 7: Describe their layout topology as a octagon
Step 8: Add UDP agent for node n1
Step 9: Create CBR traffic on top of UDP and set traffic parameters.
Step 10: Add a sink agent to node n4
Step 11: Connect source and the sink
Step 12: Schedule events as follows:
a. Start traffic flow at 0.5
b. Down the link n3-n4 at 1.0
c. Up the link n3-n4 at 2.0
d. Stop traffic at 3.0
e. Call finish procedure at 5.0
Step 13: Start the scheduler
Step 14: Observe the traffic route when link is up and down
Step 15: View the simulated events and trace file analyze it
Step 16: Stop
PROGRAM
#Link State routing protocol ls.tcl
#Create a simulator object
set ns [new Simulator]
#Use Link State routing
$ns rtproto LS
#Open the nam trace file
set nf [open out.nam w]
$ns namtrace-all $nf
# Open tracefile
set nt [open trace.tr w]
$ns trace-all $nt
#Define 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
48
close $nf
#Execute nam on the trace file
exec nam -a out.nam &
exit 0
}
# Create 8 nodes
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]
set n8 [$ns node]
# Specify link characterestics
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link $n4 $n5 1Mb 10ms DropTail
$ns duplex-link $n5 $n6 1Mb 10ms DropTail
$ns duplex-link $n6 $n7 1Mb 10ms DropTail
$ns duplex-link $n7 $n8 1Mb 10ms DropTail
$ns duplex-link $n8 $n1 1Mb 10ms DropTail
# Specify layout as a octagon
$ns duplex-link-op $n1 $n2 orient left-up
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n4 $n5 orient right
$ns duplex-link-op $n5 $n6 orient right-down
$ns duplex-link-op $n6 $n7 orient down
$ns duplex-link-op $n7 $n8 orient left-down
$ns duplex-link-op $n8 $n1 orient left
#Create a UDP agent and attach it to node n1
set udp0 [new Agent/UDP]
$ns attach-agent $n1 $udp0
#Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
#Create a Null agent (a traffic sink) and attach it to node n4
set null0 [new Agent/Null]
$ns attach-agent $n4 $null0
#Connect the traffic source with the traffic sink
$ns connect $udp0 $null0
#Schedule events for the CBR agent and the network dynamics
49
FLOODING
ALGORITHM
Step 1: Create a simulator object
Step 2: Set the options for flooding
Step 3: Trace packets on all links onto NAM trace and text trace file
Step 4: Define finish procedure to close files, flush tracing and run NAM
Step 5: Create nodes
Step 6: Specify the link characteristics between nodes
Step 7: Describe their layout topology
Step 8: Add UDP agent
Step 9: Create CBR traffic on top of UDP and set traffic parameters.
Step 10: Add a sink agent to node
Step 11: Connect source and the sink
Step 12: Schedule events.
Step 13: Start the scheduler
Step 14: Observe the traffic route when link is up and down
Step 15: View the simulated events and trace file analyze it
Step 16: Stop
PROGRAM
#Flooding routing protocol flood.tcl
# Define options
set val(chan) Channel/WirelessChannel
set val(prop) Propagation/FreeSpace
set val(netif) Phy/WirelessPhy
set val(mac) Mac/802_11
set val(ifq) Queue/DropTail/PriQueue
set val(ll) LL
set val(ant) Antenna/OmniAntenna
set val(x) 670
set val(y) 670
set val(ifqlen) 50
set val(seed) 0.0
set val(adhocRouting) FLOODING
set val(nn) 2
set val(stop) 200.0
# create simulator instance
set ns_ [new Simulator]
# setup topography object
set topo [new Topography]
#use new trace format
$ns_ use-newtrace
# create trace object for ns and nam
set tracefd [open flood.tr w]
$ns_ trace-all $tracefd
set namtrace [open flood.nam w]
$ns_ namtrace-all-wireless $namtrace $val(x) $val(y)
# define topology
51
RESULT
Thus the experiment is done to make a case study of Routing Algorithms Link State Routing, Flooding and
Distant Vector Routing and implement using NS2 Network Simulator.
Ex.No:12 Implementation of CSMA/CD in NS2
56
AIM
To implement CSMA/CD using Network Simulator 2.
ALGORITHM
Step 1: Create a simulator object
Step 2: Set different color for TCP and UDP traffic.
Step 3: Trace packets on all links onto NAM trace and text trace file
Step 4: Define finish procedure to close files, flush tracing and run NAM
Step 5: Create six nodes
Step 6: Specify the link characteristics between nodes
Step 7: Create a LAN with nodes n3, n4, n5 part of it
Step 8: Describe layout topology of nodes
Step 9: Add UDP agent for node n1
Step 10: Create CBR traffic on top of UDP and set traffic parameters.
Step 11: Add a null agent to node and connect it to udp source
Step 12: Add TCP agent for node n0
Step 13: Create FTP traffic for TCP and set its parameters
Step 14: Add a sink to TCP and connect it to source
Step 15: Schedule events as follows:
a. Start CBR & FTP traffic flow at 0.3 and 0.8 respectively
b. Stop CBR & FTP traffic flow at 7.5 and 7.0 respectively
c. Call finish procedure at 8.0
Step 16: Start the scheduler
Step 17: Observe the transmission of packets over LAN
Step 18: View the simulated events and trace file analyze it
Step 19: Stop
PROGRAM
#Lan simulation mac.tcl
set ns [new Simulator]
#define color for data flows
$ns color 1 Purple
$ns color 2 MAgenta
#open tracefile
set tracefile1 [open out.tr w]
$ns trace-all $tracefile1
#open nam file
set namfile [open out.nam w]
$ns namtrace-all $namfile
#define the finish procedure
proc finish {} {
global ns tracefile1 namfile
$ns flush-trace
close $tracefile1
close $namfile
exec nam out.nam &
exit 0
}
#create six nodes
set n0 [$ns node]
set n1 [$ns node]
57
RESULT
Thus the CSMA/CD using Network Simulator has been implemented successfully.