You are on page 1of 67

1

Exp No. 1 IMPLEMENTATION OF TCP/IP SOCKET Date :

AIM:
To write a java program for the implementation of TCP/IP Socket.

ALGORTHIM: SERVER Step 1: Start the program. Step 2: Create a socket for the server Step 3: Accept the connection using the system call, when client requests for connection. Step 4: Create an object for buffer reader to store input data. Step 5: Get the message which has to be sent by the client and display it in server output device. Step 6: Give the response message to the client. Step 7: If the message is received then write the message to the client and Goto step 6. Step 8: If the message is not received then terminate the Process. Step 9: Stop the program execution. CLIENT Step 1: Start the program. Step 2: Create a socket for client system. Step 3: Now connect the socket to server using the system call. Step 4: Create an object for buffer reader to store input data. Step 5: Send message from the Client socket to the server. Step 6: If the message is send to the server then print the message to the server output device and repeat the steps 5 & 6. Step 7: Get the message from the server side. Step 8: Write the message to the client. Step 9: If the message is not received then terminate the process. Step 10: Stop the program execution.

PROGRAM : //TCPServer.java import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String fromclient; String toclient; ServerSocket Server = new ServerSocket (5000); System.out.println ("TCPServer Waiting for client on port 5000"); while(true) { Socket connected = Server.accept(); System.out.println( " THE CLIENT"+" "+ connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED "); BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream())); PrintWriter outToClient = new PrintWriter( connected.getOutputStream(),true); while ( true ) { System.out.println("SEND(Type Q or q to Quit):"); toclient = inFromUser.readLine(); if ( toclient.equals ("q") || toclient.equals("Q") ) { outToClient.println(toclient); connected.close(); break; } else { outToClient.println(toclient); } fromclient = inFromClient.readLine(); if ( fromclient.equals("q") || fromclient.equals("Q") ) { connected.close(); break; } else { System.out.println( "RECIEVED:" + fromclient ); }

} } } } //TCPClient.java import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String FromServer; String ToServer; Socket clientSocket = new Socket("localhost", 5000); BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); PrintWriter outToServer = new PrintWriter( clientSocket.getOutputStream(),true); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); while (true) { FromServer = inFromServer.readLine(); if ( FromServer.equals("q") || FromServer.equals("Q")) { clientSocket.close(); break; } else { System.out.println("RECIEVED:" + FromServer); System.out.println("SEND(Type Q or q to Quit):"); ToServer = inFromUser.readLine(); if (ToServer.equals("Q") || ToServer.equals("q")) { outToServer.println (ToServer) ; clientSocket.close(); break; } else { outToServer.println(ToServer); } }} }} OUTPUT : Server

Client

RESULT: Thus the java program of implementing TCP/IP Socket has been executed and verified successfully.

Exp No. 2

IMPLEMENTATION OF UDP SOCKET Date :

AIM To write a java program for the implementation of UDP Socket. ALGORTHIM Step 1: Start the program. Step 2: Check the condition whether the argument length is equal to one or not. Step 3: If one then create the datagram socket of the Server port address, Call the Server function. Step 4: Otherwise, Create the datagram socket of the Client port address, Call the Client function. Step 5: In Server function, the server gets the message from the client. Step 6: Display the message. Step 7: In Client function, the client deliver the message to the server. Step 8: Stop the program execution.

PROGRAM : WriteServer.java

import java.net.*; class WriteServer { public static int serverPort=555; public static int clientPort=444; public static int buffer_size=1024; public static DatagramSocket ds; public static byte buffer[]=new byte[buffer_size]; public static void TheServer() throws Exception { int pos=0; while(true) { int c=System.in.read(); switch(c) { case -1: System.out.println("Server Quits"); return; case '\r': break; case '\n': ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort)); pos=0; break; default: buffer[pos++]=(byte)c; } } } public static void TheClient() throws Exception { while(true) { DatagramPacket p=new DatagramPacket(buffer,buffer.length); ds.receive(p); System.out.println(new String(p.getData(),0,p.getLength())); } } public static void main(String args[]) throws Exception { if(args.length==1) { ds=new DatagramSocket(serverPort); TheServer(); } else {

ds=new DatagramSocket(clientPort); TheClient(); } } } WriteClient.java import java.net.*; class WriteClient { public static int serverPort=555; public static int clientPort=444; public static int buffer_size=1024; public static DatagramSocket ds; public static byte buffer[]=new byte[buffer_size]; public static void TheServer() throws Exception { int pos=0; while(true) { int c=System.in.read(); switch(c) { case -1: System.out.println("Server Quits"); return; case '\r': break; case '\n': ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort)); pos=0; break; default: buffer[pos++]=(byte)c; } } } public static void TheClient() throws Exception { while(true) { DatagramPacket p=new DatagramPacket(buffer,buffer.length); ds.receive(p); System.out.println(new String(p.getData(),0,p.getLength())); } }

public static void main(String args[]) throws Exception { if(args.length==1) { ds=new DatagramSocket(serverPort); TheServer(); } else { ds=new DatagramSocket(clientPort); TheClient(); } } }

OUTPUT : Server

10

Client

11

RESULT: Thus the Java program of implementing UDP Socket has been executed and the output verified successfully.

12

Exp No. 3 RETRIEVING DATA WITH URLs Date :

AIM To write a java program for retrieve the data using Uniform Resource Locators ALGORITHM Step 1: Start the Program. Step 2: Create an object for the URL class. Step 3: Get the address from which the data is to be retrieved inside the URL class Step 4: Open the URL connection Step 5: Request the content Length, modified date etc. using appropriate the methods. Step 6: Display the contents to the user. Step 7: Stop the program execution.

PROGRAM :

13

import java.net.*; import java.util.Date; import java.io.*; import java.lang.*; class demo { public static void main(String args[]) throws Exception { System.out.println("Enter the URL name : "); BufferedReader bis=new BufferedReader(new InputStreamReader(System.in)); String s=bis.readLine(); URL hp=new URL(s); URLConnection hp1=hp.openConnection(); System.out.println("Date : "+new Date(hp1.getDate())); System.out.println("Content Type : "+hp1.getContentLength()); int l=hp1.getContentLength(); if(l==-1) System.out.println("Content length Unavailable"); else { System.out.println("======CONTENT======"); InputStream input=hp1.getInputStream(); int c; while((c=input.read())!=-1) System.out.println((char)c); input.close(); } } }

OUTPUT :

14

15

RESULT: Thus the java program for retrieving data with URLs has been executed and the output is verified successfully.

Exp No. 4 IMPLEMENTATION OF ECHO

16

Date :

AIM: To write a java program to implement ECHO. ALGORTHIM SERVER: Step 1: Start the program. Step 2: Create a Socket for the Sender and accept the client request.
Step 3: Create an object for input and output data. Step 4: Received the data from the client. Step 5: Display the received data on the server side. Step 6: Stop the program execution. CLIENT:

Step 1: Start the program. Step 2: Create a Socket for the client and send the request to the server. Step 3: Create an object for input and output data. Step 4: Send the data to the server. Step 5: Stop the program execution.

PROGRAM : Echoserver.java

17

import java.net.*; import java.io.*; class echoserver { public static void main(String args[]) { String buff; ServerSocket s; Socket in; try { s=new ServerSocket(4550); in=s.accept(); BufferedReader b=new BufferedReader(new InputStreamReader(in.getInputStream())); PrintWriter pw=new PrintWriter(in.getOutputStream(),true); buff=b.readLine(); System.out.println(buff); pw.println(buff+" was received"); } catch(IOException e) { } }} Echoclient.java import java.net.*; import java.io.*; class echoclient { public static void main(String args[]) { String buff; Socket s; try { s=new Socket("127.0.0.1",4550); BufferedReader b=new BufferedReader(new InputStreamReader(System.in)); BufferedReader b1=new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter pw=new PrintWriter(s.getOutputStream(),true); buff=b.readLine(); pw.println(buff); buff=b1.readLine(); System.out.println(buff); } catch(IOException e) { } }} OUTPUT : Server

18

Client

19

RESULT:

Thus the Java program for implementing ECHO has been executed and the output verified successfully.

Exp No. 5

20

SIMULATION OF BIT SLIDING WINDOW PROTOCOL Date :

AIM To write a java program for the simulation of bit Sliding Window Protocol. ALGORITHM SERVER Step 1: Start the program. Step 2: Create a Socket for the Server and accept the client request . Step 3: Create an object for an input and output data. Step 3: Get the number of frame to be requested for server . Step 4: Send the frames upto the size of the window to the receiver Step 5: If any of the frames are lost then retransmit those frames to the receiver Step 6: Stop the execution. CLIENT Step 1: Start the program. Step 2: Create the Socket for the Client and listen for the frames from the sender. Step 3: If all the frames are successfully received, send the acknowledgement for the last frame to the sender. Step 4: If any of the frames is lost, then send the acknowledgement of the last frame, which was successfully received. Step 5: Keep on receiving and acknowledging the frames until the sender sends. Step 6: Stop the program execution.

PROGRAM : Bitserver.java

21

import java.lang.System; import java.net.*; 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.java import java.lang.System; import java.net.*; import java.io.*;

22

import java.math.*; 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); } } } OUTPUT : Server

23

Client

24

RESULT: Thus the Java program for the simulation of Sliding Window Protocol has been executed and the output is verified successfully.

25

Exp No. 6

SHORTEST PATH ROUTING


Date :

AIM: To write a Java program to find the shortest path routing from the given weighted graph using Dijkstras algorithm.

ALGORITHM: Step 1: Start the program. Step 2: Read the number of nodes. Step 3: Read the adjacency matrix for the graph. Step 4: Read source node and destination node. Step 5: Set the first node is visited then find adjacent of the node. Step 6: From the source node we determine all possible path its destination. Step 7: Print the all-possible paths and its corresponding distance. Step 8: Find the minimum distance. Step 9: Print the minimum distance and its corresponding path. Step 10: Stop the program.

26

PROGRAM : import java.net.*; import java.io.*; class spath { public static void main(String args[]) throws IOException { 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++) for(j=i+1;j<=n;j++) { System.out.println("Enter the distance between"+i+ "and" +(j)); m[i][j]=Integer.parseInt(a.readLine()); } 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=1;i<n;i++) { for(j=1;j<=n;j++) { if(in[j]==0) { if(dis[j]<sd) { sd=dis[j]; y=j; } } } in[y]=1; for(j=1;j<=n;j++) { if((in[j]==0)&&(m[y][j]!=0))

27

{ 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 :

28

29

RESULT: Thus the java program to find the shortest path routing from the given weighted graph has been executed and the output is verified successfully.

Exp No. 7

30

Date :

DOMAIN NAME SYSTEM.

AIM: To write the Java program for Domain Name System.

ALGORTHIM: Step 1: Start the program. Step 2: Create the file for the server, which contains IP address and Domain name. Step 3: Server receive the domain name from the client to be resolved. Step 4: Check the existence of the domain in the server. Step 5: If domain matches then send the corresponding IP address to the client. Step 6: If domain doesnt matches then display IP address is not found. Step 7: Stop the program execution.

PROGRAM :

31

import java.io.*; class dns { public static void main(String args[]) { try { String lookupFile="lookup.txt"; String temp=" "; int flag=0; int flag1=0; BufferedReader br=new BufferedReader(new FileReader(lookupFile)); while((temp=br.readLine())!=null) { String splitvalues[]=null; flag1++; splitvalues=temp.split("-"); if(args[0].equals(splitvalues[0])) { System.out.println("SUCCESS!! FOUND"); System.out.println("IP is"+splitvalues[1]); break; } else { flag++; } } if(flag==flag1) System.out.println("Not Found"); } catch(FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch(IOException ie) { ie.printStackTrace(); } } }

OUTPUT : Lookup.txt

32

--------------www.google.com-121.0.0.12 www.yahoo.com-12.4.5.3 www.gmail.com-121.0.1.13

33

RESULT: Thus the java program for Domain name System has been executed and the output is verified successfully.

Exp No. 8

34

Date :

FILE TRANSFERING USING FTP

AIM: To write the program for transferring text file from server to client using FTP. ALGORITHM: SERVER Step 1: Start the program. Step 2: In the server side establish the connection from server. Step 3: Read the data stored in the file as character format. Step 4: Then we convert collection of characters into string forms and store this string into output buffer.

Step 5: At last we store the EOF string to the out object. Step 6: Terminate the connection after sending the data to client side. Step 7: Stop the program. CLIENT Step 1: Start the program Step 2: In the client side to connect with server we read the server name and connect the server program using port number. Step 3: Then read the source file name for getting the data from the server. Step 4: Create the output file in the client side. Step 5: Using this file output stream object we store the data in the format of character after getting string from output buffer of server program. Step 6: After writing the data into the output file close the connection. Step 7: Stop the program.

PROGRAM :

35

Fileserver.java import java.io.*; import java.net.*; class fileserver { public static void main(String a[]) throws Exception { char ch[]=new char[100]; String str; int i=0,j; ServerSocket ss=new ServerSocket(1982); Socket s=ss.accept(); BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true); String fname=in.readLine(); System.out.println(fname); FileInputStream fin=new FileInputStream("mms.txt"); while(true) { for(i=0;i<30;i++) { j=fin.read(); ch[i]=(char)j; if(j==-1) break; } str=new String(ch,0,i); out.println(str); if(i!=30) break; } out.println("EOF"); in.close(); out.close(); s.close(); } } Fileclient.java import java.io.*; import java.net.*; class fileclient { public static void main(String a[]) throws Exception { BufferedReader in1=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the host name :"); Socket s=new Socket(InetAddress.getByName(in1.readLine()),1982);

36

BufferedReader in2=new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true); System.out.println("Enter the source name: "); out.println(in1.readLine()); System.out.println("Enter the Destination name: "); FileOutputStream o=new FileOutputStream(in1.readLine()); String data; int i=0; while(true) { data=in2.readLine(); if(data.equals("EOF")) break; char ch[]=new char[120]; data.getChars(0,data.length(),ch,0); for(i=0;i<data.length();i++) o.write(ch[i]); } o.close(); in1.close(); in2.close(); out.close(); s.close(); } }

OUTPUT : Server

37

Client

38

RESULT Thus the java program for transferring text file from server to client been executed and the output is verified successfully.

Exp No. 9

39

Date :

REMOTE COMMAND EXECUTION

AIM: To write a program for implementing chatting using single program in change mode operation. ALGORITHM: SERVER MODE: Step 1: Start the program. Step 2: Enter the server modes using keyboard. Step 3: In this server mode executes the following statements under while loop until we give input as bye. i) Read the input data and stored in string variable input. ii) Then create the output buffer. iii) Store the input data on the output buffer for sending to client side. iv) Then change the mode froms to c. Now it can act as client mode. Step 4: Terminate the connection when you give input as bye. Step 5: Stop the program. CLIENT MODE Step 1: Start the program. Step 2: Enter the client mode c using keyboard. Step 3: In this client mode executes the following statements under while loop until we give input as bye. i) Get the ip address of the server from. ii) Create the input buffer then input data in the output buffer automatically stored in object. iii) Then read the data in the format of string. iv) Then print the received data in our user screen. v) Change the mode from c tos. Now it can act as server mode. Step 4: Terminate the connection when you give input as bye. Step 5: Stop the program.

PROGRAM : import java.io.*;

40

import java.net.*; import java.lang.*; class rme_chat { public static void main(String a[]) throws Exception { BufferedReader keyin=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the mode(S)erver or (C)lient :"); String mode=keyin.readLine(); String userinput=" "; InetAddress remotemachine=null; while(!userinput.equals("bye")) { if(mode.equals("s")) { ServerSocket ss=new ServerSocket(1982); Socket cs=ss.accept(); if(remotemachine==null) remotemachine=cs.getInetAddress(); PrintWriter ot=new PrintWriter(cs.getOutputStream()); System.out.print("Message :"); userinput=keyin.readLine(); ot.println(userinput); ot.flush(); mode="c"; ss.close(); cs.close(); } else { if(remotemachine==null) { String hostname=" "; System.out.println("Enter the remote host name: "); hostname=keyin.readLine(); remotemachine=InetAddress.getByName(hostname); } Socket cs=new Socket(remotemachine,1982); BufferedReader socketin=new BufferedReader(new InputStreamReader(cs.getInputStream())); userinput=socketin.readLine(); System.out.println("Response :" +userinput); mode="s"; cs.close(); socketin=null; }}}} OUTPUT : Server mode

41

Client mode

42

RESULT: Thus the java program for implementing chatting using single program in change mode operation has been executed and the output is verified successfully.

Exp No. 10

43

Date :

CHAT APPLICATION

AIM: To write the program for chatting between the users using awt tools. ALGORITHM: SERVER Step 1: Start the program. Step 2: First design the server side window by adding text box, text area, Send button, exit button, label and Panel. Step 3: At the server side it can get the text from the text box then print in text area of the server. Step 4: At the same time create the output buffer then store the given input text into the buffer. Step 5: In this server side it gets the data from the client output buffer and print this data as client message in the server side. Step 6: After committing the application terminate the connection. Step 7: Stop the program. CLIENT Step 1: Start the program. Step 2: First design the Client side window by adding text box, text area, Send button, exit button, label and Panel. Step 3: At the client side it can get the text from the text box then print in text area of the client. Step 4: At the same time create the output buffer then store the given input text into the buffer. Step 5: In this client side it gets the data from the client output buffer and print this data as client message in the client side. Step 6: After committing the application terminate the connection. Step 7: Stop the program. PROGRAM :

44

Serchat.java import java.io.*; import java.awt.*; import java.awt.event.*; import java.net.*; class serchat extends Frame implements ActionListener { Label l; TextField tf; Button bb; TextArea ta; Panel p; byte[] b,b1; serchat() { b=new byte[1000]; p=new Panel(); p.setBackground(Color.gray); l=new Label("Message : "); tf=new TextField(20); bb=new Button("Send"); bb.addActionListener(this); p.add(l); p.add(tf); p.add(bb); add(p); ta=new TextArea(15,15); ta.setBackground(Color.gray); add(ta,BorderLayout.SOUTH); setTitle("Server:->I-M.E CSE(2)"); setSize(400,300); setVisible(true); setResizable(true); } public void actionPerformed(ActionEvent ae) { try { if(!(tf.getText()).equals("")) { ta.append("Server: "+tf.getText()+"\n"); b1=tf.getText().getBytes(); DatagramSocket ds=new DatagramSocket(); DatagramPacket send=new DatagramPacket(b1,b1.length,InetAddress.getLocalHost(),1982); tf.setText(" "); ds.send(send); } tf.requestFocus();

45

} catch(Exception e) { System.out.println(e); } } public void create() { try { DatagramSocket ds=new DatagramSocket(1985); while(true) { DatagramPacket receive=new DatagramPacket(b,b.length); ds.receive(receive); byte b2[]=new byte[100]; b2=receive.getData(); ta.append("Client: "+new String(b2)); ta.append("\n"); } } catch(Exception e) { System.out.println(e); } } public static void main(String a[]) { serchat s=new serchat(); s.create(); } } Clichat.java import java.io.*; import java.awt.*; import java.awt.event.*; import java.net.*; class clichat extends Frame implements ActionListener { Label l; TextField tf; Button bb,button1; TextArea ta; Panel p; byte[] b,b1; clichat()

46

{ b=new byte[1000]; p=new Panel(); p.setBackground(Color.gray); l=new Label("Message : "); tf=new TextField(20); bb=new Button("Send"); button1=new Button("Exit"); bb.addActionListener(this); p.add(l); p.add(tf); p.add(bb); p.add(button1); add(p); ta=new TextArea(15,15); ta.setBackground(Color.gray); add(ta,BorderLayout.SOUTH); setTitle("Client:->I-M.E CSE(1)"); setSize(400,300); setVisible(true); setResizable(true); } public void actionPerformed(ActionEvent ae) { if(ae.getSource().equals(button1)) System.exit(0); else { try { if(!(tf.getText()).equals("")) { ta.append("Client: "+tf.getText()+"\n"); b1=tf.getText().getBytes(); DatagramSocket ds=new DatagramSocket(); DatagramPacket send=new DatagramPacket(b1,b1.length,InetAddress.getLocalHost(),1985); tf.setText(" "); ds.send(send); } tf.requestFocus(); } catch(Exception e) { System.out.println(e); } } } public void create() {

47

try { DatagramSocket ds=new DatagramSocket(1982); while(true) { DatagramPacket receive=new DatagramPacket(b,b.length); ds.receive(receive); byte b2[]=new byte[receive.getLength()]; b2=receive.getData(); ta.append("Server: "+new String(b2)); ta.append("\n"); } } catch(Exception e) { System.out.println(e); } } public static void main(String a[]) { clichat s=new clichat(); s.create(); } }

OUTPUT : Server

48

Client

49

RESULT: Thus the java program for implementing chatting between the users using awt tools has been executed and the output is verified successfully.

Exp No. 11

50

Date :

SIMULATION OF SNMP

AIM : To simulate the SNMP using java eclipse. ALGORITHM : Step 1: Start the program. Step 2: Use the necessary Packages. Step 3: Open the program with the help of eclipse Step 4: Set the path of the program. Step 5: Compile and debug the program. Step 6: Stop the program.

PROGRAM :

51

package SNMP4JHelper; import org.snmp4j.CommunityTarget; import org.snmp4j.PDU; import org.snmp4j.Snmp; import org.snmp4j.TransportMapping; import org.snmp4j.event.ResponseEvent; import org.snmp4j.event.ResponseListener; import org.snmp4j.mp.SnmpConstants; import org.snmp4j.smi.*; import org.snmp4j.transport.DefaultUdpTransportMapping; public class SNMP4JHelper { public static final String READ_COMMUNITY = "public"; public static final String WRITE_COMMUNITY= "private"; public static final int mSNMPVersion =0; // 0 represents SNMP version=1 public static final String OID_UPS_OUTLET_GROUP1 = "1.3.6.1.4.1.318.1.1.1.12.3.2.1.3.1"; public static final String OID_SYS_DESCR="1.3.6.1.2.1.1.1.0"; public static void main(String[] args) { try { String strIPAddress = "127.0.0.1"; SNMP4JHelper objSNMP = new SNMP4JHelper(); //objSNMP.snmpSet(); int Value = 2; String batteryCap =objSNMP.snmpGet(strIPAddress,READ_COMMUNITY,OID_SYS_DESCR); } catch (Exception e) { e.printStackTrace(); } } public void snmpSet(String strAddress, String community, String strOID, int Value) { strAddress= strAddress+"/"+161; Address targetAddress = GenericAddress.parse(strAddress); Snmp snmp; try { TransportMapping transport = new DefaultUdpTransportMapping(); snmp = new Snmp(transport); transport.listen(); CommunityTarget target = new CommunityTarget(); target.setCommunity(new OctetString(community)); target.setAddress(targetAddress); target.setRetries(2); target.setTimeout(5000); target.setVersion(SnmpConstants.version1); PDU pdu = new PDU(); pdu.add(new VariableBinding(new OID(strOID), new Integer32(Value)));

52

pdu.setType(PDU.SET); ResponseListener listener = new ResponseListener() { public void onResponse(ResponseEvent event) { ((Snmp)event.getSource()).cancel(event.getRequest(), this); System.out.println("Set Status is:"+event.getResponse().getErrorStatusText()); } }; snmp.send(pdu, target, null, listener); snmp.close(); } catch (Exception e) { e.printStackTrace(); } } public String snmpGet(String strAddress, String community, String strOID) { String str=""; try { OctetString community1 = new OctetString(community); strAddress= strAddress+"/" + 161; Address targetaddress = new UdpAddress(strAddress); TransportMapping transport = new DefaultUdpTransportMapping(); transport.listen(); CommunityTarget comtarget = new CommunityTarget(); comtarget.setCommunity(community1); comtarget.setVersion(SnmpConstants.version1); comtarget.setAddress(targetaddress); comtarget.setRetries(2); comtarget.setTimeout(5000); PDU pdu = new PDU(); ResponseEvent response; Snmp snmp; pdu.add(new VariableBinding(new OID(strOID))); pdu.setType(PDU.GET); snmp = new Snmp(transport); response = snmp.get(pdu,comtarget); if(response != null) { if(response.getResponse().getErrorStatusText().equalsIgnoreCase("Success")) { PDU pduresponse=response.getResponse(); str=pduresponse.getVariableBindings().firstElement().toString(); if(str.contains("=")) { int len = str.indexOf("="); str=str.substring(len+1, str.length()); } } } else {

53

System.out.println("Feeling like a TimeOut occured "); } snmp.close(); } catch(Exception e) { e.printStackTrace(); } System.out.println("Response="+str); return str; } }

OUTPUT :

54

55

RESULT :
Thus the Java program for the simulation of SNMP has been executed and the output is verified successfully.

Exp No. 12

56

Date :

STUDY OF NS2 NETWORK SIMULATOR

AIM To study about NS2 - Network Simulator INTRODUCTION NS is a discrete event simulator targeted at networking research. NS provides substantial support for simulation of TCP, routing, and multicast protocols over wired and wireless (local and satellite) networks. NS began as a variant of the REAL network simulator in 1989 and has evolved substantially over the past few years. In 1995 ns development was supported by DARPA through the VINT project at LBL, Xerox PARC, UCB, and USC/ISI. Currently ns development is support through DARPA with SAMAN and through NSF with CONSER, both in collaboration with other researchers including ACIRI. NS has always included substantal contributions from other researchers, including wireless code from the UCB Daedelus and CMU Monarch projects and Sun Microsystems. The network simulator ns-2 is a widely accepted discrete event network simulator, actively used for wired and wireless network simulations. It has a highly detailed model of the lower layers (Physical and MAC) of wireless IEEE 802.11 networks. Ns-2 has also an emulation feature, i.e. the ability to introduce the simulator into a live network and to simulate a desired network between real applications in real-time. Within the scope of this project we developed some methods and extensions to the ns-2 to combine wireless network simulation and network emulation. OVERVIEW NS is an event driven network simulator developed at UC Berkeley that simulates variety of IP networks. It implements network protocols such as TCP and UDP, traffic source behavior such as FTP, Telnet, Web, CBR and VBR, router queue management mechanism such as Drop Tail, RED and CBQ, routing algorithms such as Dijkstra, and more. NS also implements multicasting and some of the MAC layer protocols for LAN simulations. The NS project is now a part of the VINT project that develops tools for simulation results display, analysis and converters that convert network topologies generated by well-known generators to NS formats. Currently, NS (version 2) written in C++ and OTcl (Tcl script language with Object-oriented extensions developed at MIT) is available. This document talks briefly about the basic structure of NS, and explains in detail how to use NS mostly by giving examples. Most of the figures that are used in describing the NS basic structure and network components are from the 5th VINT/NS Simulator Tutorial/Workshop slides and the NS Manual (formerly called "NS Notes and Documentation"), modified little bit as needed.

57

Figure 1. Simplified User's View of NS As shown in Figure 1, in a simplified user's view, NS is Object-oriented Tcl (OTcl) script interpreter that has a simulation event scheduler and network component object libraries, and network setup (plumbing) module libraries (actually, plumbing modules are implemented as member functions of the base simulator object). In other words, to use NS, you program in OTcl script language. To setup and run a simulation network, a user should write an OTcl script that initiates an event scheduler, sets up the network topology using the network objects and the plumbing functions in the library, and tells traffic sources when to start and stop transmitting packets through the event scheduler. The term "plumbing" is used for a network setup, because setting up a network is plumbing possible data paths among network objects by setting the "neighbor" pointer of an object to the address of an appropriate object. When a user wants to make a new network object, he or she can easily make an object either by writing a new object or by making a compound object from the object library, and plumb the data path through the object. This may sound like complicated job, but the plumbing OTcl modules actually make the job very easy. The power of NS comes from this plumbing. Another major component of NS beside network objects is the event scheduler. An event in NS is a packet ID that is unique for a packet with scheduled time and the pointer to an object that handles the event. In NS, an event scheduler keeps track of simulation time and fires all the events in the event queue scheduled for the current time by invoking appropriate network components, which usually are the ones who issued the events, and let them do the appropriate action associated with packet pointed by the event. Network components communicate with one another passing packets, however this does not consume actual simulation time. All the network components that need to spend some simulation time handling a packet (i.e. need a delay) use the event scheduler by issuing an event for the packet and waiting for the event to be fired to itself before doing further action handling the packet. For example, a network switch component that simulates a switch with 20 microseconds of switching delay issues an event for a packet to be switched to the scheduler as an event 20 microsecond later. The scheduler after 20 microsecond dequeues the event and fires it to the switch component, which then passes the packet to an appropriate output link component. Another use of an event scheduler is timer. NS is written not only in OTcl but in C++ also. For efficiency reason, NS separates the data path implementation from control path implementations. In order to reduce packet and event processing time (not simulation time), the event scheduler and the basic network component objects in the data path are written and compiled using C++. These compiled objects are made available to the OTcl interpreter through an OTcl linkage that creates a

58

matching OTcl object for each of the C++ objects and makes the control functions and the configurable variables specified by the C++ object act as member functions and member variables of the corresponding OTcl object. In this way, the controls of the C++ objects are given to OTcl. It is also possible to add member functions and variables to a C++ linked OTcl object. The objects in C++ that do not need to be controlled in a simulation or internally used by another object do not need to be linked to OTcl. Likewise, an object (not in the data path) can be entirely implemented in OTcl. Figure 2 shows an object hierarchy example in C++ and OTcl. One thing to note in the figure is that for C++ objects that have an OTcl linkage forming a hierarchy, there is a matching OTcl object hierarchy very similar to that of C++.

Figure 2. C++ and OTcl: The Duality

Figure 3. Architectural View of NS Figure 3 shows the general architecture of NS. In this figure a general user (not an NS developer) can be thought of standing at the left bottom corner, designing and running simulations in Tcl using the simulator objects in the OTcl library. The event schedulers and most of the network components are implemented in C++ and available to OTcl through an OTcl linkage that is implemented using tclcl. The whole thing together makes NS, which is a OO extended Tcl interpreter with network simulator libraries. This section briefly examined the general structure and architecture of NS. At this point, one might be wondering about how to obtain NS simulation results. As shown in Figure 1, when a simulation is finished, NS produces one or more textbased output files that contain detailed simulation data, if specified to do so in the input Tcl (or more specifically, OTcl) script. The data can be used for simulation analysis (two simulation result analysis examples are presented in later sections) or as an input to a graphical simulation display tool called Network Animator (NAM) that is developed as a part

59

of VINT project. NAM has a nice graphical user interface similar to that of a CD player (play, fast forward, rewind, pause and so on), and also has a display speed controller. Furthermore, it can graphically present information such as throughput and number of packet drops at each link, although the graphical information cannot be used for accurate simulation analysis. This section shows a simple NS simulation script and explains what each line does. Example 3 is an OTcl script that creates the simple network configuration and runs the simulation scenario in Figure 4.

Figure 4. A Simple Network Topology and Simulation Scenario This network consists of 4 nodes (n0, n1, n2, n3) as shown in above figure. The duplex links between n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10 ms of delay. The duplex link between n2 and n3 has 1.7 Mbps of bandwidth and 20 ms of delay. Each node uses a DropTail queue, of which the maximum size is 10. A "tcp" agent is attached to n0, and a connection is established to a tcp "sink" agent attached to n3. As default, the maximum size of a packet that a "tcp" agent can generate is 1KByte. A tcp "sink" agent generates and sends ACK packets to the sender (tcp agent) and frees the received packets. A "udp" agent that is attached to n1 is connected to a "null" agent attached to n3. A "null" agent just frees the packets received. Example 3. A Simple NS Simulation Script The following is the explanation of the script above. In general, an NS script starts with making a Simulator object instance.

60

set ns [new Simulator]: generates an NS simulator object instance, and assigns it to variable ns (italics is used for variables and values in this section). Initialize the packet format (ignore this for now) Create a scheduler (default is calendar scheduler) Select the default address format (ignore this for now) The "Simulator" object has member functions that do the following: Create compound objects such as nodes and links (described later) Connect network component objects created (ex. attach-agent) Set network component parameters (mostly for compound objects) Create connections between agents (ex. make connection between a "tcp" and "sink") Specify NAM display options Most of member functions are for simulation setup and scheduling, however some of them are for the NAM display. The "Simulator" object member function implementations are located in the "ns-2/tcl/lib/ns-lib.tcl" file.

$ns color fid color: is to set color of the packets for a flow specified by the flow id (fid). This member function of "Simulator" object is for the NAM display, and has no effect on the actual simulation. $ns namtrace-all file-descriptor: This member function tells the simulator to record simulation traces in NAM input format. It also gives the file name that the trace will be written to later by the command $ns flush-trace. Similarly, the member function trace-all is for recording the simulation trace in a general format. proc finish {}: is called after this simulation is over by the command $ns at 5.0 "finish". In this function, post-simulation processes are specified. set n0 [$ns node]: The member function node creates a node. A node in NS is compound object made of address and port classifiers (described in a later section). Users can create a node by separately creating an address and a port classifier objects and connecting them together. However, this member function of Simulator object makes the job easier. To see how a node is created, look at the files: "ns-2/tcl/libs/nslib.tcl" and "ns-2/tcl/libs/ns-node.tcl". $ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex links of specified bandwidth and delay, and connects the two specified nodes. In NS, the output queue of a node is implemented as a part of a link, therefore users should specify the queue-type when creating links. In the above simulation script, DropTail queue is used. If the reader wants to use a RED queue, simply replace the word DropTail with RED. The NS implementation of a link is shown in a later section. Like a node, a link is a compound object, and users can create its sub-objects and connect them and the nodes. Link source codes can be found in "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl" files. One thing to note is that you can insert error modules in a link component to simulate a lossy link (actually users can make and insert any

61

network objects). Refer to the NS documentation to find out how to do this.

$ns queue-limit node1 node2 number: This line sets the queue limit of the two simplex links that connect node1 and node2 to the number specified. At this point, the authors do not know how many of these kinds of member functions of Simulator objects are available and what they are. Please take a look at "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl", or NS documentation for more information. $ns duplex-link-op node1 node2 ...: The next couple of lines are used for the NAM display. To see the effects of these lines, users can comment these lines out and try the simulation.

Now that the basic network setup is done, the next thing to do is to setup traffic agents such as TCP and UDP, traffic sources such as FTP and CBR, and attach them to nodes and agents respectively.

set tcp [new Agent/TCP]: This line shows how to create a TCP agent. But in general, users can create any agent or traffic sources in this way. Agents and traffic sources are in fact basic objects (not compound objects), mostly implemented in C++ and linked to OTcl. Therefore, there are no specific Simulator object member functions that create these object instances. To create agents or traffic sources, a user should know the class names these objects (Agent/TCP, Agnet/TCPSink, Application/FTP and so on). This information can be found in the NS documentation or partly in this documentation. But one shortcut is to look at the "ns-2/tcl/libs/ns-default.tcl" file. This file contains the default configurable parameter value settings for available network objects. Therefore, it works as a good indicator of what kind of network objects are available in NS and what are the configurable parameters. $ns attach-agent node agent: The attach-agent member function attaches an agent object created to a node object. Actually, what this function does is call the attach member function of specified node, which attaches the given agent to itself. Therefore, a user can do the same thing by, for example, $n0 attach $tcp. $ns connect agent1 agent2: After two agents that will communicate with each other are created, the next thing is to establish a logical network connection between them. This line establishes a network connection by setting the destination address to each others' network and port address pair.

Assuming that all the network configuration is done, the next thing to do is write a simulation scenario (i.e. simulation scheduling). The Simulator object has many scheduling member functions. However, the one that is mostly used is the following:

$ns at time "string": This member function of a Simulator object makes the scheduler (scheduler_ is the variable that points the scheduler object created by [new Scheduler] command at the beginning of the script) to schedule the execution of the specified string at given simulation time. For example, $ns at 0.1 "$cbr start" will make the scheduler call a start member function of the CBR traffic source object, which starts the CBR to transmit data. In NS, usually a traffic source does not transmit actual data, but it notifies the underlying agent that it has some amount of data to transmit, and the agent, just knowing how much of the data to transfer, creates packets and sends them.

62

After all network configuration, scheduling and post-simulation procedure specifications are done, the only thing left is to run the simulation. This is done by $ns run. NETWORK COMPONENTS

Figure 6. Class Hierarchy (Partial) The root of the hierarchy is the TclObject class that is the superclass of all OTcl library objects (scheduler, network components, timers and the other objects including NAM related ones). As an ancestor class of TclObject, NsObject class is the superclass of all basic network component objects that handle packets, which may compose compound network objects such as nodes and links. The basic network components are further divided into two subclasses, Connector and Classifier, based on the number of the possible output data paths. The basic network objects that have only one output data path are under the Connector class, and switching objects that have possible multiple output data paths are under the Classifier class. NODE AND ROUTING A node is a compound object composed of a node entry object and classifiers as shown in Figure 7. There are two types of nodes in NS. A unicast node has an address classifier that does unicast routing and a port classifier. A multicast node, in addition, has a classifier that classify multicast packets from unicast packets and a multicast classifier that performs multicast routing.

63

Figure 7. Node (Unicast and Multicast) In NS, Unicast nodes are the default nodes. To create Multicast nodes the user must explicitly notify in the input OTcl script, right after creating a scheduler object, that all the nodes that will be created are multicast nodes. After specifying the node type, the user can also select a specific routing protocol other than using a default one.

Unicast - $ns rtproto type - type: Static, Session, DV, cost, multi-path Multicast - $ns multicast (right after set $ns [new Scheduler]) - $ns mrtproto type - type: CtrMcast, DM, ST, BST

LINK A link is another major compound object in NS. When a user creates a link using a duplex-link member function of a Simulator object, two simplex links in both directions are created as shown in Figure 8.

Figure 8. Link

64

One thing to note is that an output queue of a node is actually implemented as a part of simplex link object. Packets dequeued from a queue are passed to the Delay object that simulates the link delay, and packets dropped at a queue are sent to a Null Agent and are freed there. Finally, the TTL object calculates Time To Live parameters for each packet received and updates the TTL field of the packet.

Tracing In NS, network activities are traced around simplex links. If the simulator is directed to trace network activities (specified using $ns trace-all file or $ns namtrace-all file), the links created after the command will have the following trace objects inserted as shown in Figure 9. Users can also specifically create a trace object of type type between the given src and dst nodes using the create-trace {type file src dst} command.

Figure 9. Inserting Trace Objects When each inserted trace object (i.e. EnqT, DeqT, DrpT and RecvT) receives a packet, it writes to the specified trace file without consuming any simulation time, and passes the packet to the next network object. The trace format will be examined in the General Analysis Example section.

Queue Monitor Basically, tracing objects are designed to record packet arrival time at which they are located. Although a user gets enough information from the trace, he or she might be interested in what is going on inside a specific output queue. For example, a user interested in RED queue behavior may want to measure the dynamics of average queue size and current queue size of a specific RED queue (i.e. need for queue monitoring). Queue monitoring can be achieved using queue monitor objects and snoop queue objects as shown in Figure 10.

Figure 10. Monitoring Queue When a packet arrives, a snoop queue object notifies the queue monitor object of this event. The queue monitor using this information monitors the queue. A RED queue monitoring example is shown in the RED Queue Monitor Example section. Note that

65

snoop queue objects can be used in parallel with tracing objects even though it is not shown in the above figure. PACKET FLOW EXAMPLE Until now, the two most important network components (node and link) were examined. Figure 11 shows internals of an example simulation network setup and packet flow. The network consist of two nodes (n0 and n1) of which the network addresses are 0 and 1 respectively. A TCP agent attached to n0 using port 0 communicates with a TCP sink object attached to n1 port 0. Finally, an FTP application (or traffic source) is attached to the TCP agent, asking to send some amount of data.

Figure 11. Packet Flow Example Note that the above figure does not show the exact behavior of a FTP over TCP. It only shows the detailed internals of simulation network setup and a packet flow. PACKET A NS packet is composed of a stack of headers, and an optional data space (see Figure 12). As briefly mentioned in the "Simple Simulation Example" section, a packet header format is initialized when a Simulator object is created, where a stack of all registered (or possibly useable) headers, such as the common header that is commonly used by any objects as needed, IP header, TCP header, RTP header (UDP uses RTP header) and trace header, is defined, and the offset of each header in the stack is recorded. What this means is that whether or not a specific header is used, a stack composed of all registered headers is created when a packet is allocated by an agent, and a network object can access any header in the stack of a packet it processes using the corresponding offset value.

66

Figure 12. NS Packet Format Usually, a packet only has the header stack (and a data space pointer that is null). Although a packet can carry actual data (from an application) by allocating a data space, very few application and agent implementations support this. This is because it is meaningless to carry data around in a non-real-time simulation. However, if you want to implement an application that talks to another application cross the network, you might want to use this feature with a little modification in the underlying agent implementation. Another possible approach would be creating a new header for the application and modifying the underlying agent to write data received from the application to the new header. The second approach is shown as an example in a later section called "Add New Application and Agent".

67

RESULT:

Thus the details about NS2(Network Simulator 2) have been studied.

You might also like