Sunteți pe pagina 1din 63

Computer Networks Lab Manual FINDING AN IP ADDRESS Ex.No:1 AIM: To write a java program to find an IP address of a system.

ALGORITHM:
STEP 1 : Start STEP 2 : Get the IP Address and name by getLocalHost(). STEP 3 : Using the getHostName() get the name of system. STEP 4 : Store that name in String. STEP 5 : Get the IP Address using that string. Ip = InetAddress.getByName(); STEP 6 : Display the system IP Address. STEP 7 : Stop.

Date:

Computer Networks Lab Manual SOURCE CODE: import java.net.*; import java.io.*;

public class GetIPAddress { public static void main(String [] args) { try { InetAddress thisIp =InetAddress.getLocalHost(); System.out.println("IP:"+thisIp.getHostAddress()); } catch(Exception e) { e.printStackTrace(); } } }

Computer Networks Lab Manual

SAMPLE INPUT AND OUTPUT:

RESULT:
Thus the java program to find an IP address of an system is executed and the output is verified.

Computer Networks Lab Manual ECHO, TALK, PING COMMAND Ex.No:2 AIM To write an java program to illustrate the echo,talk,ping commands.
ALGORITHM: 1. Start the program. 2. To establish a point to point communication between two processes. 3. Creation of sockets using system calls like Socket, bind, listen, connect, accept, establishes a communication link between the two processes. 4. The processes can communicate using Send and receive system calls. 5. The Echo command is used to display a line of text. 6. Ping is used to send ICMP echo request to network hosts. 7. Talk is a virtual communication program which copies lines from terminal to that of another user. 8. Stop the program ALGORITHM: ECHOSERVER 1. Start the program. 2. Import.net and other necessary packages. 3. Declare objects for DataInputStream, Socket and PrintWriter to receive server 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 server using PrintWriter and socket. 6. When the received message is end, then exit the program execution. ECHOCLIENT: 1. Start the program. 2. Import.net and other necessary packages. 3. Declare objects for ServerSocket and Socket to send the message.

Date:

Computer Networks Lab Manual


4. Declare objects for PrintStream to write message from server to client. 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 receiver. 7. Using the Print() method, receive the client echo message and print it. 8. If the message is end, terminate the program and exit. ALGORITHM : PING COMMAND 1. Start the program. 2. Import.net and other necessary packages. 3. Initialize the ping server with both sockets as null value. 4. Start the serversocket. 5. At the client and give the IP address of the server. 6. The client program is then started by starting socket. 7. At the receiver end, the server is pinged

SOURCE CODE

ECHO SERVER
import java.io.*; import java.net.*; public class Echosvr { 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("Echo-Server"); System.out.println("**********"); clsckt=ecsvr.accept(); dis=new DataInputStream(clsckt.getInputStream());

Computer Networks Lab Manual


pts=new PrintStream(clsckt.getOutputStream()); while(true) { line1=dis.readLine(); System.out.println("message Recived"); System.out.println("The message="+line1); if(line1.equals(" ")) { break; } pts.println(line1); pts.flush(); System.out.println("Message sent successfully"); } dis.close(); pts.close(); } }

ECHO CLIENT:
import java.net.*; import java.io.*; public class Eclient { public static void main (String arg[]) { PrintWriter out=null; String line1; BufferedReader networkIn=null; try { Socket theSocket=new Socket("LocalHost",9999); networkIn=new BufferedReader(new InputStreamReader(theSocket.getInputStream())); BufferedReader userIn=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(theSocket.getOutputStream()); System.out.println("ECHO CLIENT"); System.out.println("-----------"); while(true) { System.out.println("send message to server"); String theLine=userIn.readLine(); if(theLine.equals(" ")) break; out.println(theLine);

Computer Networks Lab Manual


out.flush(); System.out.println("message sent succssfully"); System.out.println(" "); System.out.println("message received from Echosvr:"+networkIn.readLine()); } } catch(IOException e) { System.err.println(e); } try { if(networkIn!=null) networkIn.close(); if(out!=null) out.close(); } catch(Exception e) { System.err.println(e); } } } SAMPLE INPUT AND OUTPUT: ECHO SERVER

ECHO CLIENT

Computer Networks Lab Manual

SOURCE CODE TALK SERVER


import java.io.*; import java.net.*; public class talkser { 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();

Computer Networks Lab Manual


System.out.println("message Recived"); System.out.println("The message="+line1); in1=new BufferedReader(new InputStreamReader(System.in)); line2=in1.readLine(); if(line2.equals(" ")) { break; } pts.println(line2); pts.flush(); System.out.println("Message sent successfully"); } dis.close(); pts.close(); } }

TALK CLIENT
import java.net.*; import java.io.*; public class talkcle { public static void main (String arg[]) { PrintWriter out=null; String line1; BufferedReader networkIn=null; try { Socket theSocket=new Socket("LocalHost",9999); networkIn=newBufferedReader(new InputStreamReader(theSocket.getInputStream())); BufferedReader userIn=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(theSocket.getOutputStream()); System.out.println("TALK CLIENT"); System.out.println("-----------"); while(true) { //system.out.println(""); System.out.println("send message to server"); String theLine=userIn.readLine(); if(theLine.equals(" ")) break; out.println(theLine);

Computer Networks Lab Manual


out.flush(); System.out.println("message sent succssfully"); System.out.println(" "); System.out.println("message received from Echosvr:"+networkIn.readLine()); } } catch(IOException e) { System.err.println(e); } try { if(networkIn!=null) networkIn.close(); if(out!=null) out.close(); } catch(Exception e) { System.err.println(e); } } } SAMPLE INPUT AND OUTPUT TALK CLIENT

TALK SERVER

10

Computer Networks Lab Manual

SOURCE CODE: SERVER:


import java.io.*; import java.net.*; public class Pingserver { public static void main(String args[]) { String line1,line2; int i; ServerSocket es; DataInputStream di; PrintStream ps; Socket csoc; es = null; csoc = null; try { es = new ServerSocket(9999);//connect } catch(Exception e)//error handler { System.out.println(e);

11

Computer Networks Lab Manual


} System.out.println("Ping Server"); try { csoc = es.accept();// accept socket di = new DataInputStream(csoc.getInputStream()); ps = new PrintStream(csoc.getOutputStream());//print data for(i=0;i<4;i++) { line1 = di.readLine();//read the received data System.out.println(" Pinged By Client " ); //input message is copied ps.println(line1+": Reply from Host: bytes=32 time<1ms TTL=128");//message sent to client } di.close(); ps.close(); } catch(Exception e) {System.out.println(e);} } }

CLIENT:
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: "); // To Get IP Address DataInputStream in = new DataInputStream(System.in);

12

Computer Networks Lab Manual


String ip= in.readLine(); Socket thesocket = new Socket(ip,9999); //establish connection

networkIn = new BufferedReader ( new InputStreamReader (thesocket.getInputStream()) ); //get data from socket

//BufferedReader userin = new BufferedReader (new InputStreamReader(System.in)); //read data from user out = new PrintWriter(thesocket.getOutputStream()); //Output stream that has print( )/println( ) System.out.println("\nPinging "+ip+" with 32 bytes of data\n"); for (i=0;i<4;i++) { out.println(ip); // send data to socket 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++) {}

13

Computer Networks Lab Manual


} System.out.println("\nRequest Timed Out "); } } } } catch(IOException e) { for(i=0;i<4;i++) { for(j=0;j<10000;j++) { for(k=0;k<50000;k++) } System.out.println("\nRequest Timed Out "); } } try { if(networkIn != null) networkIn.close(); if(out != null) out.close(); } catch(Exception e) { System.out.println("\nRequest Timed Out "); } } } {}

SAMPLE INPUT AND OUTPUT: 14

Computer Networks Lab Manual

PING CLIENT:

PING SERVER:

RESULT:
Thus the java program to implement the ECHO, TALK, PING commands are executed and the output is verified

REMOTE COMMAND EXECUTION

EXNO: 3 AIM:

DATE:

To write a java program for implementing Remote command execution.

ALGORITHM: SERVER:
Step 1: Start the program.

15

Computer Networks Lab Manual


Step 2: Create a socket for the server using Step 3: Register the host address to a specified port at the server side. Step 4: Create a connection queue and listen for incoming client request Step 5: Accept the connection using accepts ( ) method. Step 6: Receive the command from the client to be executed Step 7: Execute the command. Step 8: Send the result to the client side using a buffer. Step 9: Stop the Program execution.

CLIENT: Step 1: Start the program. Step 2: Create a socket for the client Step 3: Get the IP Address. Step 4: Now connect the socket to server. Step 5: Get the command from the user. Step 6: Send the command to the server Step 7: Receive the executed command from the server using a buffer. Step 8: Print the contents of the result. Step 9: Stop the program.

COMMANDSERVER:import java.net.*; 16

Computer Networks Lab Manual import java.io.*; public class commandserver { public static final int port=10; public static void main(String args[]) throws IOException { ServerSocket s=new ServerSocket(port); System.out.println("started:"+s); Socket ser=s.accept(); System.out.println("connection accepted:"+ser); BufferedReader in=new BufferedReader(new InputStreamReader(ser.getInputStream())); PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(ser.getOutputStream())),true); System.out.println("Command executed successfully"); String str=in.readLine(); out.println(str); Process p=Runtime.getRuntime().exec(str); } } COMMANDCLIENT:import java.net.*; import java.io.*; 17

Computer Networks Lab Manual public class commandclient { public static void main(String args[])throws IOException { InetAddress adr=InetAddress.getByName("172.16.1.116"); System.out.println("adr="+adr); Socket ser=new Socket(adr,10); System.out.println("ser"+ser); BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(ser.getOutputStream())),true); System.out.println("Enter a command"); String str=in.readLine(); out.println(str); System.out.println("Command executed successfully"); }} SAMPLE I/O: COMMANDSERVER SIDE Z:\network>javac commandserver.java Z:\network>java commandserver started:ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=10] connection accepted:Socket[addr=/172.16.1.116,port=1209,localport=10] Command executed successfully 18

Computer Networks Lab Manual COMMAND CLIENT SIDE Z:\network>javac commandclient.java Z:\network>java commandclient adr=/172.16.1.116 serSocket[addr=/172.16.1.116,port=10,localport=1209] Enter a command notepad Command executed successfully Z:\network>

RESULT:
Thus the java program for implementing Remote command execution was successfully executed.

URL PARSING AND FILE DOWNLOAD Ex.No:4


AIM: To write a java program for URL parsing and file download

Date:

ALGORITHM:
1. Start the program. 2. Import.net and other necessary packages. 3. Initialize the ping server with both sockets as null value. 4. Start the serversocket. 5. At the client and give the IP address of the server. 6. The client program is then started by starting socket. 7. At the receiver end, the server is pinged and file is sent.

19

Computer Networks Lab Manual


8. Stop

SOURCE CODE: import java.net.*; import java.io.*; import java.util.Date; class URLp { public static void main(String args[]) throws IOException { int c; URL hp = new URL("http://localhost:8080/index.jsp"); URLConnection hpCon = hp.openConnection(); long d = hpCon.getDate(); //getdate if(d == 0) System.out.println("No date information."); else System.out.println("Date: "+new Date(d)); System.out.println("Content-Type: "+hpCon.getContentType()); //get content type int len = hpCon.getContentLength(); //get content length if(len == -1) System.out.println("Content Length unavailable."); else System.out.println("Content Length: "+len); if(len != 0) { System.out.println("=== Content ==="); InputStream input = hpCon.getInputStream(); int i = len; while(((c = input.read()) != -1)) // && (--i > 0)) { System.out.print((char)c); } input.close(); } else 20

Computer Networks Lab Manual { System.out.println("No content available."); } } }

RESULT:
Thus the java program to implement the URL parsing and file download are executed and the output is verified.

URL GRAPPER AND FILE DOWNLOAD Ex.No:5 AIM : To write a java program for URL grapper and file download Date:

ALGORITHM :
1. Start the program. 2. Import.net and other necessary packages. 3. Initialize the ping server with both sockets as null value. 4. Start the serversocket. 5. At the client and give the IP address of the server with File name. 6. The client program is then started by starting socket. 7. At the receiver end, the server is pinged and file is sent.

21

Computer Networks Lab Manual


8. Stop

SOURCE CODE: import java.net.*; import java.io.*; public class URLgrap { public static void main(String args[]) throws Exception { char c; URL url = new URL("http://localhost:8080/index.jsp"); URLConnection connection = url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); int n=1; String line; while(((line = br.readLine()) != null) && (n<=20)) { System.out.println(line); n++; } if( line != null) { } } } 22 System.out.println(".........");

Computer Networks Lab Manual

RESULT:
Thus the java program to implement the URL grapper and file download are executed and the output is verified.

23

Computer Networks Lab Manual CYCLIC REDUNDANCY CHECK

Ex.No: 6

Date:

AIM: To write a java program to show the working of cyclic redundancy check in java. ALGORITHM:
1. Start the program. 2. Import necessary packages. 3. Get a user input in the form of bit data ie string. 4. Get a generator data from the user. 5. Read the length of the string and convert the data into another format by deducing 48from 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. Stop

SOURCE CODE:
import java.io.*; import java.lang.*; class crc { public static void main(String args[]) throws IOException { DataInputStream di=new DataInputStream(System.in); int input[]=new int[25]; int div[]=new int[10];

24

Computer Networks Lab Manual


int a[]=new int[10]; int b[]=new int[10]; int x[]=new int[10]; int temp[]=new int[25]; int output[]=new int[25]; int i,j,k,m,n,l,flag=0; String str; System.out.println("Enter the number of bits for input:"); str=di.readLine(); n=Integer.parseInt(str); System.out.println("Enter the message:"); for(i=0;i<n;i++) { str=di.readLine(); input[i]=Integer.parseInt(str); } System.out.println("Enter the number of bits for divisor:"); str=di.readLine(); m=Integer.parseInt(str); System.out.println("Enter the divisor:"); for(i=0;i<m;i++) { str=di.readLine(); div[i]=Integer.parseInt(str); } for(i=0;i<n;i++) { if(input[i]!=0 && input[i]!=1) { System.out.println("Invalid message!!"); break; } } for(i=0;i<n;i++) temp[i]=input[i]; for(i=0;i<m;i++) x[i]=div[i]; for(i=n;i<n+(m-1);i++) input[i]=0; System.out.println("The appended message is: "); for(i=0;i<n+(m-1);i++) System.out.print(input[i]); for(i=0;i<m;i++)

25

Computer Networks Lab Manual


{ a[i]=input[i]; if(div[i]==1) { if(a[i]==1) { b[i]=0; } else b[i]=1; } else b[i]=a[i]; } k=m; while(k<n+(m-1)) { for(i=0;i<4;i++) { a[i]=b[i+1]; } a[m-1]=input[k]; if(a[0]==0) { for(i=0;i<m;i++) div[i]=0; } else { for(i=0;i<m;i++) div[i]=x[i]; } for(i=0;i<m;i++) { if(div[i]==1) { if(a[i]==1) { b[i]=0; } else b[i]=1; } else b[i]=a[i]; }

26

Computer Networks Lab Manual


k++; } System.out.println("The remainder is:"); for(i=1;i<m;i++) System.out.print(b[i]); l=1; for(i=n;i<n+(m-1);i++) { temp[i]=b[l]; l++; } System.out.println("The transferred message is:"); for(i=0;i<n+(m-1);i++) System.out.print(temp[i]); System.out.println("Enter the received message:"); for(i=0;i<n+(m-1);i++) { str=di.readLine(); output[i]=Integer.parseInt(str); } for(i=0;i<m;i++) { a[i]=output[i]; if(div[i]==1) { if(a[i]==1) { b[i]=0; } else b[i]=1; } else b[i]=a[i]; } k=m; while(k<n+(m-1)) { for(i=0;i<4;i++) { a[i]=b[i+1]; } a[m-1]=output[k]; if(a[0]==0) {

27

Computer Networks Lab Manual


for(i=0;i<m;i++) div[i]=0; } else { for(i=0;i<m;i++) div[i]=x[i]; } for(i=0;i<m;i++) { if(div[i]==1) { if(a[i]==1) { b[i]=0; } else b[i]=1; } else b[i]=a[i]; } k++; } for(i=1;i<m;i++) { if(b[i]==0) { flag=1; } else flag=0; } if(flag==1) System.out.println("The message is transferred successfully!!"); else System.out.println("Errors in message!!"); } }

SAMPLE INPUT AND OUTPUT: 28

Computer Networks Lab Manual

RESULT:
Thus the program for CRC in java is executed and the output is verified.

FILE TRANSFER BETWEEN TWO SYSTEMS USING TCP Ex.No:7 Date: 29

Computer Networks Lab Manual AIM: To enable, file transfer between two computers by creating a socket (TCP) between them. ALGORITHM:
SERVER SIDE 1. 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 doest exits. 9. End of main. 10. End of FileServer class. CLIENT SIDE 1. 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.

30

Computer Networks Lab Manual


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.

CLIENT PROGRAM import java.net.*; import java.io.*; public class tcpClient { public static void main(String[] args) { int port = 1500; String server = args[0]; // Different PC //String server = "127.0.0.1"; Socket socket = null; try //connect to server { socket = new Socket(server, port); System.out.println("Connected with server "+socket.getInetAddress()+":"+socket.getPort()); } catch (UnknownHostException e) 31 // Localhost

Computer Networks Lab Manual { System.out.println(e); System.exit(1); } catch (IOException e) { System.out.println(e); System.exit(1); } try { byte[] buf = new byte[1024]; OutputStream os = socket.getOutputStream(); BufferedOutputStream out = new BufferedOutputStream(os,1024); System.out.println("Enter the file name(sending) : "); DataInputStream get=new DataInputStream(System.in); String file = get.readLine(); //file is read FileInputStream in = new FileInputStream(file); File fnlen=new File(file); long len,finallen; int i; long bytecount=0; 32

Computer Networks Lab Manual len =fnlen.length(); System.out.println("Length of the file to be transfered : " +len); while((len = in.read(buf,0,1) )!= -1) {

bytecount=bytecount+1; out.write(buf,0,1)// Sending one byte per transmission out.flush(); //System.out.println("Amount of bytes transfered"+bytecount+"of "+len); } in.close(); out.close(); System.out.println("Bytes Sent :"+bytecount); } catch (IOException e) { System.out.println(e); } try { 33

Computer Networks Lab Manual socket.close(); } catch (IOException e) { System.out.println(e); } } }

SERVER PROGRAM: import java.net.*; import java.io.*; public class tcpServer { public static void main(String args[]) { int port; ServerSocket server_socket; port = 1500;// Port thru which the connection is to be established try { server_socket = new ServerSocket(port); System.out.println("Server waiting for client on port " + server_socket.getLocalPort()); 34

Computer Networks Lab Manual while(true) // server infinite loop { Socket socket = server_socket.accept(); System.out.println("New connection accepted "+socket.getInetAddress()+":"+socket.getPort()); //Displaying connection information try { byte[] b = new byte[1024]; int len=0; int bytecount=1; System .out.println("Enter the name of the file to be saved : "); DataInputStream get=new DataInputStream(System.in); String FileName=get.readLine();//Getting the file name FileOutputStream inFile = new FileOutputStream(FileName); InputStream is = socket.getInputStream(); BufferedInputStream in = new BufferedInputStream(is,1024); while( (len = in.read(b,0,1) )!= -1 ) //Receving the file one byte per transmission { inFile.write(b,0,1); bytecount=bytecount+1; //System.out.println("Amount of bytes received " +bytecount); } in.close(); inFile.close(); 35

Computer Networks Lab Manual System.out.println("Bytes Writen : "+bytecount); } catch(IOException e) { System.out.println("Unable to open file" + e); return; } try { socket.close(); System.out.println("Connection closed by client"); } catch (IOException e) { } } } catch (IOException e) { System.out.println(e); } } } System.out.println(e);

36

Computer Networks Lab Manual SAMPLE INPUT AND OUTPUT: SERVER:

CLIENT:

RESULT:

Thus the program for file transfer between two computers using

TCP/IP in java is executed and verified.

37

Computer Networks Lab Manual MULTICASTING Ex.No:8 AIM: To write an java program to implement multicasting. 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. 9. Stop 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. 7. Stop

Date:

38

Computer Networks Lab Manual

SOURCE CODE: import java.net.*; import java.io.*; public class multiser { public static void main (String args[]) throws IOException { String ch,ip,rd; DataInputStream dis=new DataInputStream(System.in); System.out.println("Please enter the Class D IP address to from group or join the group"); ip=dis.readLine(); InetAddress group = InetAddress.getByName(ip); System.out.println(group); MulticastSocket s = new MulticastSocket(6789); s.joinGroup(group); System.out.println("Welcome to the group "+ip); do { do { System.out.println("Do u need to send message to a group (yes or no)"); ch=dis.readLine(); if(ch.equals("yes")) { System.out.println("Enter the message"); String msg=dis.readLine(); DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), group, 6789); s.send(hi); byte[] buf = new byte[50]; DatagramPacket recv = new DatagramPacket(buf, buf.length); s.receive(recv); int m= (recv.getLength()); ch= new String(recv.getData()); StringBuffer l=new StringBuffer(ch); l.setLength(m); System.out.println("The Message send to the group is "+l); System.out.println("Do u want send more Message (y or n)"); ch=dis.readLine(); }

39

Computer Networks Lab Manual

else break; }while(ch.equals("y")); do { System.out.println("You are in the listening mode"); byte[] buf = new byte[50]; DatagramPacket recv = new DatagramPacket(buf, buf.length); s.receive(recv); int d= (recv.getLength()); ch= new String(recv.getData()); StringBuffer f=new StringBuffer(ch); f.setLength(d); System.out.println("The Message received from group "+f); System.out.println("Continue in Listenning mode(y or n)"); rd=dis.readLine(); }while(rd.equals("y")); }while(true); } }

40

Computer Networks Lab Manual SAMPLE INPUT AND OUTPUT: SENDER:

RECEIVERS:

41

Computer Networks Lab Manual

RESULT: Thus the program to implement multicasting in java is executed and verified.

42

Computer Networks Lab Manual

REMOTE METHOD INVOCATION (RMI) Ex.No:8 AIM To write a Java Program to implement Arithmetic Operations using Remote Method Invocation (RMI). ALGORITHM: Date:

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(). 6. Stop 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. 6. Stop

43

Computer Networks Lab Manual

SOURCE CODE: ALL SERVER IMPLEMENTATION import java.rmi.*; import java.rmi.server.*; public class AllServerImpl extends UnicastRemoteObject implements AllServerIntf { public AllServerImpl() throws RemoteException { } public double add(double d1, double d2) throws RemoteException { return d1 + d2; } public double sub(double d1, double d2) throws RemoteException { return d1 - d2; } public double mul(double d1, double d2) throws RemoteException { return d1 * d2; }

44

Computer Networks Lab Manual public double div(double d1, double d2) throws RemoteException { return d1 / d2; } } ALL SERVER INTERFACE: import java.rmi.*; public interface AllServerIntf extends Remote { double add(double d1, double d2) throws RemoteException; double sub(double d1, double d2) throws RemoteException; double mul(double d1, double d2) throws RemoteException; double div(double d1, double d2) throws RemoteException; } ALL CLIENTS: import java.rmi.*; public class AllClient { public static void main(String args[]) { try { 45

Computer Networks Lab Manual String allserverURL="rmi://"+args[0]+"/AllServer"; AllServerIntf allserverintf=(AllServerIntf)Naming.lookup(allserverURL); System.out.println("The First Number is"+args[1]); double d1=Double.valueOf(args[1]).doubleValue(); System.out.println("The Second Number is"+args[2]); double d2=Double.valueOf(args[2]).doubleValue();

if(args[3].equals("add")) { System.out.println("The Addition of the Two Number is:"+allserverintf.add(d1,d2)); } if(args[3].equals("sub")) { System.out.println("The Subraction of the Two Number is:"+allserverintf.sub(d1,d2)); }

if(args[3].equals("mul")) { System.out.println("The Multiplication of the Two Number is:"+allserverintf.mul(d1,d2)); 46

Computer Networks Lab Manual }

if(args[3].equals("div")) { System.out.println("The Division of the Two Number is:"+allserverintf.div(d1,d2)); } } catch(Exception e) { System.out.println("Exception :"+e); } } } ALL SERVER: import java.rmi.*; import java.net.*; public class AllServer { public static void main(String args[]) { try { AllServerImpl allserverimpl=new AllServerImpl(); Naming.rebind("rmi://localhost:1099/AllServer",allserverimpl); 47

Computer Networks Lab Manual } catch(Exception e) { System.out.println("Exception :"+e); } } } SAMPLE INPUT AND OUTPUT

48

Computer Networks Lab Manual RESULT: Thus the java program to implement the arithmetic operation using Remote Method Invocation (RMI) is executed and the output is verified.

49

Computer Networks Lab Manual

ROUTING Ex.No:9 Date:

AIM: To implement the shortest path routing to find the shortest path between the nodes. ALGORITHM:
1. Dijkstras 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. 7. Stop

SOURCE CODE:
import java.io.*; class routerdv { public static void main(string args[]) throws ioexception {

50

Computer Networks Lab Manual


int mat[][]=new int[20][20]; int adj_dest[]=new int[20]; int final_dest[]=new int[20]; int n,adjcount; int adj_name[]=new int[10]; int final_name[]=new int[20]; int source; int i,j; DataInputStream dis = new DataInputStream(System.in); System.out.println("Routing Algorith - Distance Vector Method"); System.out.println(); System.out.print("No.Of Nodes in Subnet ? :"); n=Integer.parseInt(dis.readLine()); System.out.print("Enter The Source Node Number : "); source=Integer.parseInt(dis.readLine()); System.out.println("Enter the Number Of Nodes Adjacent to the source node "+source); adjcount=Integer.parseInt(dis.readLine()); System.out.println("Adjacent Node Details.."); for(i=1;i<=adjcount;i++) { System.out.print("Enter the node "+i+" : "); adj_name[i]=Integer.parseInt(dis.readLine()); } for(i=1;i<=adjcount;i++) { System.out.print(adj_name[i]); } System.out.println(); System.out.println(); for(i=1;i<=n;i++) { System.out.print(i); for(j=1;j<=adjcount;j++) mat[i][j]=Integer.parseInt(dis.readLine()); } System.out.println("The Existing Routing Table Is"); for(i=1;i<=n;i++) { System.out.print(i); for(j=1;j<=adjcount;j++) System.out.print("\t"+mat[i][j]); System.out.println(); } for(i=1;i<=adjcount;i++) { System.out.print("Enter the estimated Cost of " +source+ " from "+adj_name[i] +" : ");

51

Computer Networks Lab Manual


adj_dest[i]=Integer.parseInt(dis.readLine()); } for(i=1;i<=n;i++) { final_dest[i]=32767; if(source==i) { final_dest[i]=0; final_name[i]=source; continue; } for(j=1;j<=adjcount;j++) { if((mat[i][j]+adj_dest[j])<final_dest[i]) { final_dest[i]=mat[i][j]+adj_dest[j]; final_name[i]=adj_name[j]; } } } for(i=1;i<=n;i++) { if(source==i) { final_dest[i]=0; final_name[i]=source; break; } } System.out.println("New Routing table for "+source); System.out.println("\tDestination\tDelay\tLine"); for(i=1;i<=n;i++) { System.out.println("\t"+i+"\t"+final_dest[i]+"\t"+final_name[i]); }} }

52

Computer Networks Lab Manual SAMPLE INPUT AND OUTPUT

RESULT:
Thus the program for router in java is executed and the output is verified.

53

Computer Networks Lab Manual

SLIDING WINDOW Ex.No:10 AIM: To write a program in java for sliding window protocol. Date:

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. 8. Stop

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.

54

Computer Networks Lab Manual


8. Make use of Thread.Sleep() method to pause the sending of frame until cknowledgement 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. 12. Stop

SOURCE CODE: SENDER:


import java.net.*; import java.io.*; import java.lang.String; class slidserver { public static void main(String a[]) throws Exception { ServerSocket ser=new ServerSocket(9999); Socket s=ser.accept(); DataInputStream d=new DataInputStream(System.in); DataInputStream d1=new DataInputStream(s.getInputStream()); String strf[]=new String[8]; PrintStream p=new PrintStream(s.getOutputStream()); int sptr=0,sws=8,nf,ano,i,x,q; String z[]=new String[10]; String ch,str; do { System.out.println("Enter the number of frames:"); //returns the integer equivalent of the numeric equivalent with which it was called nf=Integer.parseInt(d.readLine()); p.println(nf); if(nf<=sws-1) { System.out.println("Enter "+nf+" message \n"); for(i=1;i<=nf;i++) { strf[sptr]=d.readLine(); z[i]=strf[sptr];

55

Computer Networks Lab Manual


if(i<3) { System.out.println(" Acknowledgement received \n"); p.println(strf[sptr]); sptr=++sptr%8; } if(i>=3) { System.out.println("Acknowledgement NOT received); sptr=++sptr%8; } } System.out.println(" \n\n Resending Lost Data\n\n\n"); for(i=3;i<=nf;i++) { //strf[sptr]=z[i]; p.println(z[i]); sptr=++sptr%8; System.out.println("Acknowledgement received for frame: "+i +"\n"); } sws-=nf; //returns the integer equivalent of the numeric equivalent with which it was called ano=Integer.parseInt(d1.readLine()); System.out.println("Ack"+ano); sws+=nf; } else { System.out.println("exceeds window size"); break; } System.out.println("do you want to send some more frames"); ch=d.readLine(); p.println(ch); }while(ch.equals("yes")); s.close(); } }

56

Computer Networks Lab Manual


RECEIVER:
import java.net.*; import java.io.*; class slidclient { public static void main(String args[]) throws Exception { Socket s=new Socket("127.0.0.1",9999); DataInputStream dis=new DataInputStream(s.getInputStream()); PrintStream p=new PrintStream(s.getOutputStream()); int i=0,rptr=-1,nf,rws=8; String rtrf[]=new String[8]; String ch; do { //returns the integer equivalent of the numeric equivalent //with which it was called nf=Integer.parseInt(dis.readLine()); if(nf<=rws-1) { for(i=1;i<=nf;i++) { rptr=++rptr%8; rtrf[rptr]=dis.readLine(); System.out.println("frame"+rptr+" "+rtrf[rptr]); System.out.println("acknowledgement sent\n"); } rws-=nf; p.println(rptr+1); rws+=nf; } else break; ch=dis.readLine(); }while(ch.equals("yes")); } }

SAMPLE INPUT AND OUTPUT:

57

Computer Networks Lab Manual


SENDER:

RECEIVER:

RESULT:
Thus the program sliding window in java is executed and the output is verified. IMPLEMENTATION OF FTP

58

Computer Networks Lab Manual


EX.NO : 12 Date:

AIM: To write a java program to simulate File Transfer Protocol.

ALGORITHM: SERVER SIDE 1. 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 doest exits. 9. End of main. 10. End of FileServer class. CLIENT SIDE 1. 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.

59

Computer Networks Lab Manual


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. SOURCE CODE SERVER import 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)

60

Computer Networks Lab Manual


{ 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(); } System.out.println("the file send successfully"); in.close(); c.close(); s1.close(); } } } CLIENT import java.io.*; import java.net.*; public class fileclient1 { public static void main(String args[])throws IOException

61

Computer Networks Lab Manual


{ 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: SERVER C:\Documents and Settings\SEENU.R>cd\ C:\>cd C:\Program Files\Java\jdk1.6.0\bin

62

Computer Networks Lab Manual


C:\Program Files\Java\jdk1.6.0\bin>javac fileserver1.java C:\Program Files\Java\jdk1.6.0\bin>java fileserver1 connection frameSocket[addr=/127.0.0.1,port=1056,localport=1187] enter the text file name HAI.txt the file send successfully C:\Program Files\Java\jdk1.6.0\bin>

CLIENT 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 fileclient1.java C:\Program Files\Java\jdk1.6.0\bin>java fileclient1 the content of the file is GOD LOVE'S EVERY ONE IN THE WORLD. the file is received successfully C:\Program Files\Java\jdk1.6.0\bin>

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

63

S-ar putea să vă placă și