CN Lab Manuals 2019 (1) - Converted-1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 114

ANNAMALAI UNIVERSITY

FACULTY OF ENGINEERING AND TECHNOLOGY

DEPARTMENT OF INFORMATION TECHNOLOGY

(DEC2020 - MAY 2021)

ITCP409-COMPUTER NETWORKS
LABORATORY MANUALS

IV SEMESTER

P a g e | 1 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


SYLLABUS

1. Implementation of a socket program for Echo/Ping/Talk commands.


2. Creation of a socket between two computers and enable file transfer between them.
Using (a.) TCP (b.) UDP
3. Implementation of a program for Remote Command Execution (Two M/Cs may be used).
4. Implementation of a program for CRC and Hamming code for error handling.
5. Writing a code for simulating Sliding Window Protocols.
6. Create a socket for HTTP for web page upload & Download.
7. Write a program for TCP module Implementation. (TCP services).
8. Write a program to implement RCP (Remote Capture Screen).
9. Implementation (using NS2/Glomosim) and Performance evaluation of the following
routing protocols:
a. Shortest path routing
b. Flooding
c. Link State
d. Hierarchical
10. Broadcast /Multicast routing.
11. Implementation of ARP.
12. Throughput comparison between 802.3 and 802.11.
13. Study of Key distribution and Certification schemes.
14. Design of an E-Mail system
15. Implementation of Security Compromise on a Node using NS2 / Glomosim
16. Implementation of Various Traffic Sources using NS2 / Glomosim

P a g e | 2 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


TABLE OF CONTENTS

EX.NO TITLE OF EXPERIMENTS PAGE NO


1. STUDY OF COMMANDS FOR SOCKET PROGRAMMING 5

BASIC PROGRAMS
2. 2.1 GENERATE RANDOM PORT NUMBER 11

2.2 CLIENT IP ADDRESS 13

TCP COMMUNICATION
3. 3.1 ONE WAY COMMUNICATION 15

3.2 TWO WAY COMMUNICATION 19

SOCKET COMMANDS
4.1 ECHO COMMAND 24
4.
4.2 PING COMMAND 28

4.3 TALK COMMAND 32

FILE TRANSFER
5. 5.1 TCP 37

5.2 UDP 41
6. REMOTE COMMAND EXECUTION 44

ERROR CHECKING
7. 7.1 CYCLIC REDUNDANCY CHECK 48

7.2 HAMMING CODE 55


8. SIMULATION OF SLIDING WINDOW PROTOCOL 60
9. HTTP WEBPAGE UPLOAD AND DOWNLOAD 64
10. IMPLEMENTATIONOFRCP(REMOTESCREENCAPTURE) 69

ROUTING
11.1 SHORTEST PATH ROUTING 74
11. 11.2 FLOODING ROUTING 77

11.3 MULTICAST ROUTING 84

11.4 BROADCAST ROUTING 88


12. ADDRESS RESOLUTION PROTOCOL 91
13. THROUGHPUT COMPARISON BETWEEN 802.3 & 802.11 95
14. KEY DISTRIBUTION AND CERTIFICATION SCHEMES 100
15. DESIGN OF E-MAIL SYSTEM 104

P a g e | 4 COMPUTER DEPARTMENT OF IT, FEAT, AU


EX.NO: 1 STUDY OF COMMANDS FOR SOCKET PROGRAMMING

Aim
To study the commands of the socket programming.

Sockets
A socket is one end-point of a two-way communication link between two programs running on
the network. Socket classes are used to represent the connection between a client program and a server
program.
The java.net package provides two classes--Socket and ServerSocket--that implement the
client side of the connection and the server side of the connection, respectively.
They connect to them on published ports when the ServerSocket created it will register itself
with the system as having an internet in client connection. The constructor for the ServerSocket having
client‟s connection it can leave pending before it should be refers connections.

Port
The TCP and UDP protocols use ports to map incoming data to a particular process running on a
computer. Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The
port numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services
such as HTTP and FTP and other system service (called well-known ports).

TCP/IP Protocol
TCP provides a point-to-point channel for applications that require reliable communications.
The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of
applications that require a reliable communication channel. The order in which the data is sent and
received over the network is critical to the success of these applications. When HTTP is used to read
from a URL, the data must be received in the order in which it was sent. Otherwise, you end up with a
jumbled HTML file, a corrupt zip file, or some other invalid information.

Stream Communication
The stream communication protocol, transfer control protocol, TCP is a connection-oriented
protocol. In order to do communication over the TCP protocol, a connection must first be established
between the pair of sockets. While one of the sockets listens for a connection request (server), the other
asks for a connection. Once two sockets have been connected, they can be used to transmit data in both
directions.

P a g e | 5 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Creating TCP Servers
1. Create a ServerSocket attached to a port number.
ServerSocket server = new ServerSocket(port);
2. Wait for connections from clients requesting connections to that port.
Socket channel = server.accept();
3. Get input and output streams associated with the socket.
out = new PrintWriter (channel.getOutputStream());
reader = new InputStreamReader (channel.getInputStream());
in = new Scanner (reader);
String data = in.readLine();
out.println("Hey! ");

Creating TCP Clients

1. Create a Socket object attached to a remote host, port.


Socket client = new Socket(host, port);
2. Get input and output streams associated with the socket.
out = new PrintWriter (client.getOutputStream());
reader = new InputStreamReader
(client.getInputStream()); in = new Scanner (reader);
out.println("Hi!”);
String data = in.readLine();

UDP
The UDP protocol provides for communication that is not guaranteed between two applications on
the network. UDP is not connection-based like TCP. Rather, it sends independent packets of data,
called datagrams, from one application to another. Sending datagrams is much like sending a letter
through the postal service: The order of delivery is not important and is not guaranteed, and each
message is independent of any other.

Datagram Communication
The datagram communication protocol, user datagram protocol, is a connectionless protocol,
meaning that each time you send datagrams, you also need to send the local socket descriptor and the
receiving socket‟s address.

P a g e | 6 COMPUTER DEPARTMENT OF IT, FEAT, AU


Creating UDP Servers
1. Create a DatagramSocket attached to a port.
int port = 1234;
DatagramSocket socket = new DatagramSocket(port);
2. Allocate space to hold the incoming packet, and create an instance ofDatagramPacket to hold
the incoming data.
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
3. Block until a packet is received, then extract the information you need from thepacket.
socket.receive(packet);
InetAddress remoteHost = packet.getAddress();
int remotePort = packet.getPort();
byte[] data = packet.getData();

Creating UDP Clients


1. First allocate space to hold the data we are sending and create an instance of
byte[] buffer = new byte[1024];
int port = 1234;
InetAddress host = InetAddress.getByName("magelang.com");
DatagramPacket p = new DatagramPacket(buffer, buffer.length,host,
port);
2. Create a DatagramSocket and send thepacket using
this socket. DatagramSocket socket = new
DatagramSocket(); socket.send(p);
InetAddresslocalHostname =socket.getLocalAddress();
int localPort = socket.getLocalPort();

ServerSocket Constructor and Methods


The java.net.ServerSocket class is used by server applications to obtain a port and listen for client
requests.
CONSTRUCTOR DESCRIPTION
ServerSocket(int port) Create a server socket bound to the specified port.
The backlog parameter specifies how many incoming clients
ServerSocket(int port, int backlog)
to store in a wait queue.
The inetaddress specifies the local IP address to bind to
ServerSocket(int port, int backlog, and used for servers that may have multiple IP addresses,
InetAddress address) allowing the server to specify which of its IP addresses to
accept client requests on.
Creates an unbound server socket. When using this
ServerSocket() constructor, use the bind() method when you are ready to
bind the server socket.

P a g e | 7 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


METHODS DESCRIPTION
getLocalPort() Returns the port that the server socket is listening on.
Waits for an incoming client. This method blocks until
either a client connects to the server on the specified port or
Socket.accept()
the socket times out, assuming that the time-out value has
been
set using the setSoTimeout() method.
Sets the time-out value for how long the server socket waits
setSoTimeout(int timeout)
for a client during the accept().
bind(SocketAddress host, int Binds the socket to the specified server and port in the
backlog) SocketAddress object.

Socket Constructor and Methods


The creation of socket is done through the constructor of the class socket. The creation of the
socket objects implicates establishes a connection between the client and the server.
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.

CONSTRUCTOR DESCRIPTION
Socket(String host, int port) Connect to the specified server at the specified port.
Socket(InetAddress host, int port) The host is denoted by an inetaddress object.
Socket(String host, int port, Connects to the specified host and port, creating a socket
InetAddresslocalAddress, intlocalPort) on the local host at the specified address and port.
Socket(InetAddress host, int port, The host is denoted by an inetaddress object instead of a
InetAddresslocalAddress, intlocalPort) String
Creates an unconnected socket. Use the connect()
Socket() method
to connect this socket to a server.

METHODS DESCRIPTION
Connects the socket to the specified host. This method is needed
connect(SocketAddress host,
only when you instantiated the Socket using the no-argument
int timeout)
constructor.
Returns the address of the other computer that this socket is
InetAddressgetInetAddress()
connected to.
getPort() Returns the port the socket is bound to on the remote machine.
getLocalPort() Returns the port the socket is bound to on the local machine.
Closes the socket, which makes this Socket object no longer
close()
capable of connecting again to any server.

P a g e | 8 COMPUTER DEPARTMENT OF IT, FEAT, AU


Inet Addressing
An internet is a 32 bit number that uniquely identifies each computer on the net and has
sequence of four number between 0 and 255 separated by the data. Not randomly assigned, they are
hierarchically assigned.
Class A 1.0.0.0 to 126.255.255.255 About 16 million IP addresses in a class Adomain.
Class B 128.1.0.0 to 191.254.255.255 About 64 thousand IPaddresses in class B domain.
Class C 192.0.1.0 to 223.255.254.255 256 IP addresses in a class C domain.
Class D 224.0.0.1 to 239.255.255.255 denote multicast groups.
Class E 240.0.0.0 to 254.255.255.255 Reserved for future use.

Address Types
Unicast
An identifier for a single interface. A packet sent to a unicast address is delivered to the
interface identified by that address.

The Unspecified Address


Also called anylocal or wildcard address. It must never be assigned to any node. It indicates the
absence of an address. One example of its use is as the target of bind, which allows a server to accept a
client connection on any interface, in case the server host has multiple interfaces.The unspecified
address must not be used as the destination address of an IP packet.

The Loopback Addresses


This is the address assigned to the loopback interface. Anything sent to this IP address loops
around and becomes IP input on the local host. This address is often used when testing a client.

Multicast
An identifier for a set of interfaces (typically belonging to different nodes). A packet sent to a
multicast address is delivered to all interfaces identified by that address.

METHODS DESCRIPTION
InetAddressgetByAddress(byte[] addr) Returns an InetAddress object given the raw IP address.
InetAddressgetByAddress(String host, Create an InetAddress based on the provided host name
byte[] addr) and IP address.
InetAddressgetByName(String host) Determines the IP address of a host, given the host's
name.
getHostAddress() Returns the IP address string in textual presentation.
getHostName() Gets the host name for this IP address.
InetAddressInetAddressgetLocalHost() Returns the local host.

P a g e | 9 COMPUTER DEPARTMENT OF IT, FEAT, AU


Result
Thus the study of the commands for the Socket Programming is done.

P a g e | 10 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 2.1 GENERATE RANDOM PORT NUMBER

Aim
To write a java program to generate random port number.

Algorithm
1. Start the program
2. Import the java.net and java.iopackages.
3. Declare a new class called RandomPort.
4. Inside RandomPort, declare an object of class ServerSocket, called “server”, with port number 0.
5. Display a message saying which port the object “server” runs on by getting the port number
using the method getLocalPort().
6. Catch and handle any exceptions thrown.
7. Stop the program

Source Code
import java.net.*;
import java.io.*;
class RandomPort
{
public static void main(String args[]) throws IOException
{
System.out.println("GENERATING RANDOM PORT NUMBERS");
// Create a server socket bound to the specified port
ServerSocket Server = new ServerSocket(0);
// ServerSocket Server = new ServerSocket(65536); /* port range out of range
exception */
//Returns the port the socket is bound to on the local machine
System.out.println("This server runs on port "+ Server.getLocalPort());
}
}

P a g e | 11 COMPUTER NETWORKS LABORATORY DEPARTMENT OF IT, FEAT, AU


Output

Result
Thus the Random Port Number generated program is executed and output verified.

P a g e | 12 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 2.2 CLIENT IP ADDRESS

Aim
To write a java program for Finding an IP address of client.

Algorithm
1. Start the program
2. Import the java.net, java.io, and java.util packages.
3. Declare a new class called “IPAddress”.
4. Create an object for the InetAddress Method to get the LocalHost IP Address.
5. Display the message received, which is the local host Inet Address.
6. Stop the program

Source Code
import java.net.*;
import java.io.*;
class IPAddress
{
public static void main(String args[])throws UnknownHostException
{
System.out.println("DISPLAYING HOST NAME & IP ADDRESS");
// InetAddress to get the IP address of any host
// InetAdddress containing local host name and address
InetAddress ip = InetAddress.getLocalHost();
System.out.println("Host Name & IP Address : " + ip);

// it returns the instance of InetAddress containing LocalHost IP and


name InetAddress ip1 = InetAddress.getByName("www.yahoomail.com");
System.out.println("Name of DNS System : " + ip1);

// it returns the host name of the IP address


String sysName = ip.getHostName();
System.out.println("Host Name :"+
sysName);

// it returns the IP address in string format


String sysAddr = ip.getHostAddress();
System.out.println("Host Address :"+
sysAddr);
}
P a g e | 13 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU
}

P a g e | 14 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output

Result
Thus the java program for Finding IP address of the system has been executed and successfully.

P a g e | 15 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 3.1 ONE WAY COMMUNICATION USING TCP

Aim
To write a java program for one way communication using TCP.

Algorithm
Server Program
1. Start
2. Import the java.net and java.iopackages.
3. Declare a new class called “Server”.
4. Within class “Server”, create a ServerSocket object called “ss” with the port number 8000.
5. Create a Socket object called “soc” by using the accept() method, which listens for a connection
to be made to this server socket and accepts it.
6. Create a new Scanner object, which acts as an input stream to the server from the client.
7. Create a new PrintStream object, which acts as an output stream to the client from the server.
8. Display the message “Server ready...” on the server window.
9. Repeat the following steps:
a) Prompt for the message to be sent from server to client.
b) Read in the message to be sent from the user.
c) Send the message to the client using the PrintStream object.
d) If the message equals the string “bye”, then close the input and output streams and exit
the loop.
10. Stop

Client Program
1. Start
2. Import the java.net, java.io, and java.util packages.
3. Create a new class called“Client”.
4. Inside “Client”, create a new Socket object called “soc” with port number 8000.
5. Create a new Scanner object which acts as the input stream to the client from the server.
6. Repeat the following steps:
a) Read in the input from the server to the client using the Scanner object.
b) Display the message received.
c) If the string received equals “end”, then close the input and output streams and exit the loop.
7. Stop

P a g e | 16 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Source Code
Server.java
import java.io.*;
import java.net.*;
import java.util.*;
class Server
{
public static void main(String a[])throws IOException
{
String str;
ServerSocket ss = new ServerSocket(8000);
// Opens the socket
Socket soc = ss.accept();
Scanner in = new Scanner(System.in);
PrintStream socOut = new PrintStream(soc.getOutputStream());
System.out.print("Server ready \n");
System.out.println("SERVER WILL SEND A MESSAGE TO A CLIENT");
while(true)
{
System.out.println("Enter Message to Send:");
// Reads the input from keybroad
str = in.next();
//checksforbyemessage
socOut.println(str);
if(str.equals("bye"))
{
break;
}
}
}
}

P a g e | 17 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Client.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
class Client
{
public static void main(String args[])throws IOException
{
String str;
Socket soc = new Socket("localhost",8000);
// Used to get input from keyword
Scannerin= newScanner(newInputStreamReader(soc.getInputStream()));
System.out.println("CLIENT WAITING FOR A MESSAGE FROM THE SERVER");
try
{
while(true)
{
// Reads the input from keybroad
str = in.next();
System.out.println("Message Received: " + str);
if(str.equals("bye"))
{
break;
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

P a g e | 18 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output
Server Side

Client Side

Result

Thus the java for TCP One way communication has been executed successfully.

P a g e | 19 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 3.2 TWO WAY COMMUNICATION USING TCP

Aim
To write a java program for two way communication using TCP.

Algorithm
Server Program
1. Start
2. Import the java.net and java.iopackages.
3. Create a new class called“TwoServer”.
4. Inside class “TwoServer”, create a new ServerSocket object called “ss” with the port number 8000.
5. Create a new Socket object called “ss” by using the accept() method, which listens for a
connection to be made to this server socket and accepts it.
6. Create a new PrintStream object which acts as an output stream from the server to the client.
7. Create a new Scanner object which acts as an input stream from the client to the server.
8. Display the prompt “Server isready”.
9. Repeat the following steps:
a) Prompt and read in the message from the user to be sent to the client from the server.
b) Send the message to the client using the PrintStream object.
c) If the message equals the string “bye”, then close the input and output streams and exit the loop.
d) Else, read in the message from the client using the Scanner object.
e) Display the message received from the client to the user.
f) If the message received equals the string “bye”, then close the input and output streams and
exit the loop.
10. Stop.

P a g e | 20 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Client Program
1. Start
2. Import the java.net and java.iopackages.
3. Create a new class called“TwoClient”.
4. Inside “TwoClient”, create a new Socket object called “soc” with the port number 8000.
5. Create a new Scanner object which acts as an input stream to the client from the server.
6. Create a new PrintStream object which acts as an output stream to server from the client.
7. Repeat the following steps:
a) Read in the input from the server using the Scanner object.
b) Display the message received from theserver.
c) If the message received equals “bye”, then close input & output streams and exit loop.
d) Else, Prompt and read in the message from the user, which is to be sent to the server.
e) Send the message to the server from the client using the PrintStream object.
f) If the message equals “bye”, then close the input and output streams and exit loop.
8. Stop.

Source Code
TwoServer.java
import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;
class TwoServer
{
public static void main(String a[])throws IOException
{
String str, str1;
ServerSocket ss = new ServerSocket(8000);
// Opens the socket
Socket soc = ss.accept();
Scanner socIn = new Scanner(new InputStreamReader(soc.getInputStream()));
PrintStream socOut = new PrintStream(soc.getOutputStream());
Scanner in = new Scanner(new Scanner(new InputStreamReader(System.in)));
System.out.print("Server ready \n");
try
{
while(true)
{
System.out.print("Server: ");

P a g e | 21 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


// Reads the Server
input str = in.next();
socOut.println(str);
// Checks for server end of message
if(str.equals("bye"))
{
break;
}
// Reads the Client input
str1 = socIn.next();
System.out.println("Client: " + sTR1);
// Checks for client end of message
if(str1.equals("bye"))
{
break;
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

TwoClient.java
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;
class TwoClient
{
public static void main(String a[])throws IOException
{
String str,str1;
// Creates object for socket
Socket soc = new Socket("LocalHost",8000);
Scanner socIn = new Scanner(new InputStreamReader(soc.getInputStream()));
PrintStream socOut = new PrintStream(soc.getOutputStream());

P a g e | 22 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Scanner in = new Scanner(new InputStreamReader(System.in));
System.out.println("Client Waiting for a Message");
try
{
while(true)
{
// Reads the Server input
str = socIn.next();
System.out.println("Server: " + str);
// Checks for server end of message
if(str.equals("bye"))
{
break;
}
System.out.print("Client: ");
// Readsthe Clientinput
str1 = in.next();
socOut.println(str1);
// Checks for client end of message
if(str1.equals("bye"))
{
break;
}
}
}
catch(Exception e)
{
System.out.println(e);
}

}
}

P a g e | 23 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output

Server Side

Client Side

Result

Thus the program for two way communication using TCP executed and verified.

P a g e | 24 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 4.1 ECHO COMMAND

Aim

To implementation of a socket program for Echo command.

Algorithm

Server Program
1. Start
2. Import the java.net and java.io packages.
3. Declarea new class called “EchoServer”.
4. Inside “EchoServer”, declare a ServerSocket class object called “ss” with port number 9000.
5. Create a new Socket object called “soc” using the accept() method.
6. Create a new Scanner object which acts as an input stream from the client to the server.
7. Create a new PrintStream object which acts as an output stream to the client from the server.
8. Repeat the following steps:
i) Read in the message from the client using the Scanner object.
ii) If the received message is equal to the string “end” then close the input and output streams and
exit the program.
iii) Else, display the message received from the client to the server console.
iv) Send the same message back to the client using the PrintStream object.
v) Display “Message sent successfully.”
9. Stop

Client Program
1. Start
2. Import the java.net and java.iopackages.
3. Declare a new class called “EchoClient”.
4. Inside “EchoClient”, create a new Socket object called “s” with the port number 9000.
5. Create a new Scanner object that acts as an input stream to the client from the server.
6. Create another Scanner object that acts as an input stream from the user to the client.
7. Create a new PrintWriter object that acts as an output stream from the client to the server.
8. Create a new String object called “str”.
9. Display “Echo-Client”.
10. Repeat the following steps:
i) Prompt and read in the message to be sent to the server, from the user, using the
appropriate Scanner object and store in“str”.
ii) Send the message stored in “str” to the server using the PrintWriter object.
iii) Flush the output stream to the server.
iv) If “str” is equal to the string “end”, then close the input and output streams and exit the program.

P a g e | 25 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


v) Else, display “Message sent successfully”.
vi) Read in the message echoed back from the server to the client using the appropriate
Scanner object.
vii) Display the message echoed back from the server.
10. Stop

Source Code
EchoServer.java
import java.net.*;
import java.io.*;
import java.util.*;
public class EchoServer
{
public static void main(String args[]) throws IOException
{
tr
y
{
String str;
ServerSocketss=newServerSocket(9000);
Socket soc = ss.accept();
Scanner socIn = new Scanner(new
InputStreamReader(soc.getInputStream())); PrintStream socOut = new
PrintStream(soc.getOutputStream()); System.out.println("Server Ready.
...........................................................");
while(true)
{
str = socIn.nextLine();
socOut.println(str);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

P a g e | 26 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EchoClient.java
import java.net.*;
import java.io.*;
import java.util.*;
public class EchoClient
{
public static void main(String arg[]) throws IOException
{
tr
y
{
String str;
InetAddress ip = InetAddress.getLocalHost();
Socket soc = new Socket(ip, 9000);
Scanner socIn = new Scanner(new InputStreamReader(soc.getInputStream()));
PrintStream socOut = new PrintStream(soc.getOutputStream());
Scanner keyIn = new Scanner(new InputStreamReader(System.in));
while(true)
{
System.out.print("Client Message:");
str = keyIn.nextLine();
if(str.equals("bye"))
{
break;
}
socOut.println(str);
System.out.println("Server Recieved a Message:" + socIn.nextLine());
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

P a g e | 27 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output
Server Side

Client Side

Result
Thus data from client to server is echoed back to the client executed and output is verified.

P a g e | 28 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 4.2 PING COMMAND

Aim
To implement java program for check connection between client and server using ping command.

Algorithm
Server Program
1. Start
2. Import the java.net and java.iopackages.
3. Declare a new class called “PingServer”.
4. Inside “PingServer”, declare a ServerSocket object called “sersoc” with port number 9999.
5. Create a new String object called “str”.
6. Create a new Socket object called “soc” using the accept() method.
7. Create a new Scanner object which acts as an input stream from the client to the server.
8. Create a new PrintStream object which acts as an output stream to the client from the server.
9. Display “Ping Server”.
10. Repeat the following steps for integer variable i=0 , 1, …, 4
i) Read in the message from the client using the Scanner object and store in “str”.
ii) Display “Pinged by client”.
iii) Send the message “bytes=3< time<1ms TTL=128” to the client using the
PrintStream object.
11. Close the input and output streams and close the ServerSocket object.
12. Stop

Client Program
1. Start
2. Import the java.net and java.iopackages.
3. Declare a new class called “PingClient”.
4. Inside “PingClient”, declare the integer variables “i”.
5. Create a Scanner object that acts as an input stream from the user to the client.
6. Prompt and read in the IP address from the user.
7. Create a new Socket object called “soc” with the IP address from the user and port number 9999.
8. Create a new Scanner object that acts as an input stream to the client from the server.
9. Create a new PrintWriter object that acts as an output stream from the client to the server.
10. Display “Pinging ip address with byte=32bytes of data.”
11. Create a new String object called “str”.
12. Repeat the following steps for i=0 , 1, …, 4
i) Send the IP address received from the user to the server using the PrintWriter object.
ii) Flush the output stream to the server.

P a g e | 29 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


iii) Read in the message from the server and store in “str”.
iv) If str does not equal to null, then display the message from the server with a time delay.
v) Else, display “Request Timed Out!” with time delay.
13. Close the input and output streams and close the socket object.
14. Stop

Source Code
PingServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class PingServer
{
public static void main(String args[]) throws IOException
{
String str;
int i;
System.out.println("Ping Server");
try
{
ServerSocket sersoc = new ServerSocket(9999);
Socket soc = sersoc.accept();
Scanner socIn = new Scanner(new InputStreamReader(soc.getInputStream()));
PrintStream socOut = new PrintStream(soc.getOutputStream());
for(i = 0; i < 4; i++)
{
str = socIn.nextLine();
System.out.println("Pinged by client");
socOut.println(str + " Reply from host:bytes=3<time<1ms TT<=128");
}
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
}

P a g e | 30 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


PingClient.java
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;
public class PingClient
{
public static void main(String args[]) throws IOException
{
int i;
String str;
try
{
Scanner keyIn = new Scanner(new InputStreamReader(System.in));
System.out.println("Enter the IP address: ");
String ip = keyIn.nextLine();
Socket soc = new Socket(ip,
9999);
Scanner socIn = new Scanner(new InputStreamReader(soc.getInputStream()));
PrintStream socOut = new PrintStream(soc.getOutputStream());
System.out.println("Pinging " + ip + " with 32 bytes of data");
for (i = 0; i < 4; i++)
{
socOut.println(ip);
str =
socIn.nextLine(); if
(str != null)
{
Thread.sleep(2000);
System.out.println("Reply from " + str);
}
else
{
Thread.sleep(2000);
System.out.println("Request time out");
}
}
}
catch (IOException e) {
System.out.println("Request timed out");

P a g e | 31 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


}

P a g e | 32 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


catch(InterruptedException e)
{
System.out.println("Request timed out");
}
}
}
Output
Client Side

Server Side

Result
Thus the program for connection availability between client and server using ping command is
executed and verified.

P a g e | 33 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 4.3 TALK COMMAND

Aim
To implement java program for message passing between client and server using talk command.

Algorithm
Server Program
1. Start
2. Import the java.net and java.iopackages.
3. Declare a new class called “TalkServer”.
4. Inside “TalkServer( )” constructor, declare a ServerSocket object called “ss” with port
number 9999.
5. Display “Talk Server” and “Node Succesfully Connected..”
6. Create a new Socket object called “soc” using the accept() method.
7. Create a new PrintStream object which acts as an output stream to the client from the server.
8. Create a new Scanner object that acts as an input stream to the server from the client.
9. Create another Scanner object which acts as an input stream from the user to the server.
10. Create a new String objects are called “str1 and str2”.
11. Repeat the following steps:
i) Read in the message from the client using the correct Scanner object and store in “str1”.
ii) Display the message received from the client in “str1”.
iii) If string in “str2” equals “bye” while ignoring case, then close the input and output
streams, close the ServerSocket object, and exit the program.
iv) Else, Prompt and read in the message to send to the client from the user using the
correct Scanner object and store in“str2”.
v) Send the message in “str2” to the client using the PrintStream object.
12. Stop

Client Program
1. Start
2. Import the java.net and java.iopackages.
3. Declare a new class called “TalkClient”.
4. Inside “TalkClient()” constructor, create a new Socket object called “soc” with the port
number 9999.
5. Display “Talk Client”.
6. Create a new Scanner object that acts as an input stream from the user to the client.
7. Create a new PrintStream object that acts as an output stream from the client to the server.
8. Create a new Scanner object that acts as an input stream to the client from the server.
9. Create a new String object called “str”.

P a g e | 34 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


10. Repeat the following steps:
i) Prompt and read in the message to be sent to the server, from the user, using the
appropriate Scanner object and store in“str”.
ii) Send the message stored in “str” to the server using the PrintStream object.
iii) If string in “str” equals “bye” while ignoring case, then close the input and output streams,
close the Socket object, and exit the program.
11. Stop

Source Code
TalkServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class TalkServer
{
public static void main(String args[])throws IOException
{
tr
y
{
String str1,str2;
ServerSocket ss= new ServerSocket(9999);
Socket soc = ss.accept();
Scanner socIn = new Scanner(new InputStreamReader(soc.getInputStream()));
PrintStream socOut = new PrintStream(soc.getOutputStream());
System.out.println("TALK SERVER");
System.out.println("----------------------");
System.out.println("Node Successfully connected..");
while(true)
{
str1 = socIn.nextLine();
System.out.println("Message Received");
System.out.println("Message : "+str1);
Scanner In = new Scanner(new InputStreamReader(System.in));
str2 = In.nextLine();
if(str2.equals("bye"))
{
break;
}
socOut.println(str2);

P a g e | 35 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


socOut.flush();
System.out.println("Message Sent Successfully");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

TalkClient.java
import java.io.*;
import java.net.*;
import java.util.*;
public class TalkClient
{
public static void main(String args[]) throws IOException
{
tr
y
{
String str;
Socket soc = new Socket("localhost",9999);
Scanner socIn = new Scanner(new InputStreamReader(soc.getInputStream()));
PrintStream socOut = new PrintStream(soc.getOutputStream());
Scanner keyIn = new Scanner(new InputStreamReader(System.in));
System.out.println("TALK CLIENT");
System.out.println("--------------------");
while(true)
{
System.out.println("Send Message to Server: ");
str=keyIn.nextLine();
if(str.equals("bye"))
{
break;
}
socOut.println(str);
socOut.flush();
System.out.println("Message Sent Successfully");

P a g e | 36 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


System.out.println(" ");
System.out.println("Message Received from TalkServer: "+socIn.next());
}
}
catch(IOException e)
{
System.err.println(e);
}
}
}

Output
Client Side

P a g e | 37 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Server Side

Result

Thus the program for message passing between client and server using talk command is executed
and verified.

P a g e | 38 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 5.1 FILE TRANSFER USING TCP

Aim
To implement a java program for file transfer between two nodes using TCP.

Algorithm
Server Program
1. Start
2. Import the java.net and java.iopackages.
3. Declare a new class called “FileServer”.
4. Inside “FileServer”, declare a ServerSocket object called “ss” with port number 8000.
5. Declare a new byte array
6. Repeat the following steps:
a. Display “Server is listening...”
b. Create a new Socket object called “s” using the accept() method.
c. Create Scanner object which acts as an input stream from the user to the server.
7. Get the filename and stored into the BufferedReader.
8. Create a new object for class file and readline.
9. Display “Enter the file name”.
10. If File is exists then FileReader read the content until EOF is reached.
11. Display “The file send successfully”.
12. Else Print FileName does‟t exits.
13. Stop

Client Program
1. Start
2. Import the java.net and java.iopackages.
3. Declare a new class called “FileClient”.
4. Inside “FileClient”, create a new Socket object called “soc” with the port number 8000.
5. Create a Scanner object that acts as an input stream to the client from the user.
6. Create a new String object called “str”.
7. Prompt and read in if the user wants to view the contents of the file, using Buffered Reader
object, and store in new String “str”.
8. Display “the file is received successfully”.
9. Stop

P a g e | 39 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Source Code
FileServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class FileServer
{
public static void main(String args[])throws IOException
{
try
{
String str;
ServerSocket ss = new
ServerSocket(8000); Socket soc =
ss.accept(); System.out.println("Server
Listening.................................................");
System.out.println("Connection frame: " + soc);
PrintStream socOut = new PrintStream(soc.getOutputStream());
Scanner keyIn = new Scanner(new InputStreamReader(System.in));
// BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the text file name");
String fileName = keyIn.nextLine();
File fi = new File(fileName);
if(fi.exists())
{
// Scanner fileIn = new Scanner(new FileReader(fileName));
BufferedReader fileIn = new BufferedReader(new FileReader(fileName));
while((str = fileIn.readLine()) != null)
{
socOut.println(str);
}
System.out.println("The file send successfully");
}
else
{
System.out.println("File not exists");
}
}

P a g e | 40 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


catch(IOException e)
{
System.out.println("Error: " + e);
}
}
}

FileClient.java
import java.io.*;
import java.net.*;
import java.util.*;
public class FileClient
{
public static void main(String args[])throws IOException
{
try
{
String str;
Socket soc = new Socket(InetAddress.getLocalHost(),8000);
Scanner socIn = new Scanner(new InputStreamReader(soc.getInputStream()));
if((str = socIn.nextLine()) != null)
{
System.out.println("The content of the file is");
System.out.println(str);
System.out.println("The file is received successfully");
}
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
}

P a g e | 41 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output
Server Side

Client Side

Result
Thus the program for file transfer between two nodes using TCP is executed and verified.

P a g e | 40 COMPUTER DEPARTMENT OF IT, FEAT, AU


EX.NO: 5.2 FILE TRANSFER USING UDP

Aim
To implement a java program for file transfer between two nodes using UDP.

Algorithm
Server Program
1. Start.
2. Import the java.net and java.iopackages.
3. Declare a new class called “UDPServer”.
4. Create objects for DatagramSocket and DatagramPacket to send the packet from server.
5. Inside “UDPServer”, declare a DatagramSocket object called “dsoc” with port number 1000.
6. Declare a new byte array size of 1024.
7. Cretae a DatagramPacket object called “dp” and assign the bytes and its length.
8. Display the text message.
9. Stop

Client Program
1. Start
2. Import the java.net and java.iopackages.
3. Declare a new class called “UDPClient”.
4. Inside “UDPClient”, create a DatagramSocket object called “dsoc” with the port number 2000.
5. Declare a new byte array size of 1024.
6. Create a FileInputStream object called “fi” and call the file name.
7. Send the corresponding file to UDPServer using send().
8. Stop

Source Code
UDPServer.java
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws IOException
{
try
{
while(true)
{

P a g e | 41 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


byte[] b = new byte[1024];
DatagramSocket dsoc = new DatagramSocket(1000);
while(true)
{
DatagramPacket dp = new DatagramPacket(b,b.length);
dsoc.receive(dp);
System.out.println(new String(dp.getData(),0,dp.getLength()));
System.out.println("The recieved file successfully");
}
}
}
catch(Exception e)
{
System.out.print(e);
}
}
}

UDPClient.java
import java.io.*;
import
java.net.*; class
UDPClient
{
public static void main(String args[]) throws IOException
{
try
{
int i=0;
byte[] b = new byte[1024];
DatagramSocket dsoc = new
DatagramSocket(2000); FileInputStream fi = new
FileInputStream("abc.txt"); while(fi.available()!=0)
{
b[i]=(byte)fi.read();
i++;
}
fi.close();
dsoc.send(new DatagramPacket(b,i,InetAddress.getLocalHost(),1000));
}

P a g e | 42 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


catch(Exception e)
{
System.out.println(e);
}
}
}

Output
Server Side

Client Side

Result
Thus the program for file transfer between two nodes using UDP is executed and verified.

P a g e | 43 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 6 REMOTE COMMAND EXECUTION

Aim
To implement the java program for Remote Command Execution.

Algorithm
Server Program
1. Start
2. Import the java.net, java.io, and java.lang packages.
3. Declare a new class called “RCEServer”.
4. Within class “RCEServer”, create an object of class ServerSocket called “ss” with the port
number 1000.
5. Create a Socket object called “soc” using the accept() method.
6. Create an object of class Runtime using the getRuntime() method.
7. Create a new Scanner object which acts as an input stream to the server from the client.
8. Read in the input from the client using the DataInputStream object and store it in string “s”.
9. Display the value of string“str”.
10. Execute the string command stored in “str” using the Runtime object's exec() method.
11. Stop

Client Program
1. Start
2. Import the java.net, java.lang, and java.io packages.
3. Declare a new class called “RCEClient”.
4. Within class “RCEClient”, create a new Socket object called “soc” with the port number 1000.
5. Create a new Scanner object which acts as an input stream from the user to the client.
6. Create a PrintStream object which acts as an output stream from the client to the server.
7. Send the command read from the user to the server using the getOutputStream object.
8. Display “Enter the command”.
9. Print the corresponding command message.
10. Stop

P a g e | 44 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Source Code
RCEServer.java
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;
class RCEServer
{
public static void main(String a[]) throws IOException, UnknownHostException, InterruptedException
{
ServerSocket ss = new
ServerSocket(1000); Socket soc =
ss.accept(); System.out.println("Server
Ready. ...............................................");
Runtime run = Runtime.getRuntime();
Scanner socIn = new Scanner(new InputStreamReader(soc.getInputStream()));
// BufferedReader socIn = new BufferedReader(new InputStreamReader(cs.getInputStream()));
String str = socIn.nextLine();
System.out.println("The Command Recieved: "+str);
run.exec(str);
}
}

RCEClient.java
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.*;
public class RCEClient {
public static void main(String a[])throws UnknownHostException,IOException
{
Socket soc = new Socket("localhost",1000);
Scanner keyIn = new Scanner(new InputStreamReader(System.in));
// BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
PrintStream socOut = new PrintStream(soc.getOutputStream());
System.out.println("Enter the Command:");
String str = keyIn.nextLine();
socOut.println(str);
}
}

P a g e | 45 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output

Server Side

Client Side

P a g e | 46 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Calc

Notepad

Result
Thus the program Remote Command Execution (calculator and notepad) executed and verified.

P a g e | 47 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 7.1 CYCLIC REDUNDANCY CHECK

Aim
To Implementation of a java program for Cyclic Redundancy Check (CRC) error handling.

Algorithm
1. Start
2. Import the java.net, java.io, and java.util packages.
3. Inside class “crc_gen”, define the main() method to create a new Scanner object to read input
from the user.
4. Prompt for and read in the message bits as a string and convert and store in an integer array “D”.
5. Prompt for and read in the generator bits as a string and convert and store in an integer array “G”.
6. If G[0] equals 0 then display “Invalid generator bits”.
7. Declare arrays “DR”, “rem”, and “transmitMessage” of size the sum of array D's and array G's sizes
minus one.
8. Copy array D into array DR.
9. Display arrays D, G, DR.
10. Copy DR into array rem and call the computeCRC() method.
11. Display the remainder in arrayrem.
12. Ex-or each element of the array rem with array DR and store the elements in array transmitMessage.
13. Display transmitMessage.
14. Prompt for and read in the received message as a String and convert and store as integer in
array transmitMessage.
15. Copy transmitMessage into array rem and call the computeCRC() method.
16. If any of the bits in array rem don't equal zero then display “Message Received with error”
else display “Message received succesfully.”
17. Stop

Compute CRC
1. Start
2. Declare and initialize integer variable “current” to zero.
3. Repeat the following steps:
4. Repeat for i=0 to(g-1):
5. EX-OR rem[current+i] and G[i] and store back in rem[current+i].
6. Increment “current” while rem[current] equals zero and while “current” is less than length of
array “rem”.
7. If the no. of elements after “current” position in array “rem” is less than the length of array “G”,
then exit loop.
8. Return the array “rem”.
9. Stop

P a g e | 48 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Source Code
CRC.java
import java.io.*;
import java.lang.*;
import java.util.*;
class crc_gen
{
public static void main(String args[]) throws IOException
{
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
int data_bits, divisor_bits, tot_length;
int i,j;
Scanner br = new Scanner(new InputStreamReader(System.in));
System.out.println("Enter number of data bits : ");
data_bits = Integer.parseInt(br.nextLine());
data = newint[data_bits];

System.out.println("Enter data bits : ");


for(i=0; i<data_bits; i++)
{
data[i] = Integer.parseInt(br.nextLine());
}

System.out.println("Enter number ofbits indivisor


:"); divisor_bits = Integer.parseInt(br.nextLine());
divisor = new int[divisor_bits];

System.out.println("Enter Divisor bits : ");


for(i=0; i<divisor_bits; i++)
{
divisor[i] = Integer.parseInt(br.nextLine());
}

P a g e | 49 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


System.out.print("Data bits are : ");
for(i=0; i< data_bits; i++)
System.out.print(data[i]);
System.out.println();

System.out.print("Divisor bits are : ");


for(i=0; i< divisor_bits; i++)
System.out.print(divisor[i]);
System.out.println();

tot_length = data_bits + divisor_bits -


1; div = newint[tot_length];
rem = newint[tot_length];
crc=newint[tot_length];

/*------------------ CRC GENERATION-----------------------*/


for(i=0;i<data.length;i++)
{
div[i] = data[i];
}

System.out.print("Dividend(afterappending0's)are:");
for(i=0; i< div.length; i++)
{
System.out.print(div[i]);
}
System.out.println();

for(j=0; j<div.length; j++)


{
rem[j] = div[j];
}
rem = divide(div, divisor, rem);

for(i=0;i<div.length;i++) //append dividend and remainder


{
crc[i] = (div[i]^rem[i]);
}
System.out.println();

P a g e | 50 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


System.out.print("CRC code : ");
for(i=0;i<crc.length;i++)
{
System.out.print(crc[i]);
}
/*-------------------ERROR DETECTION---------------------*/
System.out.println();
System.out.println("Enter CRC code of "+tot_length+" bits : ");
for(i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.nextLine());

System.out.print("CRC bits are : ");


for(i=0; i< crc.length; i++)
{
System.out.print(crc[i]);
}
System.out.println();

for(j=0; j<crc.length; j++)


{
rem[j] = crc[j];
}
rem = divide(crc, divisor, rem);

for(i=0; i< rem.length; i++)


{
if(rem[i]!=0)
{
System.out.println("Message is Recieved with Error!!");
break;
}
if(i==rem.length-1)
{
System.out.println("Message is Recieved successfully!!");
}
}
}

P a g e | 51 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


static int[] divide(int div[],int divisor[], int rem[])
{
int cur=0;
while(true)
{
for(int i=0;i<divisor.length;i++)
{
rem[cur+i]=(rem[cur+i]^divisor[i]);
}
while(rem[cur]==0 && cur!=rem.length-1)
{
cur++;
}
if((rem.length-cur)<divisor.length)
{
break;
}
}
return rem;
}
}

P a g e | 52 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output with No Error

P a g e | 53 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output with Error

Result
Thus the java program for Cyclic Redundancy Check is executed and output is verified successfully.

P a g e | 54 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 7.2 HAMMING CODE

Aim
To implement a java program for hamming code using error handling mechanism.

Algorithm
1. Start
2. Import the jav.io.* and java.utilpackages.
3. Inside class “Hamming_code”, define the main() method to create a new Scanner object to read
input from the user.
4. Declare the integer array d, p, c., and integer value, i and dec.
5. Declare array elements for a value as 0.
6. Enter data in bits and check for the condition.
7. Declare and initialize the variablec.
8. Calculating the array value for a1, A2, a4, a8.
9. If the value of c is equal to 1 then, the value of c is incremented.
10. If the c module 2 is equal to zero, the array value is 0 else 1.
11. The above step is repeated for all the array values.
12. The step is expected for „r‟ array and „v‟ array also.
13. The error will be detected and the corrected message is displayed.
14. Stop.

Source Code
Hamming_code.java
import java.io.*;
import java.util.*;
class Hamming_code
{
public static void main(String arg[])
{
int i, dec;
int d[] = new int[7];
int p[] = new int[4];
int c[] = new inT[11];
int r[] = new int[11];
int pr[] = new int[4];
int rd[] = new int[7];
int s[] = new int[4];

P a g e | 55 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Scanner sc = new Scanner(System.in);
System.out.println("Enter the 7-bit data code");
for(i=0;i<7;i++)
{
d[i]=sc.nextInt();
}
System.out.println();
p[0] = d[0]^d[1]^d[3]^d[4]^d[6];
p[1] =
d[0]^d[2]^d[3]^d[5]^d[6]; p[2]
= d[1]^d[2]^d[3];
p[3] = d[4]^d[5]^d[6];
System.out.println("Complete Code Word is ");
c[0] = p[0];
C[1] = p[1];
c[2] = d[0];
c[3]=p[2];
c[4] = d[1];
c[5] =d[2];
c[6]=d[3];
c[7] = p[3];
c[8] = d[4];
c[9]=d[5];
C[10]= d[6];

for(i=0; i<11;i++)
{
System.out.print(c[i]+ " ");
}
System.out.println("\n");

System.out.println("Enter the Received Code word"); for(i=0;i<11;i+


+)
{
r[i] = sc.nextInt();
}
pr[0] =r[0];
pr[1] = r[1];
rd[0] = r[2];
pr[2]=r[3];
P a g e | 56 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU
rd[1] =r[4];
rd[2] = r[5];
rd[3]=r[6];
pr[3]= r[7];
rd[4] = r[8];
rd[5] =r[9];
rd[6] = r[10];

s[0] =pr[0]^rd[0]^rD[1]^rd[3]^rd[4]^rd[6];
s[1] = pr[1]^rd[0]^rD[2]^rd[3]^rd[5]^rd[6];
s[2] = pr[2]^rd[1]^rd[2]^rd[3];
s[3] = pr[3]^rd[4]^rd[5]^rd[6];

dec = (s[0]*1)+(s[1]*2)+(s[2]*4)+(s[3]*8);
System.out.print("\n");
if(dec == 0)
{
System.out.println("No error");
}
els
e
{
System.out.println("Error is at
"+dec); if(r[dec-1]==0)
r[dec-1]=1;
else

r[dec-1]=0;
}
System.out.print("\n");
System.out.print("Corrected Code Word is: ");
for(i=0;i<11;i++)
{
System.out.print(r[i]+" ");
}
}
}

P a g e | 57 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output with No Error

P a g e | 58 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output with Error

Result
Thus the java program for Hamming Code is executed and output is verified successfully.

P a g e | 59 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 8 SIMULATION OF SLIDING WINDOW PROTOCOL

Aim
To write a java program to simulate the one bit sliding window protocol.

Algorithm
Server Program
1. Start
2. Import the packages java.io, java,net and java.io.
3. Declare the class SlidingServer, and create the object for that class.
4. Create the class ServerSocket and create the object with port number 5000.
5. Create the class Socket and create the object soc and use the method accept().
6. Declare the class Scanner and input stream reader and create the object.
7. Using the getInputStream() method, the input from the user is read.
8. Declare the integer variables a and p parse the variable to integer.
9. The frame is sent to the client and waiting for the acknowledgement.
10. Make use of Thread.Sleep()method to pause the sending of frame until acknowledgement is received.
11. Display the message “Received aknowlwdgement frame number”.
12. Stop

Client Program
1. Start
2. Import the packages java.lang, java.net, java.io and java.util.
3. Enter the corresponding ip address or local host to communicate with server.
4. Create the class Socket and object with the port number 5000 for the local host.
5. Declare the class PrintStream and Scanner and create the objects.
6. Using the intger variable str and parse it using the nextline() method.
7. Enter the number of frame need and send the acknowledgement for executed frame.
8. Stop

P a g e | 60 COMPUTER DEPARTMENT OF IT, FEAT, AU


Source Code
SlidingServer.java
import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;
class SlidingServer
{
public static void main(String[] args) throws IOException, InterruptedException
{
try
{

int i, str, p;
ServerSocketss=newServerSocket(5000);
System.out.println("Server Ready...");
Socket soc = ss.accept();
Scanner socIn = new Scanner(new InputStreamReader(soc.getInputStream()));
PrintStream socOut = new PrintStream(soc.getOutputStream());
p = Integer.parseInt(socIn.nextLine());
for(i = 1; i <= p; ++i)
{
System.out.println("Sending frame no: " + i);
socOut.println(i);
System.out.println("Waiting for acknowledgement");
Thread.sleep(5000);
str = Integer.parseInt(socIn.next());
System.out.println("Received acknowledgement for frame no: " + i + " as " + str);
}
}
catch(IOException e)
{
System.out.println(e);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}

P a g e | 61 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


SlidingClient.java
import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.*;
class SlidingClient
{
public static void main(String a[]) throws IOException
{
try
{

int str, flag = 0;


int i, j = 0;
String ip;
Scanner keyIn = new Scanner(new InputStreamReader(System.in));
System.out.println("Enter the IP address: ");
ip = keyIn.nextLine();
Socket soc = new Socket(ip, 5000);
PrintStream socOut = new PrintStream(soc.getOutputStream());
Scanner socIn = new Scanner(new InputStreamReader(soc.getInputStream()));
System.out.println("Enter number of frames needed: ");
str = Integer.parseInt(keyIn.nextLine());
socOut.println(str);
while(j < str)
{
i = Integer.parseInt(socIn.nextLine());
System.out.println("Received frame no: " + i);
System.out.println("Sending acknowledgement for frame no: " + i);
socOut.println(i);
j++;
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

P a g e | 62 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output
Client Side

Server Side

Result
Thus the simulation of simulation of sliding window protocol is executed and output verified
successfully.

P a g e | 63 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 9 HTTP WEBPAGE UPLOAD AND DOWNLOAD

Aim
To write a java program for socket for HTTP for web page upload and download.

Algorithm
Server Program
1. Start
2. Importthenecessarypackages.
3. Declare the class “HTTPServer”.
4. Inside class “HTTPServer”, read in the command line arguments.
5. Create the class ServerSocket and create the object with port number 4000.
6. Display the message “Server Waiting for Image”.
7. Create the class Socket and create the object soc and use the method accept().
8. Display the message “Client connected”.
9. Using the InputStream and DataInputStream get the input from the Client side.
10. Display the image size.
11. ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream.
12. Use the read method of the Java ImageIO class, and you can open/read images in a variety of
formats (GIF, JPG, and PNG).
13. JFrame class, is a window that has decorations such as a border, a title, and supports
button components that close oriconify the window.
14. The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.
15. The class JLabel can display either text, an image, or both.
16. Stop

Client Program
1. Start
2. Importthenecessarypackages.
3. Declare the class “HTTPClient”.
4. Display the message “Client isrunning”.
5. Create the class Socket and object with the port number 4000 for the local host.
6. Display the message “Reading image from disk”.
7. The BufferedImage subclass describes an Image with an accessible buffer of image data.
8. Creates a ByteArrayOutputStream and copies the bytes to the output, then calls toByteArray().
It handles large files by copying the bytes in blocks of 4KiB.
9. To ImageIO class provides many more static methods for more advanced usages of the Image I/O
API and create a File class and pass as parameter the image file path.
10. The “javax.imageio.ImageIO” is a handy class to read and write image into local system.

P a g e | 64 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


11. toByteArray() method creates a newly allocated buffer with the size as the current size of this
output stream.
12. Display the message “Sending image to server”.
13. An output stream accepts output bytes and sends them to some sink.
14. Use DataOutputStream stream to create an object and write the primitives to an output source.
15. The java.io.DataOuputStream.writeInt(int v) method writes a int value to the to the
underlying stream as four bytes.
16. Using write() method, Java socket receives byte array where each byte is 0.
17. Display the message “Image sent to Server”.
18. Stop

Source Code
HTTPServer.java
import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class HTTPServer
{
public static void main(String args[]) throws Exception
{
try
{

int len;
ServerSocket ss = new ServerSocket(4000);
System.out.println("Server Waiting for Image");
Socket soc = ss.accept();
System.out.println("Client connected.");
InputStream in = soc.getInputStream();
DataInputStream dis = new DataInputStream(in);
len = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB");
byte[] data = new byte[len];
dis.readFully(data);
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = ImageIO.read(ian);
JFrame f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);

P a g e | 65 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


JLabel l = new
JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}
catch(Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
}
}

HTTPClient.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 HTTPClient
{
public static void main(String args[]) throws Exception
{
System.out.println("Client is running.");
try
{
Socket soc = new Socket("localhost",4000);
System.out.println("Reading image from disk. ");
BufferedImage img = ImageIO.read(new File("Koala.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
baos.close();

P a g e | 66 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


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. ");
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
}
}

Output

Server Side

P a g e | 67 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Client Side

Koala.jpg

Result
Thus the java program for socket for HTTP for web page upload and download are executed and
output is verified.

P a g e | 68 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: IMPLEMENTATION OF RCP (REMOTE SCREEN CAPTURE)
10

Aim
To implement a java program for RCP (Remote Screen Capture).

Algorithm
Server Program
1. Start
2. Import the packages java.net, java.io, java.awt, java.image and javax.image.io.
3. Declare the class ScreenServer.
4. Inside the main method declare a new object robot, Robot class provides a useful method for
capturing a screenshot.
5. Display the message “Server Ready…”.
6. Create a new object server with a port number 5000.
7. Declare a Socket class object soc which has a accept() method.
8. The screen size as a Rectangle object to display the getScreenSize() as full image.
9. To capture the whole screen using createScreenCapture() method.
10. Assign the size and width of the image.
11. Get outputstream object to send message from client to user.
12. ObjectOutputStream class writes primitive data types and graphs of Java objects to an OutputStream.
13. Here using image io.write the image orig_screen.png is displayed.
14. Then close() and flush() method close all the server, client and out.
15. Stop

Client Program
1. Start
2. Import the packages java.net, java.io, java.awt, java.image and javax.image.io.
3. Declare a new class ScreenClient.
4. Using the Scanner class to get the input as ip address.
5. Using Socket class to create the object soc and with the port no 5000.
6. Create for object input stream as in to get input from server to client.
7. The BufferedImage subclass describes an Image with an accessible buffer ofimage data.
8. The method setRGB() can be used to set the color of a pixel of an already existing image.
9. imageio package, to load images from an external image format into the internal
BufferedImage format used by Java 2D
10. Here close the server and in object using close() method.
11. Stop

P a g e | 69 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Source Code
ScreenServer.java
import java.net.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
public class ScreenServer
{
public static void main(String[] args) throws Exception
{
try
{
int x;
Robot robot = new Robot();
System.out.println("Server Ready.
...........................................................")
;
while(true)
{
ServerSocketss=newServerSocket(5000);
Socket soc = ss.accept();
Rectangle size = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
/* To capture a screenshot of the whole screen, we need to know the screen size.
The following statement obtains the screen size as a Rectangle object: */

BufferedImage screen = robot.createScreenCapture(size);


int[] rgbData = new int[(int) (size.getWidth()*size.getHeight())];
screen.getRGB(0,0, (int) size.getWidth(), (int) size.getHeight(), rgbData, 0, (int) size.getWidth());

/* getRGB(int startX, int startY, int w, int h, int[] rgbArray, int offset, int scansize)
Returns an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and
default sRGB color space, from a portion of the image data. */

OutputStream baseOut = soc.getOutputStream();


ObjectOutputStream out = new ObjectOutputStream(baseOut);
ImageIO.write(screen, "png", new File("orig_screen.png"));
out.writeObject(size);

for (x = 0; x <rgbData.length; x++)


{

P a g e | 70 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


out.writeInt(rgbData[x]);
}

P a g e | 71 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


out.flush();
ss.close();
soc.close();
out.close();
baseOut.close();
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}

ScreenClient.java
import java.net.*;
import java.awt.*;
import
java.awt.image.*;
import java.io.*;
import java.util.*;
import javax.imageio.ImageIO;
public class ScreenClient
{
public static void main(String[] args) throws Exception
{
tr
y
{
int x;
String ip;
Scanner keyIn = new Scanner(new InputStreamReader(System.in));
System.out.println("Enter the IP address: ");
ip = keyIn.nextLine();
Socket soc = new Socket(ip, 5000);
ObjectInputStream in = new ObjectInputStream(soc.getInputStream());
Rectangle size = (Rectangle) in.readObject();
int[] rgbData = new int[(int)(size.getWidth() * size.getHeight())];
for (x = 0; x <rgbData.length;x++)
{
rgbData[x] = in.readInt();
P a g e | 72 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU
}

P a g e | 73 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


BufferedImage screen = new BufferedImage((int) size.getWidth(), (int) size.getHeight(),
BufferedImage.TYPE_INT_ARGB);
screen.setRGB(0,0, (int) size.getWidth(), (int) size.getHeight(), rgbData, 0,(int)size.getWidth());
ImageIO.write(screen, "png", new File("screen.png"));
}
catch(IOException e)
{
System.out.println(e);
}
}
}

Output

Server Side

Client Side

P a g e | 74 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Remote Screen Capture

Result
Thus the implementation of RCP (Remote Screen Capture) are executed and output is verified.

P a g e | 75 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO:11.1 SHORTEST PATH ROUTING

Aim
To implement the java program for Shortest Path Routing (Dijkstra‟s Algorithm) to find the
shortest path between the nodes.

Algorithm
1. Start
2. Import the java.net and java.iopackages.
3. Declare a class called “ShortestPath”.
4. Read in the input from the client using the Scanner object and store it in string “a”.
5. Dijkstra‟s shortest path algorithm computes all shortest path from a single node.
6. It can also be used for the all pairs shortest path problem, by the simple expedient of applying it
N times once to each vertex.
7. Get the number of nodes in the network for which the shortest path is to be calculated.
8. Represent the nodes that are connected by cost value (Number of hopes delay bandwidth, etc.,)
and nodes that are not connected by infinite value in an adjacent matrix.
9. To find the shortest path between node follow the steps as stated below.
a. Initially, T=V, where T= set of nodes and V= nodes for which the shortest path is to be found.
b. At each step of the algorithm the vertex in T with the smallest d value is removed from T.
c. Each neighbor of in T is examined would be shorter than the currently best known path.
10. The last paths that remain between the nodes are the shortest path between the source node and
the destination nodes.
11. Stop

Source Code
ShortestPath.java
import java.net.*;
import java.io.*;
import java.util.*;
class ShortestPath
{
public static void main(String args[]) throws IOException
{
int n,s,d,i,j;
int y=0, sd=9999;
int[] in = new inT[10];
int[][] m = new int[5][5];
int[] dis = new int[10];

P a g e | 76 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


int[] path = new inT[10];
Scanner a = new Scanner(System.in);
System.out.println("****** SHORTEST PATH ROUTING ******\n");
System.out.print("Enter the No of Vertex:");
n = Integer.parseInt(a.nextLine());
System.out.println("");

System.out.print("Enter the Source Vertex:");


s = Integer.parseInt(a.nextLine());
System.out.println("");

System.out.print("Enter the Destination Vertex:");


d = Integer.parseInt(a.nextLine());
System.out.println("");
for(i=1;i<n;i++)
{
J=1;

while(j<n)
{
System.out.print("\nEnter the distance between [" +i+ "," +(j+1)+"]:");
m[i][j+1] = Integer.parseInt(a.nextLine());
m[j+1][i] = m[i][j+1];
j++;
}
}
for(i=1;i<=n;i++)
{
in[i] = 0;
dis[i] = m[s][i];
if(m[s][i]!=0)
path[i] = s;
}
in[s] = 1;
dis[s] = 0;
for(i=2;i<n;i+
+)
{
for(j=1;j<=n;j++)
{
if(in[j]==0)
{
P a g e | 77 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU
if(dis[j]<sd)
{
sd=dis[j];
y=j;
}
}
}
in[y]=1;
for(j=1;j<=n;j++)
{
if((in[j]==0)&&(m[y][j]!=0))
{
if((dis[y]+m[y][j])<dis[j])
{
dis[j]=dis[y]+m[y][j];
path[j]=y;
}
}
}
}
i=d;

System.out.print("\n");
System.out.println("The Shortest Path is : \n");
System.out.print(" "+d);
while(path[i]!=s)
{
System.out.print("- - -> " +path[i]);
i=path[i];
}
System.out.print("----> ");
System.out.println(s);
System.out.print("\n");
System.out.println("Distance of the Shortest Path is "+dis[d]);
}
}

P a g e | 78 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output

Result
Thus the finding shortest path routing between two nodes are executed suessfully and output
verified.

P a g e | 79 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO:11.2 FLOODING ROUTING

Aim
To implement the java program for Flooding Routing protocol.

Algorithm
1. Start
2. Import the java.util and java.iopackages.
3. Declare a class called “Flooding”.
4. Read in the input from the client using the Scanner object and store it in string “br”.
5. Enter the number of nodes innetwork.
6. Make matrix of network n*n put 0 if not connected else 1 if connected.
7. To calculate the maximum life time of a frame.
8. Enter source address i.e. id (1...n) & destination address now algorithm will calculate where packets
will go.
9. Output will be id of nodes where packets will go.
10. Stop

Source Code
Flooding.java
import java.io.*;
import java.util.*;
public class Flooding
{
/* hopCount function will decide the life time for frame to live in network
*/ static int hopCount(int m[][],intn)
{
int i,j,h=0;
for(i=1;i<=n;i+
+)
{
for(j=1;j<=n;j++)
{
h += m[i][j];
}
}
h -= n;
h =((h%2)==0)?(h/2):(h/2+1);

P a g e | 78 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


return h;

P a g e | 79 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


/* This function show the network in matrix form which you entered */
public static void showNetworkMatrix(int m[][],int n)
{
int i, j;
System.out.println("\nNetwork Matrix 1st row and column showing nodes(or hops) id \n");
for(i=0;i<=n;i++)
{
for(j=0;j<=n;j++)
{
if(i==0 && j==0)
System.out.print("nodes- ");
else if(j==0)
System.out.print(m[i][j]+" ");
else

System.out.print(m[i][j]+" ");
}
System.out.println();
}
System.out.println();
}

static void check(int m[][],int n,int ps,int s,int d,int h)


{
/* m-network matrix ; n-number of nodes ; ps - denoted previous node; s-new source
node ; d- destination node; h- time remain to live innetwork */
int i=s,j;
if(h==0||s==d)
return;
for(j=1;j<=n;j++)
{
if(m[i][j]==1 &&j !=i && j!=ps)
System.out.print(j+" ");
}
System.out.println("\n\n");
for(j=1;j<=n;j++)
{
if(m[i][j]==1 && j!=i && j!
=ps) check(m,n,s,j,d,(h-1));
}
}

P a g e | 80 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


static void FloodAlgo(int m[][],int n,int s,int d,int h)
{
System.out.println("\n"+s+"\n");
/* check function search the next node and repeat till it not got the
destination address or hopcount will become zero; */
check(m,n,0,s,d,h);
}

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


{
int n;
Scanner br = new Scanner(new InputStreamReader(System.in));
System.out.println("***** FLOODING ROUTING PROTOCOLS
*****"); System.out.print("Enter Number of nodes in network:");
n = Integer.valueOf(br.nextLine());
// int n=6;
/* 1 stands for a connection and 0 stands for not connection between two nodes */
System.out.print("\n");
System.out.println("Enter thenetworkMatrixwith(0and1):");
int [][]network = new int[n+1][n+1];
/* this is a fix matrix u can use it network[0][0]=0;network[0][1]=1;network[0][2]=2;network[0]
[3]=3;network[0][4]=4; network[0][5]=5;network[0][6]=6; network[1][0]=1;network[1]
[1]=1;network[1][2]=1;network[1][3]=0;network[1][4]=0; network[1][5]=0;network[1][6]=0;
network[2][0]=2;network[2][1]=1;network[2][2]=1;network[2][3]=1;network[2][4]=0; network[2]
[5]=0;network[2][6]=0; network[3][0]=3;network[3][1]=0;network[3][2]=1;network[3]
[3]=1;network[3][4]=1; network[3][5]=1;network[3][6]=0; network[4][0]=4;network[4]
[1]=0;network[4][2]=0;network[4][3]=1;network[4][4]=1; network[4][5]=0;network[4][6]=0;
network[5][0]=5;network[5][1]=0;network[5][2]=0;network[5][3]=1;network[5][4]=0; network[5]
[5]=1;network[5][6]=1; network[6][0]=6;network[6][1]=0;network[6][2]=0;network[6]
[3]=0;network[6][4]=0; network[6][5]=1;network[6][6]=1;
*/

P a g e | 80 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


/*First row and colmn contains nodes(hops) number starting from 1 to n
*/ for(int I=1;i<=n;i++)
{
network[0][i] = i;
network[i][0] = i;
}

/*Thisis matrix containing the inmforation about connection between hops*/


for(int I=1;i<=n;i++)
{
System.out.println("Row no:"+(i));
for(int j=1;j<=n;j++)
{
System.out.print((j)+": ");
int c=Integer.valueOf(br.nextLine());
if(c==0||C==1)
{
network[i][j]=c;
}
els
e
{
System.out.println("YouenteredOtherthan0or1.\nEnteragain.");
j-=1;

}
}
}

showNetworkMatrix(network,n);
inth= hopCount(network,n); //h used to count maximum time to live
frame System.out.println("Maxium Life of frame : "+h +"\n");
int c;//just a variable used to determine
error do
{
System.out.print("Enter the source node id :");
c=Integer.valueOf(br.nextLine()); if(c==0||
c>n)
System.out.print("Entered wrong id number not available in network.try again.\n");
}while(c==0||c>n);

P a g e | 81 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


int s=c;//source node idvariable
do
{
System.out.println();
System.out.print("Enter the destination node id: ");
c=Integer.valueOf(br.nextLine());
if(c==0||c>n)
{
System.out.print("Entered wrong id number not available in network.try again.\n ");
}
}while(c==0||c>n);

int d=c;//destination nodeidvariable


FloodAlgo(network,n,s,d,h);
}
}

Output

P a g e | 82 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Result
Thus the implementation of Flooding routing protocol is successfully executed and output verified.

P a g e | 83 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO:11.3 MULTICAST ROUTING

Aim
To implement the java program for Muticast Routing protocol.

Algorithm

Multicast Sender
1. Start
2. Import the java.io and java.netpackages.
3. Declare the class “MulticastSender”.
4. Inside class “MulticastSender”, declare thevariables.
5. Creates a datagram socket and binds it with the available Port Number on the localhost machine.
6. Display the message “This is multicast” with counter values.
7. Prompt for and read in a Class D IP Address (Range: 224.0.0.0 – 239.255.255.255).
8. Create an InetAddress object using the getByName() method and the Class D IP Address.
9. Create a new DatagramPacket object with port number 8888 and join the Class D IP Address group.
10. Encapsulate the message in a DatagramPacket object and send the message to the group IP Address.
11. Stop

Multicast Receiver
1. Start
2. Import the java.io and java.netpackages.
3. Declare the class “MulticastReceiver”.
4. Inside class “MulticastReceiver”, declare thevariables.
5. Create an InetAddress object using the getByName() method and the Class D IP Address.
6. Create a new MulticastSocket object with port number 8888 and jointhe Class DIPAddress
group using the joinGroup() method.
7. Encapsulate the message in a DatagramPacket object and receive the message to the group IP Address.
8. Display the message with the IP address.
9. Stop

P a g e | 84 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Source Code
MulticastSender.java
import java.io.*;
import java.net.*;
public class MulticastSender
{
public static void main(String[] args) throws IOException
{
final int PORT =
8888; long counter =
0; String msg;
try
{
DatagramSocket socket = new DatagramSocket();
while (true)
{
msg="This is multicast! "+ counter;
counter++;
byte[] outBuf = msg.getBytes();
// Send to multicast IP address and port
InetAddress address = InetAddress.getByName("224.2.2.3");
DatagramPacket outPacket = new DatagramPacket(outBuf, outBuf.length, address, PORT);
socket.send(outPacket);
System.out.println("Server sends : " + msg);
try
{
Thread.sleep(500);
}

catch (InterruptedException e)
{
System.out.println(e);
}
}
}
catch (IOException ioe)
{
System.out.println(ioe);
}

P a g e | 85 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


}
}

MulticastReceiver.java
import java.io.*;
import java.net.*;
public class MulticastReceiver
{
public static void main(String[] args) throws IOException
{
String msg;
byte[] inBuf = new
byte[256]; try
{
//Prepare to join multicast group
MulticastSocket socket = new MulticastSocket(8888);
InetAddress address = InetAddress.getByName("224.2.2.3");
socket.joinGroup(address);
while(true)
{
DatagramPacket inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
msg = new String(inBuf, 0, inPacket.getLength());
System.out.println("From"+inPacket.getAddress()+"Msg:"+msg);
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}

P a g e | 86 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output
Sender Side

Receiver Side

Result
Thus implementation the java program for Muticast Routing protocol is executed and output
verified.

P a g e | 87 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO:11.4 BROADCAST ROUTING

Aim
To implement the java program using broadcast routing protocol.

Algorithm
Server Program
1. Start
2. Import java.net, java.io and java.utilpackages.
3. Declare a new class called BroadcastServer.
4. Inside the main method declare a new object for datagram socket as soc.
5. Using the Scanner object as in which acts as an inputStreamReader in input.
6. ArrayList class uses a dynamic array for storing the elements.
7. Add() method used to insert the specified element at the specified position index in a list.
8. The message is delievered to the client one by one with the help of the Datagram Packet.
9. Inside the try block declare a get byname () method.
10. To get the address of client by using the port number 5000.
11. Thus display the message as “message successfully sent to client”.
12. Stop

Client Program
1. Start
2. Import java.net, java.io and java.utilpackages.
3. The DatagramSocket and DatagramPacket are initialized with the port no 5000.
4. The message from sender is take as the packet from buffer.
5. Receive the message using DatagramPacketclass.
6. The message is displayed along with the IP address of the server.
7. Stop the program.

P a g e | 88 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Source Code
BroadcastServer.java
import java.net.*;
import java.io.*;
import java.util.*;
public class BroadcastServer
{
public static void main(String args[]) throws Exception
{
String msg, client;
byte[] buf = new byte[1025];
DatagramSocket soc = new DatagramSocket();
Scanner in = new Scanner(new InputStreamReader(System.in));
System.out.println("**** BROADCASTING SERVER ****");
ArrayList <String> data = new ArrayList <String>();
data.add("127.0.0.1");
while(true)
{
System.out.print("Server: ");
msg = in.nextLine();
buf = msg.getBytes();
for(int i = 0; i<data.size(); i++)
{
try
{
client = data.get(i);
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName(client), 5000);
soc.send(dp);
System.out.println("Message Successfully Sent to Client: " + InetAddress.getByName(client));
System.out.println();
}
catch(Exception e)
{
System.out.println("Error " + e);
}
}
}
}
}

P a g e | 89 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


BroadcastClient.java
import java.net.*;
import java.io.*;
public class BroadcastClient
{
public static void main(String args[]) throws Exception
{
String msg;
byte[] buf = new byte[1024];
DatagramSocket soc = new DatagramSocket(5000);
DatagramPacket dp = new DatagramPacket(buf, buf.length);
System.out.println("**** BROADCASTING CLIENT ****");
while(true)
{
tr
y
{
soc.receive(dp);
msg = new String(dp.getData(), 0, dp.getLength());
InetAddress addr = dp.getAddress();
System.out.println("From:"+addr+"Message:"+msg);
System.out.println();

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

P a g e | 90 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output
Server Side

Client Side

Result
Thus the implementation of broadcast routing is executed and output verified.

P a g e | 91 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 12 ADDRESS RESOLUTION PROTOCOL

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

Algorithm
1. Start
2. Import the java.net package.
3. Declare a new class called “ARP”.
4. Create a new object of class InetAddress and initialize it with Local Host IP Address.
5. Display the InetAddress object.
6. Convert the InetAddress object to String object and store in “ip”.
7. Create a new NetworkInterface object and initialize it using the InetAddress object.
8. Create a new byte array “MAC” and initialize it using the getHardwareAddress() method.
9. Create a new StringBuilder object.
10. Repeat the following steps for i = 0 to length of byte array “MAC”:
i. Assign MAC[i] to String“s”.
ii. Convert value in “s” to Integer type and store in integer type variable “j”.
iii. Convert value in “j” to HexString and store in String “sl”.
iv. If “sl” contains more than 2 characters, then get substring of 2 characters from “sl” and store
back in “sl”.
v. If i ≠ 0, then append “-” before the sl value.
vi. Append “sl” to the StringBuilderobject.
11. Display the NetworkInterface name using the method getDisplayName() through
the NetworkInterface object.
12. Display the MAC Address.
13. Stop

P a g e | 92 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Source Code
ARP.java
import java.net.*;
import java.io.*;
public class ARP
{
public static void main(String[] args)
{
tr
y
{
int i;
System.out.println("**** ADDRESS RESOLUTION PROTOCOL ****\n");
InetAddress ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());
System.out.println();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();

System.out.print("Current MAC address : ");


StringBuilder sb = new StringBuilder();

for(i=0; i<mac.length; i++)


{
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
System.out.println(sb.toString());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (SocketException e)
{
System.out.println(e);
}
}
}

P a g e | 93 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Output

Result
Thus the implementation of Address Resolution Protocol are executed and output verified.

P a g e | 94 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: THROUGHPUT COMPARISON BETWEEN 802.3 & 802.11
13

Aim
To study the throughput comparison between IEEE 802.3 and 802.11.

Performance Analysis
In the process of protocol designs and deployments, it is important to understand the
performance of the protocol so that the protocol parameters can be tuned to achieve an optimum
operation in an actual network environment. To make the performance analyses tractable, most
presented performance analyses introduce someassumptions to simplify the protocol operation and/or
the traffic arrival process.

As a result, the obtained analytical results may not be realistic and their applications are
somewhat limited.
Two realistic scenarios that may occur in a LAN – the saturation and the disaster scenarios.
1. The saturation scenario represents a continuous overload condition. The results of this scenario
indicate a fundamental limit of a protocol – its worst performance for a given number of stations.
2. As for the disaster scenario, it models the response of a protocol to the recovery (power up) from a
major failure. This situation is likely to occur in a LAN when the shared channel in the network is
temporarily inaccessible due to, for example, a broken cable or a long period of noise.

The Saturation and the Disaster Scenarios

The Saturation Scenario


There are m stations in a shared LAN using a certain MAC protocol. All m stations share a
common channel for data frame transmission. Under the saturation scenario, the stations are
saturated in the sense that after a completion of each data frame transmission, the station immediately
generates a new data frame for transmission. This scenario models the busiest situation in a network
where the local buffer in each station is never empty. The results of this scenario indicate a
fundamental limit of a protocol that is the worst performance of a protocol for a given number of
stations. The size of the generated data frames may be fixed or variable which can be described by a
certain distribution function.

The Disaster Scenario


The disaster scenario is termed by IEEE 802.14 workgroup to describe a power up situation in
the hybrid fiber coax (HFC) networks. Consider that there are m stations in a shared network, under
this scenario, each station is assumed to carry a data frame for transmission, and all m data
frame transmissions are commenced at the same time. Once a data frame is successfully transmitted,
the station will remain idle. The process for all m stations to successfully transmit their data frames is
defined as a recovery process of the disaster scenario. By the time the last station completes its
P a g e | 95 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU
data frame transmission, the recovery process ends.

P a g e | 96 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Such a scenario is also likely to occur in a LAN when the common channel of the LAN is temporarily
inaccessible because of a broken cable, a faulty hub, a long period of noise or other factors. For this
scenario, mainly focus on the time it takes to clear the backlog of m stations, that is the duration of the
recovery process.

IEEE 802.3 under the Saturation and the Disaster Scenarios


We assume that
1. Stations are arranged in a star topology connected to a multiport repeater, sometimes known as an
Ethernet hub. The distance between any pair of stations is fixed. The signal propagation time from
a station to all other stations is τ units of time.
2. The channel is slotted so that each station can only start its transmission in the beginning of a slot.
3. The collision detection time is ignored. The jam signal transmission is not included.
4. To use a common mechanism for detecting a collision and aborting collided transmissions in a
slotted channel, the minimum duration of a slot is 2Τ [Lam80]. Here we assume that the slot time
is 2Τ.
5. The current IEEE 802.3 MAC protocol exhibits the capture effect causing temporary performance
boost and unfairness. To avoid this transient effect influencing the steady state performance
results, in the analysis, we make a slight modification to the BEB retransmission algorithm. We
adopt the solution proposed by Molle and consider that when a backlog station detects a successful
transmission, it resets its Collision Counter so that after a successful transmission, all stations
access the channel with the same probability. The BEB retransmission algorithm remains the same.
This version of retransmission algorithm provides a conservative prediction to the performance.

In the following, the IEEE 802.3 MAC protocol will be analyzed and simulated under the saturation
and the disaster scenarios based on the assumptions given in the above.

The Saturation Analysis

Comparing the saturation throughput of the protocol with the two different data frame sizes, it
is evident that the protocol performs better if a larger data frame size is used.The figure also shows that
the performance of IEEE 802.3 drops as the number of stations increases. This performance
degradation is more significant for the case of a shorter data frame.

P a g e | 97 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


The Disaster Analysis

The results again suggest that the IEEE 802.3 MAC protocol performs reasonably well for a small
population, but poor for a large population of stations in a LAN.

IEEE 802.11 under the Saturation and the Disaster Scenarios


The Saturation Analysis
1. We consider only a fixed data frame size that is smaller than or equal to the maximum fragment
size specified in the IEEE 802.11standard.
2. All stations are stationary within the same radio coverage. The network contains no hidden or
exposed stations.
3. The signal propagation between any pair of stations is the same.

P a g e | 98 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


Table below summarizes values of some important protocol parameters related to the
FHSS physical layer of IEEE 802.11. The time duration of a collision and a data frame transmission is
provided in Table 3.3.

Figure shows the saturation throughput of IEEE 802.11 versus the number of saturated
stations. From the saturation throughput curves, it is evident that with a good selection of CW
parameters, the IEEE
802.11 MAC protocol performs efficiently for a large population of active stations. The
saturation throughput remains over 80% for the case of CWmin=32 and CWmax=256 for as many as
50 saturated stations.

P a g e | 99 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


The Disaster Analysis

The results shown in Figure again confirm the efficiency of the IEEE 802.11 MAC protocol. For as
many as 50 saturated stations, the recovery process lasts below one second. Even better performance
results are achieved when the four-way handshaking access method is employed.

Result
Thus the study of the throughput comparison between IEEE 802.3 and 802.11 WAS done.

P a g e | 100 COMPUTER NETWORKS DEPARTMENT OF IT, FEAT, AU


EX.NO: 14 KEY DISTRIBUTION AND CERTIFICATION SCHEMES

Aim
To study the various the key distributions and certification schemes.

Introduction
For symmetric key cryptography, the trusted intermediary is called a Key Distribution Center
(KDC), which is a single, trusted network entity with whom one has established ashared secret key.
One can use the KDC to obtain the shared keys needed to communicate securely with all other network
entities. For public key cryptography, the trusted intermediary is called a Certification Authority (CA).
A certification authority certifies that a public key belongs to a particular entity (a person or a network
entity). For a certified public key, if one can safely trust the CA that the certified the key, then one can
be sure about to whom the public key belongs. Once a public key is certified, then it can be distributed
from just about anywhere, including a public key server, a personal Web page or a diskette.

The Key Distribution Center


Suppose once again that Bob and Alice want to communicate using symmetric key
cryptography. They have never met (perhaps they just met in an on-line chat room) and thus have not
established a shared secret key in advance. How can they now agree on a secret key, given that they can
only communicate with each other over the network? A solution often adopted in practice is to use a
trusted Key Distribution Center (KDC).

Kerberos
Kerberos is an authentication service developed at MIT that uses symmetric key encryption
techniques and a Key Distribution Center. Although it is conceptually the same as the generic KDC, its
vocabulary is slightly different. Kerberos also contains several nice variations and extensions of the
basic KDC mechanisms. Kerberos was designed to authenticate users accessing network servers and
was initially targeted for use within a single administrative domain such as a campus or company.
Thus, Kerberos is framed in the language of users who want to access network services (servers) using
application-level network programs such as Telnet (for remote login) and NFS (for access to remote
files), rather than human-to-human conversant who want to authenticate themselves to each other, the
key (pun intended) underlying techniques remains the same. The Kerberos Authentication Server (AS)
plays the role of the KDC. The AS is the repository of not only the secret keys of all users (so that each
user can communicate securely with the AS) but also information about which users have access
privileges to which services on which network servers. The most recent version of Kerberos (V5)
provides support for multiple Authentication Servers, delegation of access rights, and renewable
tickets.

Page| 100 COMPUTERNETWORKSLABORATORY DEPARTMENT OF IT, FEAT, AU


Public Key Certification

One of the principle features of public key encryption is that it is possible for two entities to
exchange secret messages without having to exchange secret keys. For example, when Alice wants to
send a secret message to Bob, she simply encrypts the message with Bob's public key and sends the
encrypted message to Bob; she doesn't need to know Bob's secret (i.e., private) key, nor does Bob need
to know her secret key. Thus, public key cryptography obviates the need for KDC infrastructure, such
as Kerberos. Of course, with public key encryption, the communicating entities still have to exchange
public keys.

A user can make its public key publicly available in many ways, e.g., by posting the key on the
user's personal Web page, placing the key in a public key server, or by sending the key to a
correspondent by e-mail. A Web commerce site can place its public key on its server in a manner that
browsers automatically download the public key when connecting to the site. Routers can place their
public keys on public key servers, thereby allowing other browsers and network entities to retrieve
them.

There is, however, a subtle, yet critical, problem with public key cryptography. To gain insight
to this problem, let's consider an Internet commerce example. Suppose that Alice is in the pizza
delivery business and she accepts orders over the Internet. Bob, a pizza lover, sends Alice a plaintext
message which includes his home address and the type of pizza he wants. In this message, Bob also
includes a digital signature. Alice can obtain Bob's public key (from his personal Web page, a public
key server, or from an e-mail message) and verify the digital signature. In this manner Alice makes
sure that Bob (rather than some adolescent prankster) indeed made the order.

This all sounds fine until clever Trudy comes along. Trudy decides to play a prank. Trudy sends
a message to Alice in which she says she is Bob, gives Bob's home address, and orders a pizza. She also
attaches a digital signature, but she attaches the signature by signing the message digest with her (i.e.,
Trudy's) private key. Trudy also masquerades as Bob by sending Alice Trudy's public key but saying
that it belongs to Bob. In this example, also will apply Trudy's public key (thinking that it is Bob's) to
the digital signature and conclude that the plaintext message was indeed created by Bob. Bob will be
very surprised when the delivery person brings to his home a pizza with everything on it! Here, as in
the flawed authentication scenario, the man-in-the-middle attack is the room cause of our difficulties.
For public key cryptography to be useful, entities (users, browsers, routers, etc.) need to know for sure
that they have the public key of the entity with which they are communicating. For example, when
Alice is communicating with Bob using public key cryptography, she needs to know for sure that the
public key that is supposed to be Bob's is indeed Bob's. Binding a public key to a particular entity is
typically done by a certification authority (CA), which validates identities and issue certificates.

Page| 101 COMPUTERNETWORKSLABORATORY DEPARTMENT OF IT, FEAT, AU


A CA has the following roles:
First to verify that entity (a person, a router, etc) is who it says it is. There are no mandated
procedures for how certification is done. When dealing with a CA, one must trust the CA to have
performed a suitably rigorous identity verification. For example, if Trudy were able to walk into Fly-by-
Night Certificate Authority and simply announce "I am Alice" and receive keys associated with the
identity of "Alice," then one shouldn't put much faith in public keys offered by the Fly-by-Night
Certificate Authority. On the other hand, one might (or might not!) be more willing to trust a CA that is
part of a federal- or state-sponsored program. One can trust the "identify" associated with a public key
only to the extent that one can trust a CA and its identity verification techniques.Once the CA verifies
the entity of the entity, the CA creates a certificate that binds the public key of the identify to the
identity. The certificate contains the public key and identifying information about the owner of the
public key. The certificate is digitally signed by the CA.When Alice receives Bob's order, she gets Bob's
certificate, which may be on his Web page, in an e-mail message or in a certificate server. Alice uses the
CA's public key to verify that the public key in the certificate is indeed Bob's. If we assume that the
public key of the CA itself is known to all (for example, it could published in a trusted, public, and well-
known place, such as The New York Times, so that it is known to all and can not be spoofed), then Alice
can be sure that she is indeed dealing with Bob.

Both the International Telecommunication Union and the IETF have developed standards for
Certification Authorities. ITU X.509 specifies an authentication service as well as a specific syntax for
certificates. RFC 1422 describes CA-based key management for use with secure Internet e-mail. It is
compatible with X.509 but goes beyond X.509 by establishing procedures and conventions for a key
management architecture.

Field name Description


version version number of X.509 specification
serial number CA-issued unique identifier for a certificate
signature specifies the algorithm used by Ca to "sign" this certificate
issuer name identity of CA issuing this certificate, in so-called
Distinguished Name(DN) [RFC 1779] format
validity period start and end of period of validity for certificate
subject name identity of entity whose public key is associated with this
certificate, in DN format
subject public key the subject's public key as well as an indication of the public key
algorithm (and algorithm parameters) to be used with this key

Page| 102 COMPUTERNETWORKSLABORATORY DEPARTMENT OF IT, FEAT, AU


With the recent boom in electronic commerce and the consequent widespread need for secure
transactions, there has been increased interest in Certification Authorities. Among the companies
providing CA services are Cybertrust, Verisign and Netscape. A certificate issued by the US Postal
Service, as viewed through a Netscape browser, is shown in Figure.

One-Time Session Keys


We have seen above that a one-time session key is generated by a KDC for use in symmetric key
encryption of a single session between two parties. By using the one-time session keys from the KDC, a
user is freed from having to establish a priori its own shared key for each and every network entity with
whom it wishes to communicate. Instead, a user need only have one shared secret key for
communicating with the KDC, and will receive one-time session keys from the KDC for all of its
communication with other network entities. One time session keys are also used in public key
cryptography. A public key encryption technique such as RSA is orders of magnitude more
computationally expensive that a symmetric key system such as DES.
Thus, public key systems is often used for authentication purposes. Once two parties have
authenticated each other, they then use public-key-encrypted communication to agree on a shared
one- time symmetric session key.This symmetric session key is then used to encrypt the remainder of
the communication using a more efficient symmetric encryption technique, such as DES.

Result
Thus the study of the various the key distributions and certification schemes was done.

Page| 103 COMPUTERNETWORKSLABORATORY DEPARTMENT OF IT, FEAT, AU


EX.NO: 15 DESIGN OF E-MAIL SYSTEM

Aim
To demonstrate design and implementation of e-mail system.

Design
During the design phase the classes identified in object-oriented analysis must be revisited with a
shift focus to their implementation. New classes or attribute and Methods must be an added for
implementation purposes and user interfaces. Theobject-oriented design process consists of the following
activities:
1. Apply design axioms to design classes, their attributes, methods, associations, structure and
protocols Refine and complete the static UML class diagram by adding details to the UML
diagram.
This step consists of following activities.
 Refine attributes
 Design methods and protocols by utilizing a UML activity diagram to represent the
method‟s algorithms.
 Refine associations between classes
 Refine class hierarchy and design with inheritance
 Iterate and refine again
2. Design the access layer
 Create mirror classes: For every business class identified and created. For example, if there are
three business classes, create three access layer classes.
 Identify access layer class relationships.
 Simplify classes and their relationships: The main goal here is to eliminate redundant classes
and structures.
 Redundant classes: Do not keep two classes that perform similar translate results
activities. Simply select one and eliminate the other.
 Method classes: Revisit the classes that consist of only one or two methods to see if theycan
be eliminated or combined with existing classes.
 Iterate and refine again.

Define the view layer classes


 Design the macro level user interface, identifying view layer objects.
 Design the micro level user interface, which includes these activities:

Design the view layer objects by applying the design axioms and corollaries. Built a prototype of the
view layer interface.
 Test usability and user satisfaction
 Iterate and refine.
Page| 104 COMPUTERNETWORKSLABORATORY DEPARTMENT OF IT, FEAT, AU
3. Iterate refine the whole design process. From the class diagram, you can begin to extrapolate which
classes you will have to build and which existing classes you can reuse. As you do this, also begin
this, also begin thinking about the inheritance structure. If you have several classes that seem
relates but have specific differences. Design also must be traceable across requirements, analysis,
and design from the Requirements model.

Design Axioms
Axioms are a fundamental truth that always is observed to be valid and for which there is no
counter example or exception. Such explains that axioms may be hypothesized form a large number of
observations by nothing the common phenomena shared by all cases; they cannot be proven or
derived, but they can be invalidated by counter examples or exceptions. A theorem is a proposition that
may not be self-evident but can be proven from accepted axioms. If therefore, is equivalent to a law or
principle. A corollary is a proposition that follows from an axioms or another proposition that has been
proven. Again, corollary is shown to be valid or not valid in the same manner as a theorem. In the two
important axioms axiom 1 deals with relationships between system components and axiom 2 deals
with the complexity of design.

The following the two important axioms

Axiom 1: Theindependence axiom, which maintainthe independence of the components.

Axiom 2: The information axioms that maintain the information content of the design.

AxiomS1 states that, during the design process, as we go from requirement and use case to a system
component, each component must satisfy that requirement without affecting other requirements.

An axiom 2 is concerned with simplicity. Scientific theoreticians often rely on a general rule known as
Occam‟s razor, after William of Occam. He says, “The best theory explains the known facts with a
minimum amount of complexity and maximum simplicity and straightforwardness.”

The best designs usually involve the least complex code but not necessarily the fewest number of
classes or methods. Minimizing complexity should be the goal, because that produces the most easily
maintained and enhanced application. In an object-oriented system, the best way to minimize
complexity is to use inheritance and the systems built in classes and to add as little as possible to what
already is there.

From the two design axioms, many corollaries may be derived as a direct consequence of the axioms.
These corollaries may be more useful in marking specific design decisions, since they can be applied to
actual situations.

Page| 105 COMPUTERNETWORKSLABORATORY DEPARTMENT OF IT, FEAT, AU


1. Uncoupled design with less information content: Highly cohesive objects can improve coupling
because only a minimal amount of essential information need be passed between objects. The
degree or strength of coupling between two components is measured by the amount and
complexity of information transmitted between them.
2. Single purpose: Each class must have single, clearly defined purposes.
3. Large number of simple classes: Keeping the classes simple allows reusability. Large and
complex classes are too specialized to bereused.
4. Strong mapping: There must be a strong association between the physical system and logical
design. During the design phase, we need to design this class, design its methods, its association
with other objects. So a strong mapping links classes should be identified.
5. Standardization: promote standardization by designing interchangeable and reusing existing
classes or components.
6. Design with inheritance: Common behavior must be moved to super classes. The super class-sub
class structure must make logical sense.

Refining attributes and methods


Attributes identified in object oriented analyzed must be refined in the design phase. In the
analysis phase, the name of the attributes was sufficient. But in the design phase, detailed information
must be added to the model.

The three basic types of attributes are:


1. Single valued attributes: This has only value or state.
2. Multiplicity or multivalue attributes: This has a collection of many values at any point in time.
3. Instance connection attributes: This is required to provide the mapping needed by an object to
fulfill its responsibilities.

UML attribute presentation

Visibility name: type-expression = initial - value


 Visibility indicates either public visibility or protected visibility or private visibility. The public
visibility indicates that the attribute can be accessible to all classes. The protected visibility
indicates that the accessibility is given to the subclasses and operations of the class. The private
visibility indicates that the accessibility can be given only to the operations of the class only.
 Type expression is a language dependent specification of the implementation type of an attribute.
Initial value is a language dependent expression for the initial value is optional.

Page| 106 COMPUTERNETWORKSLABORATORY DEPARTMENT OF IT, FEAT, AU


Sequence and Collaboration Diagrams
Sequence Diagram
 An interaction diagram shows an interaction, consisting of a set of objects and their
relationships, including the messages that may be dispatched among them.
 A sequence diagram is an interaction diagram that emphasizes the time ordering of messages.
 Graphically, a sequence diagram is a table that shows objects arranged along x-axis and messages,
ordered in increasing time, along the y-axis.

Contents
Sequence diagrams commonly contain the following:
 Objects
 Links
 Messages
Like all other diagrams, sequence diagrams may contain notes and constrains

Sequence

Register Login Inbox Compose Mail AddressBook Update Profile

: User

Fill Form
valid

response

LoginRequest
valid

response

select

response
compose

response
Add contacts

response

update personal details

response

Collaboration Diagram
 Collaboration is a society of classes, interfaces, and other elements that work together to provide
some cooperative behavior that‟s bigger than the sum of all its parts.

Page| 107 COMPUTERNETWORKSLABORATORY DEPARTMENT OF IT, FEAT, AU


 Collaboration is also the specification of how an element, such as a classifier or an operation, is
realized by a set of classifiers and associations playing specific roles used in a specific way

Contents
Collaboration diagrams commonly contain the following:
 Objects
 Links
 Messages
Like all other diagrams, sequence diagrams may contain notes and constrains.

Collaboration

2: valid

5: valid
Register

1: Fill Form

4: LoginRequest 11: Add contacts


Login
3: response AddressBo
ok
12: response
6: response
: User 9: compose
8:
response 14:
response
7: select 10: response
13: update personal details

Inbox
Compose
Update
Mail
Profile

Component Diagram

Inbox Compose
Check

User Mail

Database-
JDBC

Page| 108 COMPUTERNETWORKSLABORATORY DEPARTMENT OF IT, FEAT, AU


Deployment Diagram
 A deployment diagram is a diagram that shows the configuration of run time processing nodes and
the components that live on them.
 Graphically, a deployment diagram is collection of vertices and arcs.

Contents
 Deployment diagram commonly contain the following things:
 Nodes
 Dependency and association relationships
 Like all other diagrams, deployment diagrams may contain notes and constraints.
 Deployment diagrams may also contain components, each of which must live on some node.
 Deployment diagrams may also contain packages or subsystems, both of which are used to
group elements of your model into largerchunks.

Database Server

MySQL Server

Application Server

J2SE
Server

USER
Web Servlets
Browser Application

Result
Thus to design and implement an email system is executed successfully.

Page| 109 COMPUTERNETWORKSLABORATORY DEPARTMENT OF IT, FEAT, AU

You might also like