Top Banner
MANAKULA VINAYAGAR INSTITUTE OF TECHNOLOGY KALITHEERTHALKUPPAM , MADAGADIPET , PUDUCHERRY-605 107 DEPARTMENT OF INFORMATON TECHNOLOGY LAB MANUAL FOR
88
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Lab manual cn-2012-13

MANAKULA VINAYAGAR INSTITUTE OF TECHNOLOGY

KALITHEERTHALKUPPAM , MADAGADIPET , PUDUCHERRY-605 107

DEPARTMENT OF INFORMATON TECHNOLOGY

LAB MANUAL

FOR

COMPUTER NETWORKS

Page 2: Lab manual cn-2012-13

MANAKULA VINAYAGAR INSTITUTE OF TECHNOLOGYKalitheerthaalkuppam, Puducherry – 605 107

Department of Information Technology

List of Experiments

COMPUTER NETWORKS LAB (2012-13 EVEN SEM)[IT P63]

Year/Sem: III/VI Batch: 2010-2014Sl. No Proposed

DateActual Date Experiment Proposed

Sessions1 21.12.12 Study of Socket Programming

12 21.12.12 Finding The IP Address

TCP Communication3 26.12.12 TCP-One Way Communication 14 26.12.12 TCP-Two Way Communication

UDP Communication5 02.01.13 UDP-One Way Communication 16 02.01.13 UDP-Two Way Communication

Socket Programming7 09.01.13 Echo Command 18 09.01.13 Ping Command9 23.01.13 Talk Command 1

File Transfer10 23.01.13 Using TCP 1

Sliding Window Protocol11 30.01.13 1 – Bit Sliding Window Protocol 1

Casting12 06.02.13 Broadcasting 113 06.02.13 Cyclic Redundancy Check 1

Routing Algorithms14 13.02.13 Shortest Path Routing 1

1520.02.13 Remote Method Invocation-

Factorial of A Number 116 27.02.13 Remote Command Execution 117 27.02.13 Study of NS2

Staff-in-Charge HOD

STUDY THE COMMANDS OF SOCKET PROGRAMMINGAIM To study the commands of the socket programming.

Page 3: Lab manual cn-2012-13

IMPLEMENTATION OF SOCKET PROGRAMMING

In this two modules are there:

1. Server.java

2. Client.java

These modules are used to establish a point to point communication between two process using socket programming. The creation of socket can be achieved by the constructors like ServerSocket(), Socket(), these processes then communicate using readline and println().

TCP/IP PROTOCOL TCP/IP Sockets are used to implement, reliable, bidirectional, persistent, point to point stream based connection between host on the internet. There are 2 types of sockets available:1. ServerSocket and 2. Socket. 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 clients connection it can leave pending before it should be refers connections. The default is 50 the constructor might through IOException Otherwise Try{…..} Catch(IOException){…..} should be used .

CLIENT SOCKET 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.

CONSTRUCTOR OF SERVERSOCKETServerSocket(int Port) Creates ServerSocket on the specified port with a queue

length of 50.

ServerSocket(int Port,int Maxqueue). Creates a ServerSocket on the specified port with a maximum queue length of maxqueue.

ServerSocket(int Port, int Maxqueue,Inet Addres local Address)

Creates a SeverSocket on the specified with a maximum queue length of the maxqueue on a multihost,local address specifies the IP Address.

The ServerSocket has one additional method called accept() which is a blocking call that will wait for a client to initiate communication.

Socket(String hostname, int Port) Creates a Socket contaion the local host to the n,amed host the port can throw an unknown host exception or an IOException.

Socket(Inet Address,IPAddress,int port) Creates a Socket using a preexisting Inet Address object and a port can throw an IOException.

METHODInet Address get Inet Address()

Return InetAddress, associated with the socket object.

Page 4: Lab manual cn-2012-13

Inet getport() Return the remote port to which this socket object is connected.

Inet getLocalport() Return the localport to which this socket object is connected.

The following I/O Streams related methods are also available in the socket.InputStream getInput Stream() Return the InputStream associated with the invoking

socket.

OutputStream get outputstream() Return the output stream associated with the invoking socket.

Void close Close both the inputstream and outputstream.

INET ADDRESSING Every computer on the internet has an address. An internet is a number that uniquely identifies each computer on the net. There are 32 bit in an IP Address and we often refer to them has sequence of four number between 0 and 255 separated by the data. This makes them easier to remember because they are not randomly assigned, they are hierarchically assigned. The first few bits define which class of network lettered A,B,C,D or E . The address represents internet or on a class C network since there are 2 million networks in class C .

Static Inet Address get localhost() throws unknown host Exception

Return the Inet address object that represents the localhost

Static Inet Address get by name(String host name)throws unknown host Exception

Returns on an InetAddress for a host name passed to it

Static Inet Address get all by name host Exception Return an array of Inet Address that represent all of the address,meta particular name.

SOME OTHER METHOD Boolean equals(object other) Return true if this object has same name internet

address as other.

Byte[]get address() Return a four element byte array represent the object.

String get Host Address() Return a string that represents that host address associated with InetAddress object

Int hascode() Return the hashcode of the invoking object

Boolena is multicost address Return true if this internet address is a multicost address otherwise it return false.

FINDING THE IP ADDRESS

AIM To write a java program to find the IP address of the system.

Page 5: Lab manual cn-2012-13

ALGORITHM

1. Start the program

2. Create an object for the class InetAddress.

3. An IP address of the system is retrieved using the member function getLocalHost().

4. System number is displayed using the member function getHostName().

5. The IP address of other system can be retrieved by using the member function getByName(),

passing the system number as parameter.

6. Stop the program.

FINDING IP ADDRESS

SOURCE CODE

Page 6: Lab manual cn-2012-13

import java.io.*;import java.net.*;class address{public InetAddress ip;public static void main(String args[])throws UnknownHostException{// To get local machine’s IP address

InetAddress ip=InetAddress.getLocalHost();System.out.println("\n IP address is :"+ip);

// Gets the local machine’s nameString s1=ip.getHostName();

System.out.println("system number is:"+s1);

//To receive the other machine’s nameInetAddress ip1=InetAddress.getByName("system 10");System.out.println("\n name of other system is :"+ip1);}}

OUTPUT

C:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\Java

Page 7: Lab manual cn-2012-13

D:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac address.javaD:\Chitra\Java>java address

IP address is : student1/172.16.11.136system number is: student1

RESULTThus the java program is executed and output is verified successfully.

TCP-ONE WAY COMMUNICATION

AIM

Page 8: Lab manual cn-2012-13

To write a java program to implement one way communication using TCP (Transmission Control Protocol).

ALGORITHM

SERVER

1. Start the program.

2. Import java.net package and other packages.

3. Create objects for ServerSocket, Socket, DataInputStream and PrintStream to transfer the

data.

4. Using PrintStream transfer the data in OutputStream via a port.

5. Run an loop to send the data from server until an “end or exit” string is transferred.

6. If “end or exit” is encountered, close the socket and exit the program.

7. Stop the program.

CLIENT

1. Start the program.

2. Import java.net package and other packages.

3. Create objects for Socket and DataInputStream to receive the server data.

4. Run an loop to receive the data from server and store it in a string using DataInputStream.

5. Display the server data and exit when an “end or exit” message is encountered.

6. Stop the program.

TCP ONE WAY COMMUNICATION

SOURCE CODE

Page 9: Lab manual cn-2012-13

CLIENTimport java.io.*;

import java.net.*;

class tcp1client

{

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

{

Socket s=new Socket("localHost",8000);

//Used to get input from keyword

DataInputStream in=new DataInputStream(s.getInputStream());

while(true)

{

// Reads the input from keybroad

String str=in.readLine();

System.out.println("Message Received:"+str);

if(str.equals("end"))

{

//Close the socket

s.close();

break;

}

}

}

}

SOURCE CODESERVER

Page 10: Lab manual cn-2012-13

import java.io.*;import java.net.*;class tcp1server{public static void main(String a[])throws IOException{ServerSocket ss=new ServerSocket(8000);//Opens the socketSocket s=ss.accept();DataInputStream in=new DataInputStream(System.in);PrintStream dos=new PrintStream(s.getOutputStream());while(true){System.out.println("enter message to send:");//Reads the input from the input deviceString str=in.readLine();dos.println(str);//checks for end of messageif(str.equals("end")){//Closes the socketss.close();break;}}}}

OUTPUTSERVERC:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\Java

Page 11: Lab manual cn-2012-13

D:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac server.javaD:\Chitra\Java>java serverenter message to send:GOOD MORNING HAVE A NICE DAYenter message to send:endD:\Chitra\Java>

CLIENTC:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\JavaD:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java> javac client.javaD:\Chitra\Java> java clientMessage Received:GOOD MORNING HAVE A NICE DAYMessage Received:end

D:\Chitra\Java>

RESULTThus the java program is executed and output is verified successfully.

TCP-TWO WAY COMMUNICATION

AIM

Page 12: Lab manual cn-2012-13

To write a java program to implement two way communication using TCP (Transmission Control Protocol).

ALGORITHAM

SERVER

1. Start the Program.

2. Import java.net package and other packages.

3. Create objects for ServerScoket, Socket and PrintStream to transfer the Server data.

4. Create objects for Scoket and DataInputStream to receive the client data.

5. Using PrintStream transfer the data in OutputStream via a port.

6. Run an loop to send the data from server until an ”end or exit” String is transferred.

7. Using same loop receive the data from server and store it in a string using DataInputStream.

8. Print the received client data and exit when an ”end or exit” message is encountered.

9. Stop the program.

CLIENT

1. Start the program.

2. Import java.net package and other packages.

3. Create objects for Socket, Socket and PrintStream to transfer the client data.

4. Create objects for Socket and DataInputStream to receive the server data.

5. Using PrintStream transfer the data in OutputStream via a port.

6. Run an loop to send the data from server until an “end or exit” string is transferred.

7. Using same loop receive the data from server and store it in a string using DataInputStream.

8. Print the received server data and exit when an “end or exit” message is encountered.

9. Stop the program.

TCP TWO WAY COMMUNICATION

SOURCE CODECLIENT

Page 13: Lab manual cn-2012-13

import java.io.*;import java.net.*;import java.lang.*;class tcp2client{public static void main(String a[])throws IOException{//Creates object for socketSocket s=new Socket("LocalHost",8000);DataInputStream in=new DataInputStream(s.getInputStream());DataInputStream inn=new DataInputStream(System.in);PrintStream dos=new PrintStream(s.getOutputStream());while(true){//Reads the input from the input deviceString str=in.readLine();System.out.println("msg received:"+str);//Checks for end of messageif(str.equals("end")){//Closes the sockets.close();break;}System.out.println("enter the msg to send: ");//Reads the message to sendString str1=inn.readLine();dos.println(str1);//Checks for end of messageif(str1.equals("end")){//Closes the sockets.close();break;}}}}

SERVER

import java.io.*;import java.net.*;

Page 14: Lab manual cn-2012-13

import java.lang.*;class tcp2server{public static void main(String a[])throws IOException{ServerSocket ss=new ServerSocket(8000);//Opens the socketSocket s=ss.accept();PrintStream dos=new PrintStream(s.getOutputStream());DataInputStream in=new DataInputStream(System.in);DataInputStream inn=new DataInputStream(s.getInputStream());while(true){System.out.println("enter the msg to send: ");//Reads the inputString str=in.readLine();dos.println(str);//Checks for end of messageif(str.equals("end")){//Closes the socketss.close();break;}String str1=inn.readLine();System.out.println("msg received"+str1);if(str1.equals("end")){ss.close();break;}}}}

OUTPUTSERVERC:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\Java

Page 15: Lab manual cn-2012-13

D:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac server1.javaD:\Chitra\Java>java server1enter the msg to send:HAI FRIENDSmsg received:HELLOenter the msg to send:endD:\Chitra\Java>

CLIENTC:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\JavaD:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac client1.javaD:\Chitra\Java>java client1

msg received:HAI FRIENDSenter the msg to send:HELLOenter the msg to send:end D:\Chitra\Java>

RESULT

Thus the java program is executed and output is verified successfully.

UDP-ONE WAY COMMUNICATION

AIM

Page 16: Lab manual cn-2012-13

To write a program in java to perform one way message transfer using the User Datagram Protocol (UDP).

ALGORITHM

SERVER

1. Start the program.

2. Import java.net and other necessary packages.

3. Create objects for DatagramSocket and DatagramPacket to send the packet from server.

4. Create an object for InetAddress of the LocalHost.

5. Get user input data and convert it into bytes and send the bytes using DatagramPacket and

DatagramSocket.

6. Get user input in an loop and send data until the user input sends “end”.

7. If end is encountered, exit sending data.

8. Stop the program.

CLIENT

1. Start the program.

1. Import java.net and other necessary Packages.

2. Create objects for DatagramSocket and Datagrampacket to receive the packet data from

server.

3. Create an object for InetAddress of the LocalHost.

4. Receive the data from sender using receive() method and store it to a string.

5. Run an loop and store the data in the string until the received message is “end”.

6. Print the received message.

7. Stop the program.

UDP ONE WAY COMMUNICATION

SOURCE CODESENDER

Page 17: Lab manual cn-2012-13

import java.io.*;import java.net.*;class udp1sender{DatagramSocket ds;DatagramPacket dp;byte buff[]=new byte[1024];String str,str1;boolean i=true;public void send() throws IOException{while(i){ds=new DatagramSocket();DataInputStream in=new DataInputStream(System.in);System.out.println("Enter the msg:");str=in.readLine();buff=str.getBytes();dp=new DatagramPacket(buff,buff.length,InetAddress.getLocalHost(),8000);ds.send(dp);System.out.println("do u want to continue:yes or no");str1=in.readLine();if(str1.equals("yes")){i=true;}else{i=false;}}}public static void main(String args[])throws IOException{ udp1sender se=new udp1sender();se.send();}}

RECEIVERimport java.io.*;import java.net.*;class udp1receiver

Page 18: Lab manual cn-2012-13

{DatagramSocket ds;DatagramPacket dp;byte buff[]=new byte[1024];String str;public void receive() throws IOException{ds=new DatagramSocket(8000);while(true){dp=new DatagramPacket(buff,buff.length);ds.receive(dp);str=new String (dp.getData(),0,0,dp.getLength());System.out.println(str);System.out.println("InetAddress:"+dp.getAddress());} }public static void main(String args[])throws Exception{ udp1receiver re=new udp1receiver();re.receive();} }

OUTPUTSERVER

C:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\Java

Page 19: Lab manual cn-2012-13

D:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac udp1sender.javaD:\Chitra\Java>java udp1sender

Enter the msg:IT KINGSdo u want to continue:yes or nonoD:\Chitra\Java>

CLIENTC:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\JavaD:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac udp1receiver.javaD:\Chitra\Java>java udp1receiver

IT KINGSInetAddress:/172.16.11.99D:\Chitra\Java>

RESULT

Thus the java program is executed and output is verified successfully.

UDP-TWO WAY COMMUNICATION

AIM

Page 20: Lab manual cn-2012-13

To write a java program to perform two way message transfer using the user datagram protocol(UDP).

ALGORITHM

SERVER

1. Start the program.

2. Import java.net and other necessary packages.

3. Create objects for DatagramSocket and DatagramPacket to receive packet data from client.

4. Create an object for InetAddress of the LocalHost.

5. Receive the client data using receive() method and store it in a string.

6. Run a loop and store the data in the string until the received message is “end”.

7. Print the received client’s message.

8. Get user input in the same loop and send the data until the user input is “end”.

9. Convert the user input into bytes and send the byte using DatagramPacket and DatagramSocket.

10. If end is encountered, exit the sending data to client.

11. Stop the program.

CLIENT

1. Start the program.

2. Import java.net and other necessary packages.

3. Create objects for DatagramSocket and DatagramPacket to receive packet data from server.

4. Create an object for InetAddress of the LocalHost.

5. Receive the server data using receive() method and store it in a string.

6. Run a loop and store the data in the string until the received message is “end”.

7. Print the received server’s message.

8. Get user input in the same loop and send data until the user input is end.

9. Convert the user input into bytes and send the byte using DatagramPacket and DatagramSocket.

10. If end is encountered, exit sending data to server.

11. Stop the program.

UDP TWO WAY COMMUNICATION

SOURCE CODE

Page 21: Lab manual cn-2012-13

SERVERimport java.io.*;import java.net.*;class udp2sender{public static void main(String a[])throws Exception{while(true){DatagramSocket ds=new DatagramSocket();BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("enter the msg:");String msg=br.readLine();byte bl[]=msg.getBytes();InetAddress add=InetAddress.getLocalHost();DatagramPacket dp=new DatagramPacket(bl,bl.length,add,1234);ds.send(dp);if(msg.equals("exit"))System.exit(0);byte b[]=new byte[255];DatagramPacket dp1=new DatagramPacket(bl,bl.length);ds.receive(dp1);String msg1=new String(dp1.getData());System.out.println("received msg:" +msg1);}}}

CLIENT

import java.io.*;

Page 22: Lab manual cn-2012-13

import java.net.*;

import java.lang.*;

class udp2receiver

{

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

{

DatagramSocket ds=new DatagramSocket(1234);

byte b[]=new byte[255];

while(true)

{

DatagramPacket dp=new DatagramPacket(b,b.length);

ds.receive(dp);

String msg=new String(dp.getData());

System.out.println("Msg Received:"+msg);

InetAddress add=dp.getAddress();

int port=dp.getPort();

System.out.println("Enter a line of text to send:");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String msg1=br.readLine();

byte b1[]=msg1.getByte();

DatagramPacket dp1=new DatagramPacket(b1,b1.length,add,port);

ds.send(dp1);

if(msg1.equals("exit"))

System.exit(0);

}

}

OUTPUTSERVER

Page 23: Lab manual cn-2012-13

C:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\JavaD:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac udp2sender.javaD:\Chitra\Java>java udp2sender

enter the msg:GOOD MORNINGreceived msg:HAVE A NICE DAYenter the msg:endD:\Chitra\Java>

CLIENTC:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\JavaD:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac udp2receiver.javaD:\Chitra\Java>java udp2receiver

Msg Received:GOOD MORNINGEnter a line of text to send:HAVE A NICE DAYMsg Received:endD:\Chitra\Java>

RESULT:

Thus the java program is executed and output is verified successfully.

ECHO

AIM

Page 24: Lab manual cn-2012-13

To write a program in java to demonstrate the ECHO command.

ALGORITHM

ECHOSERVER

1. Start the program.

2. Import java.net and other necessary packages.

3. Create objects for DataInputStream, Socket and PrintWriter to receive client message and

send it back.

4. Store the message in a string and print the message using print() method.

5. Send the same received message to the client using PrintWriter and Socket.

6. When the received character is ‘.’, then stop sending the data back.

7. Stop the program.

ECHOCLIENT

1. Start the program.

2. Import java.net and other necessary packages.

3. Create objects for ServerSocket and Socket to send the message.

4. Create objects for PrintStream to write message from client to server.

5. Get the user input and store it in a string.

6. Print the string in the Socket using PrintStream to be received by the server.

7. Using the Print() method, receive the client echo message and print it.

8. If the user input is ‘.’, then stop sending the data.

9. Stop the program.

ECHO

SOURCE CODE

Page 25: Lab manual cn-2012-13

ECHO SERVER

import java.io.*;import java.net.*;class echoserver{public static void main(String args[]){try{Socket s=null;ServerSocket ss=new ServerSocket(8000);s=ss.accept();System.out.println(s);BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));PrintWriter print=new PrintWriter(s.getOutputStream());int i=1;while(i>0){String str=br.readLine();if(str.equals("."))break;System.out.println("msg received by client:"+str);print.println(str);print.flush();}}catch(IOException e){System.out.println("\n error:"+e);}}}

ECHO CLIENT

import java.io.*;

Page 26: Lab manual cn-2012-13

import java.net.*;class echoclient{public static void main(String a[]){try{Socket s=new Socket("LocalHost",8000);DataInputStream in=new DataInputStream(System.in);BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));BufferedReader br2=new BufferedReader(new InputStreamReader(s.getInputStream()));PrintWriter print=new PrintWriter(s.getOutputStream());System.out.println("\n msg to be echo:");String str=br1.readLine();print.println(str);print.flush();System.out.println(br2.readLine());}catch(UnknownHostException e){}catch(IOException e){System.out.println("\n error:"+e);}}}

OUTPUT

Page 27: Lab manual cn-2012-13

ECHOCLIENTC:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\JavaD:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac echoclient.javaD:\Chitra\Java>java echoclient

msg to be echo:

GOD IS GREAT

GOD IS GREAT

D:\Chitra\Java>

ECHOSERVERC:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\JavaD:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac echoserver.javaD:\Chitra\Java>java echoserver

Socket[addr=/127.0.0.1,port=1623,localport=8000]

msg received by client:GOD IS GREAT

D:\Chitra\Java>

RESULT

Thus the java program is executed and output is verified successfully.

PING COMMAND

Page 28: Lab manual cn-2012-13

AIMTo write a program in java to demonstrate the usage of PING command.

ALGORITHM

PINGSERVER

1. Start the program.

2. Import java.net and other necessary packages.

3. Initialize the ping server with both sockets as null value.

4. Start the server socket.

5. At the client give the IP address of the server.

6. The client program is then started by starting socket.

7. At the receiver end, the client is pinged.

8. Stop the program.

PINGCLIENT

1. Start the program.

2. Import java.net and other necessary packages.

3. Initialize the ping client with both sockets as null value.

4. Start the socket.

5. Get the IP address of the server.

6. Ping the server.

7. At the receiver end, the server is pinged.

8. Stop the program.

PING COMMAND

Page 29: Lab manual cn-2012-13

SOURCE CODEPING SERVERimport java.io.*;import java.net.*;public class pingserver{public static void main(String a[]){String line1,line2;int i;ServerSocket es;DataInputStream di;PrintStream ps;Socket csoc;es=null;csoc=null;try{es=new ServerSocket(9999);}catch(Exception e){System.out.println(e);}System.out.println("ping server");try{csoc=es.accept();di=new DataInputStream(csoc.getInputStream());ps=new PrintStream(csoc.getOutputStream());for(i=0;i<4;i++){line1=di.readLine();System.out.println("pinged by client");ps.println(line1+"reply from host:bytes=3<time<1ms TT<=128");}di.close();ps.close(); }catch(Exception e){System.out.println(e); } } }

PING CLIENT

Page 30: Lab manual cn-2012-13

import java.io.*;import java.net.*;public class pingclient{public static void main(String args[]){PrintWriter out=null;int i,j,k;BufferedReader networkIn=null;try{System.out.println("enter the IP address:");DataInputStream in = new DataInputStream(System.in);String ip = in.readLine();Socket thesocket = new Socket(ip, 9999);networkIn = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(thesocket.getOutputStream());System.out.println("\npinging" + ip + "with 32 bytes of data\n");for (i = 0; i < 4; i++){out.println(ip);out.flush();String inp = networkIn.readLine();if (inp != null){for (j = 0; j < 10000; j++){for (k = 0; k < 50000; k++){}}System.out.println("reply from" + inp);}else{for (i = 0; i < 4; i++){for (j = 0; j < 10000; j++){for (k = 0; k < 50000; k++){

}System.out.println("\nrequest time out");

Page 31: Lab manual cn-2012-13

}}}}}catch (IOException e){for (i = 0; i < 4; i++){for (j = 0; j < 1000; j++){for (k = 0; k < 5000; k++){}}System.out.println("\nrequest timed out");}}try{if(networkIn!=null)networkIn.close();if(out!=null)out.close();}catch(Exception e){System.out.println("\nrequested time out");}}}

OUTPUT

PING CLIENT

Page 32: Lab manual cn-2012-13

C:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\JavaD:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac pingclient.javaD:\Chitra\Java>java pingclient

enter the IP address:192.168.1.10pinging192.168.1.10with 32 bytes of data5reply from58reply from89reply from94reply from4D:\Chitra\Java>

PINGSERVERC:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\JavaD:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac pingserver.javaD:\Chitra\Java>java pingserver

ping server

pinged by client

pinged by client

pinged by client

pinged by client

D:\Chitra\Java>

RESULT

Thus the java program is executed and output is verified successfully.

IMPLEMENTATION OF TALK COMMAND

Page 33: Lab manual cn-2012-13

AIMTo send and receive message from client and server using connection oriented service.

ALGORITHM

SERVER

1. Start the program.

2. Create server and client sockets.

3. Use input streams to get the message from user.

4. Use output stream to send message to the client.

5. Wait for client to display this message and write a new one to be displayed by the server.

6. Display message given at client using input streams read from socket.

7. If in the message given by server or client, the word “end” is encountered, exit both the programs.

8. Stop the program.

CLIENT

1. Start the program.

2. Create a client socket that connects to the required host and port.

3. Using input streams read message given by server and print it.

4. Using input streams, get message from user to be given to the server.

5. Use output streams to write message to the server.

6. Stop the program.

SOURCE CODETALKSERVER

Page 34: Lab manual cn-2012-13

import java.io.*;import java.net.*;public class talkserver{public static void main(String args[])throws Exception{ServerSocket ecsvr=null;String line1,line2;DataInputStream dis=null;PrintStream pts=null;Socket clsckt=null;BufferedReader in1=null;ecsvr=new ServerSocket(9999);System.out.println("TALK SERVER");System.out.println("----------------------");clsckt=ecsvr.accept();dis=new DataInputStream(clsckt.getInputStream());pts=new PrintStream(clsckt.getOutputStream());System.out.println("Node successfully connected..");while(true){line1=dis.readLine();System.out.println("Message Received");System.out.println("The Message ="+line1);in1=new BufferedReader(new InputStreamReader(System.in));line2=in1.readLine();if(line2.equals("end")){break;}pts.println(line2);pts.flush();System.out.println("Message sent successfully");}dis.close();pts.close();}}

TALK CLIENTimport java.io.*;

Page 35: Lab manual cn-2012-13

import java.net.*;public class talkclient{public static void main(String args[]){PrintWriter out=null;String line1;BufferedReader networkln=null;try{Socket theSocket=new Socket("LocalHost",9999);networkln=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));BufferedReader userln=new BufferedReader(new InputStreamReader(System.in));out=new PrintWriter(theSocket.getOutputStream());System.out.println("TALK CLIENT");System.out.println("--------------------");while(true){System.out.println("send message to server: ");String theLine=userln.readLine();if(theLine.equals("end"))break;out.println(theLine);out.flush();System.out.println("message sent successfully");System.out.println(" ");System.out.println("message received from talkserver: "+networkln.readLine());} }catch(IOException e){System.err.println(e);} try{if(networkln!=null)networkln.close();if(out!=null)out.close();} catch(Exception e){System.err.println(e);} } }

OUTPUTTALKSERVER

Page 36: Lab manual cn-2012-13

C:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\JavaD:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac talkerver.javaD:\Chitra\Java>java talkserver

TALK SERVER----------------------Node successfully connected.Message ReceivedThe Message =HAIHI..Message sent successfullyMessage ReceivedThe Message =HOW ARE YOUI AM FINEMessage sent successfullyMessage ReceivedThe Message =K BYEendD:\Chitra\Java>

TALKCLIENTC:\Documents and Settings\Mitstaff>cd\C:\>cd D:\Chitra\JavaD:\Chitra\Java> set path=c:\program files\java\jdk1.6.0_02\binD:\Chitra\Java>javac talkclient.javaD:\Chitra\Java>java talkclient

TALK CLIENT--------------------send message to server: HAImessage sent successfullymessage received from talkserver: HI..send message to server: HOW ARE YOUmessage sent successfullymessage received from talkserver: I AM FINEsend message to server: K BYEmessage sent successfullysend message to server:endD:\Chitra\Java>

RESULTThus the java program is executed and output is verified successfully.

IMPLEMENTATION OF FTP

Page 37: Lab manual cn-2012-13

AIM:To write a java program to perform “File Transfer Protocol”.

ALGORITHM

SERVER SIDE1. Import the java packages and create class fileserver.2. String of argument is passed to the args[].3. Create a new server socket and bind it to the port.4. Accept the client connection at the requested port.5. Get the filename and stored into the BufferedReader.6. Create a new object class file and readline.7. If File is exists then FileReader read the content until EOF is reached.8. Else Print FileName does’t exits.9. End of main.10. End of FileServer class.

CLIENT SIDE1. Import the java packages and create class fileClient.2. String of argument is passed to the args[].3. The connection between the client and server is successfully established.4. The object of a BufferReader class is used for storing data content which have been

retrieved from socket object s.5. The content are read and stored in inp until the EOF is reached.6. The content of file are displayed in displayed in client window and the connection is

closed.7. End of main.8. End of Fileclient class.

IMPLEMENTATION OF FTP

SOURCE CODE

Page 38: Lab manual cn-2012-13

SERVERimport java.io.*;import java.net.*;public class fileserver1{public static void main(String args[])throws IOException{ServerSocket s1=null;try{s1=new ServerSocket(1187);}catch(IOException u1){System.out.println("could not found port 1187");System.exit(1);}Socket c=null;try{c=s1.accept();System.out.println("connection frame" +c);}catch(IOException e){System.out.println("accept failed");System.exit(1);}PrintWriter out=new PrintWriter(c.getOutputStream(),true);BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));System.out.println("enter the text file name");String s=sin.readLine();File f=new File(s);if(f.exists()){BufferedReader in=new BufferedReader(new FileReader(s));String v;while((v=in.readLine())!=null){

out.write(v);out.flush();

Page 39: Lab manual cn-2012-13

}System.out.println("the file send successfully");in.close();c.close();s1.close();}}}

CLIENT

import java.io.*;import java.net.*;

Page 40: Lab manual cn-2012-13

public class fileclient1{public static void main(String args[])throws IOException{Socket s=null;BufferedReader b=null;try{s=new Socket(InetAddress.getLocalHost(),1187);b=new BufferedReader(new InputStreamReader(s.getInputStream()));}catch(Exception u){System.out.println("the file is received");System.out.println("don't know host");System.exit(1);}String inp;while((inp=b.readLine())!=null){System.out.println("the content of the file is");System.out.println(inp);System.out.println("the file is received successfully");}b.close();s.close();}}

OUTPUT:SERVERC:\Documents and Settings\SEENU.R>cd\C:\>cd C:\Program Files\Java\jdk1.6.0\bin

Page 41: Lab manual cn-2012-13

C:\Program Files\Java\jdk1.6.0\bin>javac fileserver1.javaC:\Program Files\Java\jdk1.6.0\bin>java fileserver1connection frameSocket[addr=/127.0.0.1,port=1056,localport=1187]enter the text file nameHAI.txtthe file send successfullyC:\Program Files\Java\jdk1.6.0\bin>

CLIENT

C:\Documents and Settings\SEENU.R>cd\C:\>cd C:\Program Files\Java\jdk1.6.0\binC:\Program Files\Java\jdk1.6.0\bin>javac fileclient1.javaC:\Program Files\Java\jdk1.6.0\bin>java fileclient1the content of the file isGOD LOVE'S EVERY ONE IN THE WORLD.the file is received successfullyC:\Program Files\Java\jdk1.6.0\bin>

RESULT:Thus the java program is executed and output is verified successfully.

REMOTE METHOD INVOCATION – FACTORIAL OF A NUMBER

Page 42: Lab manual cn-2012-13

AIM:To develop a java program for implementing the remote method invocation.

ALGORITHM:1. Start the program.2. Establish the connection between the client and the server to calculate the factorial

operation.3. In implement() it calls the inter() which throws remote exception thrown by fact().4. In the client URL has been specified and declared as string.5. It calls the inter() to connect with the implement() and get the result.6. Stop.

REMOTE METHOD INVOCATION

SOURCE CODE

Page 43: Lab manual cn-2012-13

SERVER

import java.rmi.*;import java.rmi.server.*;import java.rmi.registry.*;import java.net.*;public class rmiserver{public static void main(String args[]) throws RemoteException{try{implement i=new implement();Naming.rebind("server",i);System.out.println("server reasdy");}catch(Exception e){System.out.println("exception:"+e);}}}

CLIENT:

Page 44: Lab manual cn-2012-13

import java.io.*;import java.rmi.*;import java.rmi.registry.*;import java.net.*;public class rmiclient{public static void main(String args[]) throws RemoteException{try{String host="rmi://LABCSE105/server";inter a=(inter)Naming.lookup(host);System.out.println("Enter a number:");DataInputStream ds=new DataInputStream(System.in);int n=Integer.parseInt(ds.readLine());a.fact(n);}catch(Exception e){}}}

IMPLEMENT:

Page 45: Lab manual cn-2012-13

import java.rmi.*;import java.rmi.server.*;import java.rmi.registry.*;public class implement extends UnicastRemoteObject implements inter{public implement() throws RemoteException{}public void fact(int n) throws RemoteException{int f=1;for(int i=1;i<=n;i++)f=f*i;System.out.println("Factorial of "+n+" is "+f);}}

INTERFACE:

import java.rmi.*;import java.rmi.server.*;public interface inter extends Remote{public void fact(int n) throws RemoteException;}

OUTPUT

SERVER

Page 46: Lab manual cn-2012-13

C:\Documents and Settings\SEENU.R>cd\

C:\>cd C:\Program Files\Java\jdk1.6.0\bin

C:\Program Files\Java\jdk1.6.0\bin>javac inter.java

C:\Program Files\Java\jdk1.6.0\bin>javac implement.java C:\Program Files\Java\jdk1.6.0\bin>javac rmiserver.java C:\Program Files\Java\jdk1.6.0\bin>start rmiregistry C:\Program Files\Java\jdk1.6.0\bin>java rmiserver server ready Factorial of 8 is 40320

CLIENT:

C:\Program Files\Java\jdk1.6.0\bin>cd\ C:\>cd C:\Program Files\Java\jdk1.6.0\bin

C:\Program Files\Java\jdk1.6.0\bin>javac rmiclient.java C:\Program Files\Java\jdk1.6.0\bin>java rmiclient Enter a number: 8

RESULT:Thus the java program is executed and output is verified successfully.

1-BIT SLIDING WINDOW PROTOCOL

Page 47: Lab manual cn-2012-13

AIM:To write a program in java for one bit sliding window protocol.

ALGORITHM:SERVER:

1. Start the program.2. Import .net and other necessary packages.3. Declare objects for input/oiutput and Socket to receive the frame and send acknowledgement.4. Wait for the client to establish connection.5. Receive the frame one by one from the socket and return the frame number as acknowledgement within the thread sleep time.6. send acknowledgement for each receiving frame and continue the process until acknowledgement for all frames are sent.7. when acknowledgement the last frame, exit the program.

CLIENT:

1. Start the program.2. Import .net and other necessary packages.3. Create objects for Serversocket,socket to send the frames.4. Display the server address when the server is connected.5. Get the number of frames to be sent,from the user.6. send the frist frame to servert using the socket.7. when one frame is sent,wait for the acknowledgement from the receiver for the previous

frame.8. Make use of Thread.Sleepa()method to pause the sending of frame until acknowledgement

is received.9. when the acknowledgement is received,send the next frame.10. Continue the process till all specified number of frames are sent and acknowledgement is

received.11. When all the frames are sent and acknowledgement is received exit the program.

1-BIT SLIDING WINDOW PROTOCOL SERVER:

import java.lang.System;import java.net.*;

Page 48: Lab manual cn-2012-13

import java.io.*;class bitserver{public static void main(String[] args){try{BufferedInputStream in;ServerSocket Serversocket=new ServerSocket(500);System.out.println("waiting for connection");Socket client=Serversocket.accept();System.out.println("received request for sending frames");in=new BufferedInputStream(client.getInputStream());DataOutputStream out=new DataOutputStream(client.getOutputStream());int p=in.read();System.out.println("sending.....");for(int i=1;i<=p;++i){System.out.println("sending frame no"+i);out.write(i);out.flush();System.out.println("waiting for acknowledge");Thread.sleep(5000);int a=in.read();System.out.println("received acknowledge for frame no:"+i+"as"+a);}

out.flush();in.close();out.close();client.close();Serversocket.close();System.out.println("quiting");}catch(IOException e){System.out.println(e);}catch(InterruptedException e){}}}CLIENT:import java.lang.System;import java.net.*;import java.io.*;import java.math.*;

Page 49: Lab manual cn-2012-13

class client{public static void main(String a[]){try{InetAddress addr=InetAddress.getByName("Localhost");System.out.println(addr);Socket connection=new Socket(addr,500);DataOutputStream out=new DataOutputStream(connection.getOutputStream());BufferedInputStream in=new BufferedInputStream(connection.getInputStream());BufferedInputStream inn=new BufferedInputStream(connection.getInputStream());BufferedReader ki=new BufferedReader(new InputStreamReader(System.in));int flag=0;System.out.println("connect");System.out.println("enter the no of frames to be requested to server:");int c=Integer.parseInt(ki.readLine());out.write(c);out.flush();int i,jj=0;while(jj<c){i=in.read();System.out.println("received frame no"+i);System.out.println("sending acknowledgement for frame no"+i);out.write(i);out.flush();jj++;}out.flush();in.close();inn.close();out.close();System.out.println("quiting");}catch(Exception e){System.out.println(e);}}}

OUTPUTBITCLIENTC:\Documents and Settings\SEENU.R>cd\C:\>cd C:\Program Files\Java\jdk1.6.0\binC:\Program Files\Java\jdk1.6.0\bin>javac bitclient.java

Page 50: Lab manual cn-2012-13

C:\Program Files\Java\jdk1.6.0\bin>java bitclientLocalhost/127.0.0.1connectenter the no of frames to be requested to server:4received frame no1sending acknowledgement for frame no1received frame no2sending acknowledgement for frame no2received frame no3sending acknowledgement for frame no3received frame no4sending acknowledgement for frame no4quitingC:\Program Files\Java\jdk1.6.0\bin>

BITSERVERC:\Documents and Settings\SEENU.R>cd\C:\>cd C:\Program Files\Java\jdk1.6.0\binC:\Program Files\Java\jdk1.6.0\bin>javac bitserver.javaC:\Program Files\Java\jdk1.6.0\bin>java bitserverwaiting for connectionreceived request for sending framessending.....sending frame no1waiting for acknowledgereceived acknowledge for frame no:1as1sending frame no2waiting for acknowledgereceived acknowledge for frame no:2as2sending frame no3waiting for acknowledgereceived acknowledge for frame no:3as3sending frame no4waiting for acknowledgereceived acknowledge for frame no:4as4quitingC:\Program Files\Java\jdk1.6.0\bin>

RESULT:

Thus the java program is executed and output is verified successfully..

IMPLEMENTATION OF REMOTE COMMAND EXECUTION

Page 51: Lab manual cn-2012-13

AIM:To perform remote command execution (ie) command entered by the user at the client should

be executed by the server.

ALGORITHM:

SERVER:1. Create server and client socket.2. Create a runtime object using getRuntime() method.3. Create a process object p.4. Read the command entered by the user at the client using input streams.5. Execute the command using the exec().

CLIENT:1. Create a client socket corresponding to the required server and port.2. Promote the user to enter the command.3. Read the command using input streams.4. Write the command to the server using output streams.5. lose the streams and socket.

SOURCE CODE

SERVER

Page 52: Lab manual cn-2012-13

import java.io.*;import java.net.*;import java.lang.*;class RCEserver{public static void main(String a[])throwsIOException,UnknownHostException,InterruptedException{ServerSocket ss=new ServerSocket(1000);Socket cs=ss.accept();Runtime r=Runtime.getRuntime();Process p=null;InputStream is=cs.getInputStream();DataInputStream dis=new DataInputStream(is);String s=dis.readLine();System.out.println(s);p=r.exec(s);p.waitFor();}}

CLIENT

import java.io.*;

Page 53: Lab manual cn-2012-13

import java.net.*;import java.lang.*;public class RCEclient{public static void main(String a[])throws UnknownHostException,IOException{Socket c=new Socket("localhost",1000);System.out.println("Enter cmd:");DataInputStream dis=new DataInputStream(System.in);String s=dis.readLine();OutputStream os=c.getOutputStream();DataOutputStream dos=new DataOutputStream(os);dos.write(s.getBytes());dos.close();dis.close();c.close();}}

OUTPUTSERVER

Page 54: Lab manual cn-2012-13

C:\Documents and Settings\SEENU.R>cd\C:\>cd C:\Program Files\Java\jdk1.6.0\binC:\Program Files\Java\jdk1.6.0\bin>javac RCEserver.javaC:\Program Files\Java\jdk1.6.0\bin>java RCEservercalc

CLIENT

C:\Documents and Settings\SEENU.R>cd\C:\>cd C:\Program Files\Java\jdk1.6.0\binC:\Program Files\Java\jdk1.6.0\bin>javac RCEclient.java.C:\Program Files\Java\jdk1.6.0\bin>java RCEclientEnter cmd:calcC:\Program Files\Java\jdk1.6.0\bin>

RESULT:Thus the java program is executed and output is verified successfully.

BROADCASTING

AIM:

Page 55: Lab manual cn-2012-13

To write a java program to send a single message to multiclient.

ALGORITHM:SENDER:

1. Start the program.2. Import .net and other necessary packages.3. The DatagramSocket and the DataInputStream are initialized.4. The buffer is declare for message.5. The message is obtained from the user.6. The message is delievered to the client one by one with the help of the Datagram Packet.7. The client details is obtained.8. If message is ‘bye’ then the server quits.

CLIENT:

1. Start the program.2. Import .net and other necessary packages.3. The DatagramSocket and DatagramPacket are initialized.4. The message from sender is takeb as the packet from buffer.5. The message is displayed along with the IP address of the server.6. If the message is ‘bye’ then the client quits from the transmission and the connection is

terminated.

BROADCASTING

SOURCE CODE

SERVER

Page 56: Lab manual cn-2012-13

import java.net.*;import java.io.*;public class server{public static void main(String args[]) throws Exception{DatagramSocket socket=new DatagramSocket();DataInputStream in=new DataInputStream(System.in);String msg=" ";String client=" ";byte[] buf=new byte[1025];while(true){System.out.println("Server");msg=in.readLine();buf=msg.getBytes();for(int i=1;i<=10;i++){try{client=("sys"+i);DatagramPacket packet=new DatagramPacket(buf,buf.length,InetAddress.getByName(client),5000);socket.send(packet);System.out.println("Message successfully sent to client:"+client);}catch(Exception e){System.out.println("Unable to connect at "+client+e);}if(msg.equalsIgnoreCase("Bye")){System.out.println("Server quits");return;} } } } }

CLIENT:

import java.net.*;

Page 57: Lab manual cn-2012-13

import java.io.*;public class client{public static void main(String args[]) throws Exception{DatagramSocket socket=new DatagramSocket(5000);while(true){try{byte[] buf=new byte[1025];DataInputStream in=new DataInputStream(System.in);String msg=null;DatagramPacket packet=new DatagramPacket(buf,buf.length);socket.receive(packet);msg=new String(packet.getData(),0,packet.getLength());InetAddress addr=packet.getAddress();System.out.println("From :"+addr+"message"+msg);if(msg.equalsIgnoreCase("Bye")){System.out.println("Quits");return;}}catch(Exception e){System.out.println("Error:"+e);}}}}

OUTPUTBROADSERVER

C:\Documents and Settings\SEENU.R>cd\

Page 58: Lab manual cn-2012-13

C:\>cd C:\Program Files\Java\jdk1.6.0_14\binC:\Program Files\Java\jdk1.6.0_14\bin>javac broadsender.javaNote: broadsender.java uses or overrides a deprecated API.Note: Recompile with -Xlint:deprecation for details.C:\Program Files\Java\jdk1.6.0_14\bin>java broadsenderServerGOOD MORNINGUnable to connect at sys1java.net.UnknownHostException: sys1Unable to connect at sys2java.net.UnknownHostException: sys2Unable to connect at sys3java.net.UnknownHostException: sys3Unable to connect at sys4java.net.UnknownHostException: sys4Unable to connect at sys5java.net.UnknownHostException: sys5Unable to connect at sys6java.net.UnknownHostException: sys6Unable to connect at sys7java.net.UnknownHostException: sys7Unable to connect at sys8java.net.UnknownHostException: sys8Unable to connect at sys9java.net.UnknownHostException: sys9Unable to connect at sys10java.net.UnknownHostException: sys10ServerBYEUnable to connect at sys1java.net.UnknownHostException: sys1Server quitsC:\Program Files\Java\jdk1.6.0_14\bin>

BROADRECEIVERC:\Documents and Settings\SEENU.R>cd\C:\>cd C:\Program Files\Java\jdk1.6.0_14\binC:\Program Files\Java\jdk1.6.0_14\bin>javac broadreceive.javaC:\Program Files\Java\jdk1.6.0_14\bin>java broadreceive

RESULT:Thus the java program is executed and output is verified successfully.

CYCLIC REDUNDANCY CHECK

AIM:

Page 59: Lab manual cn-2012-13

To write a java program to implement cyclic redundancy check.

ALGORITHM:

1. Start the program.2. Import necessary packages.3. Get an user input in the form of bit data ie string.4. Get an generator data from the user.5. Read the length of the string and convert the data into another format by deducing 48 from

it.6. Now Add the generator data to the original data and send the string as transmitter string.7. In the receiving end, enter the generator code.8. Using the generator code, to the length of the received string, add 48 to the number format

of the string by character.9. If the generator string is wrong, display “message received with error”.10. If the generator string is correct, perform step 8 and display “message received with no

error”.11. End the program.

CYCLIC REDUNDANCY CHECK

SOURCE CODEimport java.io.*;import java.lang.*;

Page 60: Lab manual cn-2012-13

public class crc{public static void main(String args[]) throws IOException{int f[]=new int[25];int gen[]=new int[10];int rem[]=new int[10];int flen,glen,rlen,i,j;int p,sum,iframe,igen,irem;String data;BufferedReader in=new BufferedReader(new InputStreamReader(System.in));System.out.println("Enter the frame:");data=in.readLine();flen=data.length()-1;for(i=0;i<data.length();i++)f[i]=((int)(data.charAt(i)))-48;System.out.println("Enter the generator:");data=in.readLine();glen=data.length()-1;for(i=1;i<=glen;i++)f[flen+i]=0;flen=flen+glen;for(i=0;i<data.length();i++)gen[i]=((int)(data.charAt(i)))-48;p=0;sum=0;for(i=flen;i>=0;i--){sum=sum+(f[i]*(int)Math.pow(2,p));p=p+1;}iframe=sum;p=0;sum=0;for(i=glen;i>=0;i--){sum=sum+(gen[i]*(int)Math.pow(2,p));

p=p+1;}igen=sum;irem=iframe%igen;irem=igen-irem;iframe+=irem;i=0;

Page 61: Lab manual cn-2012-13

while(iframe>0){f[i]=iframe%2;iframe=iframe/2;i++;}if(iframe==1)f[i]=iframe;System.out.println("Transmitted string:");for(i=flen;i>=0;i--)System.out.print(f[i]);System.out.println("\n enter the received string:");data=in.readLine();flen=data.length()-1;for(i=0;i<data.length();i++)f[i]=((int)(data.charAt(i)))-48;p=0;sum=0;for(i=flen;i>=0;i--){ sum=sum+(f[i]*(int)Math.pow(2,p)); p=p+1; } iframe=sum;irem=iframe%igen;if(irem==0)System.out.println("Message received with no error");elseSystem.out.println("Message received with error");}}

OUTPUT

C:\Documents and Settings\SEENU.R>cd\C:\>cd C:\Program Files\Java\jdk1.6.0\binC:\Program Files\Java\jdk1.6.0\bin>javac crc.javaC:\Program Files\Java\jdk1.6.0\bin>java crc

Page 62: Lab manual cn-2012-13

Enter the frame:10101011Enter the generator:1011Transmitted string:10101011111 enter the received string:1011Message received with no error

C:\Program Files\Java\jdk1.6.0\bin>java crcEnter the frame:10101011Enter the generator:1011Transmitted string:10101011111 enter the received string:1001Message received with errorC:\Program Files\Java\jdk1.6.0\bin>

RESULT:Thus the java program is executed and output is verified successfully.

SHOREST PATH

AIM: To implement the shortest path routing (Dijkstra’s Algorithm) to find the shortest path between the nodes.

ALGORITHM:

Page 63: Lab manual cn-2012-13

1. Dijkstra’s shortest path algorithm computes all shortest path from a single node.2. It can also be used for the all pairs shortest path problem,by the simple expledient of

applying it N times once to each vertex.3. Get the number of nodes in the network for which the shortest path is to be calculated.4. 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.5. 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 smalled d value is removed from T.

c. Each neighbour of in T is examined would be shorter than the currently best known path.

6. The last paths that remain between the nodes are the shortest path between the source node and the destination nodes.

OUTPUTSOURCE CODE:

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

Page 64: Lab manual cn-2012-13

{int n,s,d,i,j,y=0,sd=100;int[] in=new int[10];int[][] m=new int[5][5];int[] dis=new int[10];int[] path=new int[10];DataInputStream a=new DataInputStream(System.in);System.out.println("Enter the no of vertex:");n=Integer.parseInt(a.readLine());System.out.println("Enter the source vertex:");s=Integer.parseInt(a.readLine());System.out.println("Enter the destination vertex:");d=Integer.parseInt(a.readLine());for(i=1;i<n;i++){j=1;while(j<n){System.out.println("Enter the distance between"+i+ "and" +(j+1));m[i][j+1]=Integer.parseInt(a.readLine());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){if(dis[j]<sd){sd=dis[j];y=j;}}}

Page 65: Lab manual cn-2012-13

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;}}}}System.out.println(" "+d+"<----");i=d;while(path[i]!=s){System.out.println(" "+path[i]+"<----");i=path[i];}System.out.println(" "+s);System.out.println("Distance is "+dis[d]);}}

OUTPUT:

C:\Documents and Settings\LABCSE1>cd\C:\>cd C:\Program Files\Java\jdk1.6.0\binC:\Program Files\Java\jdk1.6.0\bin>javac spath.javaC:\Program Files\Java\jdk1.6.0\bin>java spathEnter the no of vertex:3

Page 66: Lab manual cn-2012-13

Enter the source vertex:1Enter the destination vertex:3Enter the distance between1and22Enter the distance between1and31Enter the distance between2and20Enter the distance between2and30 3<---- 1Distance is 1

C:\Program Files\Java\jdk1.6.0\bin>java spathEnter the no of vertex:4Enter the source vertex:1Enter the destination vertex:4Enter the distance between1and22Enter the distance between1and33Enter the distance between1and45Enter the distance between2and20Enter the distance between2and30

Enter the distance between2and42Enter the distance between3and20Enter the distance between3and30Enter the distance between3and4

Page 67: Lab manual cn-2012-13

3 4<---- 2<---- 1Distance is 4

C:\Program Files\Java\jdk1.6.0\bin>

RESULT:

Thus the java program is executed and output is verified successfully.

CRYPTOGRAPHY

AIM: To write a java program to implement client server cryptography.

Page 68: Lab manual cn-2012-13

ALGORITHM:SERVER: 1. Start the program.2. Import .net and other necessary packages.3. Declare objects for Socket,ServerSocket and PrintStream to transfer the encrypted string.4. Initialize string variables to null.5. Get an integer value from the user as key and a string from the user.6. Read the string in character format to its length using charAt().7. Convert each character to integer and add the key value to display it as a encrypted string.8. Send the encrypted string and value to the client using PrintStream an Socket.9. After sending the string and key exit the program.CLIENT:1. Start the program.2. Import .net and other necessary packages.3. Declare objects for Socket and InputStream to receive the string and key from server.4. Store the string and key to different variables.5. Read the string character wise to its length.6. Request the user to enter the key for decryption.7. Compare the key with the received key;8. If both keys are equal then, -Convert the each charater of the string to integer and deduce the key value. - Convert the integer value to character and form it into a string and display the decrypted string. Else

-Print the message as cannot decrypt, wrong message and quit.

9. End the program.

SOURCE CODESERVER

import java.io.*;import java.net.*;class encrypserver{public static void main(String a[])throws Exception

Page 69: Lab manual cn-2012-13

{try{ServerSocket ss=new ServerSocket(1000);Socket s=ss.accept();PrintStream ps=new PrintStream(s.getOutputStream());BufferedReader br=new BufferedReader(new InputStreamReader(System.in));String s2="",s3="";int i=0,k;System.out.println("\n Enter a String :");String s1=br.readLine();System.out.print("\n Enter the key:");k=Integer.parseInt(br.readLine());while(i<s1.length()){char c1=s1.charAt(i++);int n=(int)c1+k+1;c1=(char)n;s2+=c1;n=(int)c1-k-1;c1=(char)n;s3+=c1;}System.out.print("\n Encrypted String :"+s2);ps.println(s2);ps.println(k);ps.close();s.close();ss.close();}catch(Exception e){System.out.print("\n Error :"+e);}}}

CLIENTimport java.io.*;import java.net.*;class decrypclient{public static void main(String args[])throws Exception{try

Page 70: Lab manual cn-2012-13

{Socket s=new Socket("LocalHost",1000);BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));BufferedReader brs=new BufferedReader(new InputStreamReader(System.in));String s1="",s2="";s1=br.readLine();int k1=Integer.parseInt(br.readLine());int i=0;System.out.print("\n Encrypted sender String :"+s1);System.out.print("\n Enter the key :");int k=Integer.parseInt(brs.readLine());if(k==k1){while(i<s1.length()){char c1=s1.charAt(i++);int n=(int)c1-k-1;c1=(char)n;s2+=c1;}System.out.print("\n Decrypted String :"+s2);}else{System.out.print("\n U r unable to decrypt...Wrong key...");System.exit(0);}}catch(Exception e){System.out.print("\n Error :"+e);}}}

OUTPUT

SERVER

C:\Documents and Settings\LABCSE1>cd\C:\>cd C:\Program Files\Java\jdk1.6.0\binC:\Program Files\Java\jdk1.6.0\bin>javac encrypserver.javaC:\Program Files\Java\jdk1.6.0\bin>java encrypserver

Page 71: Lab manual cn-2012-13

Enter a String :GOD IS GREATEnter the key:8 Encrypted String :PXM)R\)P[NJ]C:\Program Files\Java\jdk1.6.0\bin>

CLIENT

C:\Documents and Settings\LABCSE1>cd\C:\>cd C:\Program Files\Java\jdk1.6.0\binC:\Program Files\Java\jdk1.6.0\bin>javac decrypclient.javaC:\Program Files\Java\jdk1.6.0\bin>java decrypclient Encrypted sender String :PXM)R\)P[NJ] Enter the key :8Decrypted String :GOD IS GREATC:\Program Files\Java\jdk1.6.0\bin>

RESULT:

Thus the java program is executed and output is verified successfully.