EX NO : DATE

:

SOCKET PROGRAMMING – TCP SOCKETS

AIM:
To write a C program for implementing Client-Server Chat using TCP.

ALGORITHM: SERVER:
Step 1: Start the program. Step 2: Create an unnamed socket for the server using the parameters AF_INET as domain and the SOCK_STREAM as Step 3: Name the socket using bind( ) system call with the parameters server_sockfd and the server address(sin_addr and sin_sport). Step 4: Create a connection queue and wait for clients using the listen( ) system call with the number of clients request as parameters. Step 5: Accept the connection using accept( ) system call when client requests for connection. Step 6: Get the message which has to be sent to the client and check that it is not equal to ‘Bye’. Step 7: If the message is not equal to ‘Bye’ then write the message to the client and Goto step 6. Step 8: If the message is ‘Bye’ then terminate the Process. Step 9: Stop the program execution. type.

1

CLIENT
Step 1: Start the program. Step 2: Create an unnamed socket for client using socket( ) system. Step 3: Call with parameters AF_INET as domain and SOCK_STREAM as type. Step 4: Name the socket using bind( ) system call. Step 5: Now connect the socket to server using connect( ) system call. Step 6: Read the message from the server socket and compare it with ‘Bye’. Step 7: If the message is not equal to ‘Bye’ then print the message to the server output device and repeat the steps 6 & 7. Step 8: Get the message from the client side. Step 9: Write the message to server sockfd and goto step 4. Step 10:If the message is equal to ‘Bye’then print good bye message and terminate the process. Step 11:Stop the process.

PROGRAM:
2

SERVER
#include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> main() { int sd,sd2,nsd,clilen,sport,len; char sendmsg[20],rcvmsg[20]; struct sockaddr_in servaddr,cliaddr; printf("Enter the Server port"); printf("\n_____________________\n"); scanf("%d",&sport); sd=socket(AF_INET,SOCK_STREAM,0); if(sd<0) printf("Can't Create \n"); else printf("Socket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(sport); sd2=bind(sd,(struct sockaddr*)&servaddr,sizeof(servaddr)); if(sd2<0) printf(" Can't Bind\n"); else

3

printf("%s". clilen=sizeof(cliaddr). send(nsd. else printf("Accepted\n"). len=strlen(sendmsg). nsd=accept(sd. if(nsd<0) printf("Can't Accept\n"). sendmsg[len-1]='\0'.20.0). } while(strcmp(sendmsg.20. } CLIENT 4 .rcvmsg.0). listen(sd.rcvmsg). printf("\nReceived Messages\n").20.printf("\n Binded\n").sendmsg. do { recv(nsd. fgets(sendmsg."bye")!=0).stdin). wait(20).&clilen).(struct sockaddr*)&cliaddr.5).

sizeof(servaddr))<0) printf("Can't Connect\n").&cport). struct sockaddr_in servaddr. do { fgets(sendmsg.h> #include<sys/types. servaddr. else printf("Connected\n"). else printf("Scocket is Created\n"). 5 .cport.stdin). servaddr.#include<stdio.0).(struct sockaddr*)&servaddr.sin_family=AF_INET. if(connect(csd. printf("Enter the port\n").20.s_addr=htonl(INADDR_ANY). char sendmsg[20].SOCK_STREAM. if(csd<0) printf("Can't Create\n"). csd=socket(AF_INET.sin_port=htons(cport).h> main() { int csd.sin_addr.h> #include<netinet/in.revmsg[20]. scanf("%d".len. servaddr.

0).20. } 6 .revmsg). recv(csd.20. } while(strcmp(revmsg.sendmsg.len=strlen(sendmsg). wait(20). send(csd. printf("%s". sendmsg[len-1]='\0'."bye")!=0).0).revmsg.

.../tcps Enter the Server port _____________________ 6523 Socket is Created Binded Accepted Received Messages Hi.. Hellooooooooooooo bye [mecse8@localhost mecse8]$ Client Side: [mecse8@localhost mecse8]$ .OUTPUT: Server Side: [mecse8@localhost mecse8]$ .... Hellooooooooooooo bye bye[mecse8@localhost mecse8]$ 7 ......../tcpc Enter the port 6523 Scocket is Created Connected Hi...

8 .RESULT: Thus the C program for chat using TCP is executed and the output is verified successfully.

Step 6:Stop the program execution. Step 4:The server gets the message from the client. PROGRAM: 9 . Step 2:Create an unnamed socket for the server using the parameters AF_INET as domain and the SOCK_DGRAM as type. CLIENT: Step 1: Start the program. Step 5:Prints the message. Step 5: The Sendto( ) system call is used to deliver the Message to the server. ALGORITHM: SERVER: Step 1: Start the program. Step 4: Name the socket using bind( ) system call. Step 3:Name the socket using bind( ) system call with the parameters server_sockfd and the server address(sin_addr and sin_sport). Step 6: Stop the program execution.EX NO: DATE : AIM: SOCKET PROGRAMMING – UDP SOCKETS To write a C program for implementing chat program using UDP. Step 2: Create an unnamed socket for client using socket Step 3:Call with parameters AF_INET as domain an SOCK_DGRAM as type.

sin_family=PF_INET.h> #include<netinet/in. int id.h> main() { struct sockaddr_in sadd. if(id<0) printf("Can't Create\n"). scanf("%d". else printf("Created\n").h> #include<sys/socket. sadd. id=socket(PF_INET.(struct sockaddr*)&sadd. sadd.SOCK_DGRAM.SERVER #include<stdio. char rbuff[100].sin_port=htons(port). sadd.0). b=bind(id.sin_addr.&port).port. if(b<0) 10 .s_addr=htonl(INADDR_ANY).sizeof(sadd)).cadd.a. printf("Enter the port Address\n").len. printf("____________________\n").h> #include<sys/types.b.

else printf("Server received =%s\n". printf("~~~~~~\n"). } 11 .rbuff). len=sizeof(cadd). close(id).0.rbuff.sizeof(rbuff). else printf("Binded\n").(struct sockaddr*)&cadd.&len)<0) printf("Received Error\n").printf("Can't Bind"). if(recvfrom(id.

scanf("%s". id=socket(PF_INET. int id. scanf("%s".sin_addr.serstr[100].str. printf("Enter the port Address\n").len.sizeof(cadd))<0) printf("Transmit Error").h> main() { struct sockaddr_in sadd. else printf("Socket is Created\n").(struct sockaddr*)&cadd. b=bind(id.str). cadd. printf("Enter the Data\n"). cadd. char str[100].0).(struct sockaddr*)&cadd. scanf("%d". printf("Enter the IP address\n").n.c.sin_family=PF_INET.h> #include<sys/types.serstr). 12 .&port). if(id<0) printf("Can't Create\n").sin_port=htons(port).cadd.sizeof(str).sizeof(cadd)).s.h> #include<netinet/in.CLIENT #include<stdio.s_addr=inet_addr(serstr).SOCK_DGRAM.0.b.port.h> #include<sys/socket. cadd. if(sendto(id.

close(id).else printf("Server Transmitted=%s\n".str). } OUTPUT: Server Side: 13 .

..104 Enter the port Address 6523 Enter the Data Hi... Server Transmitted=Hi..15..[mecse8@localhost mecse8]$ .......170. [mecse8@localhost mecse8]$ RESULT: Thus the C program for chat using UDP is executed and the output is verified successfully... EX NO: SOCKET PROGRAMMING – APPLICATIONS USING SOCKET FTP DATE: 14 .../uc Socket is Created Enter the IP address 172.. [mecse8@localhost mecse8]$ Client Side: [mecse8@localhost mecse8]$ ..../us Created Enter the port Address ____________________ 6523 Binded ~~~~~~ Server received =Hi..

AIM: To implement the FTP program using Java. Data connection is made for each file transfer ie) server waits for client request and then response to the client. • • CLIENT: • FTP client has three component: User Interface. FTP establishes the connection between client and server. • • 15 . client control process. New data connection is made for next file transfer. ALGORITHM: • • File Transfer Protocol (FTP) is a mechanism to copy a file from one host to another. data structure and transmission mode of data to be transmitted. SERVER: • • FTP server has control process and data transfer process. The client defines the file type. client data transfer process. Data connection is closed after a file is transferred. The clients send a request to server to enable connection for data transfer.

out.out.")..PROGRAM: File Server: import java.println("Service Thread Started.println("Requestreceived +"@"+socket. } } public static void main(String[] atgs) { try 16 form"+socket. new fileservant(socket).*. System.net. } void waitForRequests()throws IOException { serversocket=new ServerSocket(port).getInetAddress() . import java. int port.println("Server waiting.io.. fileserver() { this(9999). while(true) { System....out. Socket socket.getPort()).").port=port. } fileserver(int port) { this. System.start().*. public class fileserver { ServerSocket serversocket.accept(). socket=serversocket.

{ new fileserver(). import java. fileservant(Socket socket)throws IOException { this. } public void run() { Try { filename=in.getInputStream())).waitForRequests().readLine().getOutputStream())). in=new BufferedReader(new InputStreamReader(socket.*.printStackTrace().*.net. BufferedReader in.socket=socket. } catch(IOException e) { e. 17 . PrintWriter out. String filename. public class fileservant extends Thread { Socket socket. out=new PrintWriter(new OutputStreamWriter(socket. } } } File Servant: import java.io.

String content=null.println("File sent.").println("Requested File not found...readLine())!=null) { out.out.println("File not found"). while((content=fileReader.. System. } } public static void main(String[] args) { }} 18 .flush().. if(file.out.").println("Connection closed.close().printStackTrace().File file=new File(filename). } else { System. } System.exists()) { BufferedReader fileReader=new BufferedReader(new FileReader(filename)).flush(). out.println(content). } socket.. } catch(FileNotFoundException e) { e. out..").printStackTrace(). } catch(IOException e) { e.out.. out.

} void getResponseFromServer()throws IOException { 19 .. import java.serverAddress=serverAddress.println("Request sent"). int port. getResponseFromServer(). Socket socket.IOException { socket=new Socket(serverAddress. } fileclient(String serverAddress. String serverAddress. System.*. fileclient() { this("localhost"."sample1.").println("Connected to server.int port.getOutputStream())).String filename) { this. socket.. System. writer.println(filename).io. PrintWriterwriter=newPrintWriter(new OutputStreamWriter(socket.close().out.9999. this.txt").File Client: import java.filename=filename.*.port=port.net. this. } void sendRequestForFile()throws UnknownHostException. public class fileclient { String filename. writer.out.flush().port).

if(response. String response=reader.toLowerCase().flush().BufferedReader reader=new BufferedReader(new InputStreamReader(socket.write(response).getInputStream())). fileWriter.readLine())!=null). do { fileWriter.equals("file not found")) { System. fileWriter. }}} 20 . } catch(UnknownHostException e) { e. } } public static void main(String[] args) { Try { new fileclient().out. } catch(IOException e) { e. return. } Else { BufferedWriter fileWriter=new BufferedWriter(new FileWriter("readfile.trim().printStackTrace().printStackTrace().println(response). } while((response=reader.close().sendRequestForFile().txt")).readLine().

Connection closed.OUTPUT: File Server: D:\mecn>java fileserver Server waiting.. File Servant: D:\mecn>java fileservant D:\mecn>copy con readfile. File sent.... EX NO: DEVELOPMENT OF APPLICATIONSDNS-INETADDRESS 21 . Request received form/127...1@1111 Service Thread Started....0..0......txt File Client: D:\mecn>java fileclient Connected to server.txt welcome D:\mecn> RESULT: Thus the java program for FTP is executed and the output is verified successfully. Request sent D:\mecn>type readfile. Server waiting.

SEARCHING DATE: AIM: To implement DNS to search internet address using Java ALGORITHM: • • • • DNS is a internet service that translates domain names into IP addresses The host is identified by its IP addresses. IP address of the Local host. website IP address. Here DNS is used to obtain the IP addresses. the collection of IP addresses for the IP address in network is obtained as a result using getfunction in Java. Host file is used for domain name to IP mapping. • PROGRAM: 22 .

i<website. InetAddress website[]=InetAddress.out. System.println(Address).*.*.i++) System. System. System. for(int i=0.out.net. System.getAllByName(args[0]). System.out.length. import java.out.println(Address).getByName(args[0]).println(website[i]).println("The website ipaddress in Internet:" ).io. Address=InetAddress.import java.println("The local host ipaddress is:").println("The collection of ipaddresses for the ipaddress in internet:").getLocalHost().out.out. class InetAddressSearchin { public static void main(String args[])throws UnknownHostException { InetAddress Address=InetAddress. } } OUTPUT: 23 .

D:\mecn>javac InetAddressSearching.81 The website ipaddress in Internet: home-12175d3f3e/115.30.241.30.241.81 The collection of ipaddresses for the ipaddress in internet: home-12175d3f3e/115.java D:\mecn>java InetAddressSearching in home-12175d3f3e The local host ipaddress is: home-12175d3f3e/115.81 RESULT: Thus the java program for Inet Address Searching is executed and the output is verified successfully.241.30. EX NO: UNIFORM RESOURCE LOCATORS 24 .

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

getContentLength()).getDate())).out.PROGRAM: import java.out.read())!= -1) System.getLastModified())). URLConnection uc=u. } } } 26 .println("Modified Date:"+new Date(uc.getContentEncoding()).out. System.util.*.out.println("Expired Date:"+new Date(uc. System. class UrlDemo { public static void main(String[] arg)throws MalformedURLException.println("Content Length:"+uc.*.out. import java. int c. import java.println("exception caught:"+e).println("Content Type:"+uc.print((char)c).out. } catch(IOException e1) { System.openConnection().println("Date:"+new Date(uc.io. System.html").getExpiration())). InputStream in=uc.out.out.println("exception caught:"+e1).println("Content Encoding:"+uc. System. System.net.out. while(( c=in. } catch(MalformedURLException e) { System.getInputStream(). System.getContentType()).IOException { try { URL u= new URL("file:\\d:\\hai.*.

HTML <html> <head> <title> MY HTML </title> </head> <body> <center>WELCOME</center> </body> </html> 27 .HAI.

OUTPUT: <html> <head> <title> MY HTML </title> </head> <body> <center>WELCOME</center> </body> </html> Content Length:103 Content Type:text/html Content Encoding:null Date:Thu Jan 01 05:30:00 IST 1970 Modified Date: Wed Nov 09 11:10:47 IST 2011 Expired Date: Thu Jan 01 05:30:00 IST 1970 RESULT: Thus the java program using URL is executed and the output is verified successfully EX NO: DOWNLOADING USING APPLET 28 .

29 . ALGORITHM: • • • • • Import the necessary java packages. the contents of the file should be displayed.DATE: AIM: To download a page using Applet in Java. Create a button DOWN. Also generate Content-Type and Content-Length of the file. On clicking the DOWN button. A HTML file is created and its file name is declared in program using URL.

} public void actionPerformed(ActionEvent er) { try { URL u=new URL("file:\\c:\\HAI. String headervalue=uc. JTextArea header=new JTextArea(5.NORTH).*..awt.setVisible(true).openConnection().SOUTH).add(pane. header. 30 .setPage(u).event. for(int i=0.swing.*. import javax.35). JTextField status=new JTextField(35). if(headername==null&&headervalue==null) break.BorderLayout. fa.add(pane.event. import java. jspViewer.createVerticalBox().addActionListener(this).io.getInputStream().add(header).setText(header.swing.add(status).getHeaderFieldKey(i). fa. JButton goButton=new JButton("DOWN"). fa.net. URLConnection uc=u.null). JEditorPane pane=new JEditorPane().i++) { String headername=uc. JFrame fa=new JFrame().getContentPane(). } pane. goButton. setDefaultCloseOperation(EXIT_ON_CLOSE). public Download() { vb.PROGRAM: import java.700). class Download extends JFrame implements ActionListener { JScrollPane jspViewer=new JScrollPane(). import javax.HTML").getText()+headername+":"+headervalue+"\n"). import java.getViewport(). fa.*.net.getHeaderField(i). InputStream in=uc. Box vb=Box.*.add(jspViewer). fa.*.getContentPane().URL.setSize(700.getContentPane(). import java.awt. vb.add(goButton).BorderLayout.add(vb.*. vb. import java.

} } public static void main(String str[])throws Exception { Download g=new Download().} catch(Exception e) { System.out.println(e). } } 31 .

HAI.HTML <html> <head> <title> MY HTML </title> </head> <body> <center>WELCOME</center> </body> </html> 32 .

OUTPUT: RESULT: Thus the Java program to download a file using Applet is executed and output is successfully verified. 33 .

URL file is used to include the HTML document in HTTP. The data and size of the web page is displayed as a result using Java functions in HTTP.EX NO: DATE : HTTP AIM: To implement the HTTP program using java ALGORITHM: • Hyper Text Transfer Protocol (HTTP) is a protocol used access data on the world wide web Data is created in worldwide web using HTML document. • • • PROGRAM: 34 .

URL.net.println(builder. System. } catch (IOException ex) { ex.close(). int byteRead.append((char) byteRead).printStackTrace(). System. } catch (MalformedURLException ex) { ex.read()) != -1) builder. StringBuffer builder = new StringBuffer().URLConnection. public class HTTP2 { public void getWebSite() { try { URL url = new URL("file:\\D:\\hai.out. BufferedInputStream buffer = new BufferedInputStream(urlc.length() + " bytes.net. import java.toString()). buffer.lang.StringBuffer.openConnection(). } } OUTPUT: <html> 35 .getInputStream()).out.printStackTrace(). import java.println("The size of the web page is " + builder. while ((byteRead = buffer. URLConnection urlc = url.import java.").html").

<head> <title> MY HTML </title> </head> <body> <center>WELCOME</center> </body> </html> The size of the web page is 103 bytes RESULT: Thus the Java program using HTTP is executed and output is verified successfully. EX NO: DATE: E-MAIL 36 .

Step 3: The file size is compared with the mailid’s size. ALGORITHM: Step 1: Start the Program Step 2: Get the input from the user for the file to mail to the list of mail id’s.AIM: To email the contents of a file usin C program. If the file size is greater than mailid’s size then display the error. Step 5: The user can open the Inbox to see the incoming messages by specifying ‘mail userid’ Step 6: Stop the program 37 . Step 4: The contents of a file are transferred using mail statement followed by the Subject. otherwise go to step 4.

char fpBuffer[400]={0x0}."Please Review:". email_list[i])). if(system (fpBuffer)==(-1)) { perror("email failure"). void email_it(char *filename).fname).h> #define cknull(x) if((x)==NULL) {perror(""). scanf("%s". exit(EXIT_FAILURE).i++) { cknull(strcpy(tmp. } } } 38 .} #define cknltz(x) if((x)<0) {perror(""). cknltz(sprintf (fpBuffer. for(i=0.} #define LIST_LEN 4 //char *f="sam.*email_list[i]>0x0.h> #include <string. exit(EXIT_FAILURE). exit(EXIT_FAILURE). main() { char fname[15].{0x0}}. tmp.txt". int i=0. char email_list[LIST_LEN][256]={{"mecse3@localhost. } void email_it(char *filename) { char tmp[256]={0x0}. email_it(fname).localdomain"}. printf("enter the filename\n")."mail -s '%s %s' %s < %s".PROGRAM: #include <stdlib.filename)). filename.

OUTPUT:
[1me2@localhost ~]$ vi email.c [1me2@localhost ~]$ cc email.c [1me2@localhost ~]$ ./a.out

Enter the file name: sample.c [1me2@localhost~]$/home/1me1/dead.letter….savedmessagein /home/1me1/dead.letter…..

RESULT
Thus the program for developing E-mail application is executed and the output is verified successfully

EX NO:

MULTIUSER CHAT
39

DATE: AIM:
To write a C program for implementing Client-Server Chat using TCP.

ALGORITHM: SERVER:
Step 1: Start the program. Step 2: Create an unnamed socket for the server using the parameters AF_INET as domain and the SOCK_STREAM as type. Step 3: Name the socket using bind ( ) system call with the parameters server_sockfd and the server address (sin_addr and sin_sport). Step 4: Create a connection queue and wait for clients using the listen( ) system call with the number of clients request as parameters. Step 5: Get the client’s id as input from the user to communicate. If the client’s id is 0 then go to step 10 otherwise go to step 6. Step 6: Accept the connection using accept ( ) system call when client requests for connection. Step 7: Get the message which has to be sent to the client and check that it is not equal to ‘Bye’. Step 8: If the message is not equal to ‘Bye’ then write the message to the client and Goto step 6. Step 9: If the message is ‘Bye’ then terminates the connection with current client and Go to step 5. Step 10: Stop the program execution.

40

CLIENT:
Step 1: Start the program. Step 2: Create an unnamed socket for client using socket ( ) system. Step 3: Call with parameters AF_INET as domain and SOCK_STREAM as type. Step 4: Name the socket using bind( ) system call. Step 5: Now connect the socket to server using connect ( ) system call. Step 6: Read the message from the server socket and compare it with ‘Bye’. Step 7: If the message is not equal to ‘Bye’ then print the message to the server output device and repeat the steps 6 & 7. Step 8: Get the message from the client side. Step 9: Write the message to server sockfd and goto step 4. Step 10: If the message is equal to ‘Bye’then print good bye message and terminate the process. Step 11: Stop the process.

41

cliaddr. printf("Client %d is connected\n". scanf("%d". else printf("Accepted\n").&sport).sport.rcvmsg[20]. servaddr.h> main() { int i. if(i==0) exit(0). do { printf("Enter the client no to communicate\n").h> #include<sys/types.sd.SOCK_STREAM.len. char sendmsg[20]. nsd=accept(sd.sin_port=htons(sport).i).0).nsd.h> #include<netinet/in. else printf("\n Binded\n"). sd=socket(AF_INET.(struct sockaddr*)&cliaddr. do { 42 .sin_family=AF_INET. servaddr. if(sd<0) printf("Can't Create \n").(struct sockaddr*)&servaddr.&i).5). if(nsd<0) printf("Can't Accept\n"). sd2=bind(sd.&clilen).s_addr=htonl(INADDR_ANY). listen(sd.h> #include<string. struct sockaddr_in servaddr.sin_addr.PROGRAM: SERVER #include<stdio. clilen=sizeof(cliaddr). scanf("%d". if(sd2<0) printf("Can't Bind\n").sizeof(servaddr)). servaddr.sd2. else printf("Socket is Created\n").clilen.

sendmsg[len-1]='\0'. } while(strcmp(sendmsg. len=strlen(sendmsg).recv(nsd. fgets(sendmsg.rcvmsg.20. wait(20). printf("%s".0). send(nsd.rcvmsg). } while(i!=0).sendmsg."bye")!=0).20. } 43 .0).20.stdin).

sin_port=htons(cport). else printf("Connected\n"). recv(csd. struct sockaddr_in servaddr.cport. send(csd. servaddr. } while(strcmp(revmsg.stdin).h> main() { int csd. printf("%s". wait(20). char sendmsg[20]. csd=socket(AF_INET.SOCK_STREAM.20.sizeof(servaddr))<0) printf("Can't Connect\n"). printf("Enter the port\n"). else printf("Socket is Created\n"). sendmsg[len-1]='\0'. if(connect(csd.revmsg. do { fgets(sendmsg.len."bye")!=0).(struct sockaddr*)&servaddr. } 44 .h> #include<netinet/in.20.h> #include<sys/types. servaddr.s_addr=htonl(INADDR_ANY).sin_addr. if(csd<0) printf("Can't Create\n").sendmsg.0).0).CLIENT .&cport). len=strlen(sendmsg). servaddr. scanf("%d".0).revmsg).sin_family=AF_INET.1 #include<stdio.20.revmsg[20].

cport. } while(strcmp(revmsg.revmsg).0). char sendmsg[20].sin_port=htons(cport).(struct sockaddr*)&servaddr.sendmsg.stdin).revmsg[20].0). if(csd<0) printf("Can't Create\n").len. else printf("Connected\n").sin_addr."bye")!=0).20. len=strlen(sendmsg). servaddr.0). } OUTPUT: 45 . printf("%s". recv(csd.CLIENT – 2 #include<stdio. sendmsg[len-1]='\0'. servaddr.h> #include<sys/types. scanf("%d".20. servaddr. send(csd. if(connect(csd.20. struct sockaddr_in servaddr.revmsg. csd=socket(AF_INET. do { fgets(sendmsg. printf("Enter the port\n").h> main() { int csd.h> #include<netinet/in.&cport).sizeof(servaddr))<0) printf("Can't Connect\n").sin_family=AF_INET.s_addr=htonl(INADDR_ANY). wait(20). else printf("Socket is Created\n").SOCK_STREAM.

/m1 6523 Socket is Created Binded Enter the client no to communicate 1 Client 1 is connected Accepted bye bye bye Enter the client no to communicate 2 Client 2 is connected Accepted bye bye Enter the client no to communicate 3 Client 3 is connected Accepted bye bye bye Enter the client no to communicate 0 46 .Server Side: [mecse8@localhost mecse8]$ .

/c1 Enter the port 6523 Socket is Created Connected bye bye bye[mecse8@localhost mecse8]$ Client Side – 2 [mecse8@localhost mecse8]$ ./c2 Enter the port 6523 Socket is Created Connected bye bye[mecse8@localhost mecse8]$ RESULT: Thus the C program for chat multiclient-serve chat program using tcp has been executed successfully. 47 .1 [mecse8@localhost mecse8]$ .Client Side .

EX NO: DATE: SIMULATION OF SLIDING WINDOW PROTOCOL AIM: To write a C program for the simulation of Sliding Window Protocol. then send the acknowledgement of the last frame. Step 2: Create the Socket for the Receiver. send the acknowledgement for the last frame to the sender. ALGORITHM: SENDER: Step 1: Start the program. which was successfully received. RECEIVER: Step 1: Start the program. Step 4: If any of the frames is lost. 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. Step 5: Keep on receiving and acknowledging the frames until the sender sends. 48 . Step 3: If all the frames are successfully received. bind it and listen for the frames from the sender. Step 6: Stop the program execution. Step 2: Create a Socket for the Sender and bind it with the receiver. Step 3: Set the size of the window.

cliaddr.sd. servaddr. sd=socket(AF_INET.port.PROGRAM: SERVER: #include<stdio. servaddr.h> main() { int a.&port).0).s_addr=htonl(INADDR_ANY). struct sockaddr_in servaddr. 49 .h> #include<string.newsd.h> #include<sys/socket.bd.h> #include<netinet/in.h> #include<sys/types. char lost[20]. printf("Enter the port no\n"). a=sizeof(servaddr). if(bd<0) printf(" Can't Bind\n").recvmsg[20].sin_addr. else printf("Socket is Created\n"). if(sd<0) printf("Can't Create \n"). bd=bind(sd.(struct sockaddr*)&servaddr.a).sin_port=htons(port).sendmsg[20]. servaddr. scanf("%d".SOCK_STREAM.sin_family=AF_INET.clilen.

5). } 50 .20. printf("Enter the lost frame\n").0). else printf("Accepted\n").20. scanf("%s".lost.lost). printf("\n Frame %s is successfully received". if(newsd<0) printf("Can't Accept\n").recvmsg). send(newsd.(struct sockaddr*)&cliaddr.recvmsg.&clilen). listen(sd. clilen=sizeof(cliaddr). newsd=accept(sd.else printf("\n Binded\n"). recv(newsd.0).

&n). scanf("%d".0).h> #include<netinet/in. printf("\nThe frames all\n"). if(sd<0) printf("Can't Create\n").sin_family=AF_INET. printf("Enter the no of frames\n"). servaddr.SOCK_STREAM. scanf("%d".s_addr=htonl(INADDR_ANY).port.n.(struct sockaddr*)&servaddr. 51 . servaddr.recvmsg[100]. printf("Enter the port\n").CLIENT #include<stdio. if(connect(sd. struct sockaddr_in servaddr. char sendmsg[100].h> main() { int i.sizeof(servaddr))<0) printf("Can't Connect\n").sin_addr. sd=socket(AF_INET.sd. else printf("Connected\n").&port). else printf("Socket is Created\n").h> #include<sys/types.h> #include<string. servaddr.sin_port=htons(port).

strcpy(sendmsg. send(sd.sendmsg. recv(sd.i).recvmsg.for(i=1. } 52 . printf("\n Lost frame %s is retransmitted ".recvmsg).20.0).i++) printf("Frame %d\n".i<=n.recvmsg).20.0).

c [1me16alhost~]: /a.c [1me16alhost~]: CC swclient. Enter the no of frames: 4 The frames all Frame 1/n Frame 2/n Frame 3/n Frame 4/n 53 .out Enter the port address 8543 Socket is created Binded Accepted Enter the lost frame: 3 Frame tcpserver.c [1me16alhost~]: CC swserver.out Enter the client port no 8543 Socket is created Connected…………..c is successfully transmitted CLIENT: [1me16alhost~]: VI swclient.OUTPUT: SERVER: [1me16alhost~]: VI swserver.c [1me16alhost~]: /a.

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

Step 6: Current node is set as the starting vertex. Step 8: Update distance and previous lists based on those vertices which can be immediately reached from the current vertex. a previous vertex list. Step 4: All values in visited list are set to false. Step 5: All values in the previous list are set to a special value signifying that they are undefined. Step 9: Update the current vertex to the unvisited vertex that can be reached by the shortest path from the starting vertex. 55 . Step 10: Repeat (from step 6) until all nodes are visited. and a current vertex. Step 11: Stop the program execution. Step 3: All the values in the distance list are set to infinity except the starting vertex which is set to zero. ALGORITHM Step 1: Start the Program Step 2: Create a distance list. Step 7: Mark the current vertex as visited.EX NO: DATE: AIM SIMULATION OF ROUTING PROTOCOLS To Simulate Shortest Path Routing Algorithm using C. a visited list.

int).co. do { display_given().PROGRAM: #include<stdio. int weight[10][10].&n2). 56 .h> #include<string. get_node(). void get_node(). shortpath(n1.&n1. get_wt().n2.k. main() { int n1.e. int node[10].cost[10][10].m.h> int i.j. char ch[2]. void display_given(). void shortpath(int. scanf("%d %d". void get_wt().c. void display_result(). long int sp. long int path[10][10]. char name[10]. printf("\n Enter the nodes to find the shortest path:").n2).len[10].

i<=m. path[i][j]=0. node[i]=i. } for(i=1."y")).i++) { for(j=1.printf("\n\n Do you want to continue. } } } 57 ..&ch). scanf("%d". } void get_node() { printf("\n Enter the no of nodes in the graph:"). press Y:"). cost[i][j]=0.i++) { printf("\n Enter the name of the node %d:".j++) { weight[i][j]=0. } while(!strcmp(ch. for(i=1. scanf("%s"..i)..&m).&name[i]). scanf("%d".i<=m.j<=m.

&node1.&w). int w. } } } for(i=1.j++) { if(node[i]==node1&&node[j]==node2) weight[i][j]=w. printf("\n Enter the no of edges:").j<=m. scanf("%d".k<=e.i++) { for(j=1.void get_wt() { int node1.&e).&node2.dnode and wt of the edge %d:".j<=m.i++) { for(j=1.node2.k). for(k=1. scanf("%d %d %d". for(i=1.i<=m.j++) { if(weight[i][j]!=0) { 58 .k++) { printf("\n Enter the snode.i<=m.

} else cost[i][j]=236.j++) printf("\t%d".weight[i][j]).i<=m.name[i]).i<=m. printf("\n").i<=m.i++) printf("\t%d".cost[i][j]=weight[i][j].name[i]).i++) printf("\t%c". for(i=1. for(i=1. for(i=1. 59 . path[i][j]=(i*10)+j.i++) { printf("\t%d".j<=m. printf("\n"). printf("\n"). } printf("\n Matrix representation of cost graph:\n\t"). } } } void display_given() { printf("\n Matrix representation of the given graph:\n\t"). for(j=1.name[i]).

i++) { printf("\t%d". for(i=1. for(j=1. printf("\n"). for(i=1.int node2) 60 . else printf("\t%c".j<=m.i<=m.i++) { printf("\t%d".path[i][j]).i<=m. for(j=1.j++) printf("\t%ld".name[i]).j++) { if(cost[i][j]<236) printf("\t%d".name[i]). } } void shortpath(int node1.i++) printf("\t%d".236).for(i=1. printf("\n").cost[i][j]). } printf("\n Matrix representation of path graph:\n\t").j<=m.name[i]).i<=m. } printf("\n").

j++) { if(cost[i][j]<cost[i][k]+cost[k][j]) cost[i][j]=cost[i][j].k++) { for(i=1.{ for(k=1.i++) { for(j=1.k<=m. else { cost[i][j]=cost[i][k]+cost[k][j].j<=m.i<=m. } } } } for(i=1. } 61 . path[i][j]=(path[i][k]*10)+j.i++) { for(j=1. sp=path[i][j].j<=m.j++) { if(node1==node[i]&&node2==node[j]) { co=cost[i][j].i<=m.

printf("\n The weight of the path is:%d". } printf("%d".i=1. sp=sp/10.name[len[1]]).i>1.i++) 62 .} } display_result(). } for(i=c. while(sp>0) { len[i]=sp%10. } void display_result() { printf("\n Matrix representation of result cost graph:\n\t"). c=c+1.name[len[i]]).i--) { printf("\t%d".i<=m. printf("\n The shortest path for given nodes:\n"). c=0. printf("---->"). for(i=1.co). i=i+1.

j++)\ { if(cost[i][j]<236) printf("\t%d".name[i]).i<=m.path[i][j]).j++) printf("\t%ld". for(j=1.i<=m.j<=m.cost[i][j]). for(i=1. printf("\n"). else printf("\t%c". for(i=1.name[i]). } printf("\n Matrix representation of result path graph:\n\t").name[i]).printf("\t%d". printf("\n").i<=m. for(i=1.236).i++) { printf("\t%d". } printf("\n").i++) printf("\t%d".i++) { printf("\t%d". printf("\n"). for(j=1. } } 63 .name[i]).j<=m.

OUTPUT: [mtech@Server nanthu]$ cc simulospf.dnode and wt of the edge 1:1 2 1 Enter the snode.out Enter the no of nodes in the graph:4 Enter the name of the node 1:1 Enter the name of the node 2:2 Enter the name of the node 3:3 Enter the name of the node 4:4 Enter the no of edges:5 Enter the snode./a.c [mtech@Server nanthu]$ .dnode and wt of the edge 4:3 1 4 Enter the snode.dnode and wt of the edge 2:2 4 Enter the snode.dnode and wt of the edge 5:4 1 5 Matrix representation of the given graph: ☺ 1 2 3 4 0 0 4 5 ☻ 1 0 0 0 0 0 0 3 ♥ 0 2 0 0 ♦ Matrix representation of cost graph: 1 1 2 3 4 ∞ ∞ 4 5 2 1 ∞ ∞ ∞ 3 ∞ ∞ ∞ 3 4 ∞ 2 ∞ ∞ 64 .dnode and wt of the edge 3:4 3 3 Enter the snode.

.. press Y:n 65 ..Matrix representation of path graph: 1 1 2 3 4 0 0 31 41 2 12 0 0 0 3 0 0 0 43 4 0 24 0 0 Enter the nodes to find the shortest path:1 3 Matrix representation of result cost graph: 1 1 2 3 4 8 7 4 5 2 1 8 5 6 3 6 5 10 3 4 3 2 7 8 Matrix representation of result path graph: 1 1 2 3 4 1241 241 31 41 2 12 242 312 412 3 4 1243 243 124 24 31243 3124 43 4124 The shortest path for given nodes: 1----> 2----> 4---->3 The weight of the path is:6 Do you want to continue.

66 .RESULT: Thus the C program for simulating Shortest Path Routing Algorithm is executed and the output is verified.

Step 9: Read the input for the object. print and terminate the process. Step 4: Name the socket using bind ( ) system call. Step 8: Read the input for the object. 67 . Go to step 10. send it and receive the details of the system from the agent. Step 7: If the input is equal to ‘TCP connection’ then goto next step else If it is equal to ‘system’ Goto step 9. Step 3: Call with parameters AF_INET as domain and SOCK_STREAM as type.EX NO: DATE : AIM: SIMULATION OF NETWORK MANAGEMENT PROTOCOL To write a C program for simulation of Simple Network management Protocols. Step 5: Now connect the socket to agent using connect ( ) system call. send it and receive the details of the TCP connection of that object from the agent. Step 2: Create an unnamed socket for client using socket ( ) system. Step 6: Get the input for the type of information needed from the agent. Step 10: Receive the message. ALGORITHM: MANAGER: Step 1: Start the program. Go to step 10. Step 11: Stop the process.

Step 2: Create an unnamed socket for the server using the parameters AF_INET as domain and the SOCK_STREAM as type. Step 7: Stop the program execution. Step 5: Accept the connection using accept( ) system call when manager requests for connection. 68 . Step 6: Receive the message from the manager. else if the request is for ‘System’ then send the details of the requested system. If the request is for ‘TCP connections’ then send the details of the requested object.AGENTS Step 1: Start the program. Step 3: Name the socket using bind( ) system call with the parameters server_sockfd and the manager address(sin_addr and sin_sport). Step 4: Create a connection queue and wait for manager using the listen ( ) system call with the number of manager request as parameters.

&cport). scanf("%d".(struct sockaddr*)&servaddr.oid[100].sizeof(servaddr))<0) printf("Can't Connect\n"). servaddr.h> #include<netinet/in.SOCK_STREAM. char sendmsg[20].s_addr=htonl(INADDR_ANY).sin_port=htons(cport). if(connect(csd. if(csd<0) printf("Can't Create\n").cport.rcvmsg[100]. printf("Enter the port\n").len. 69 . servaddr. csd=socket(AF_INET.rmsg[100].sin_addr. else printf("Connected\n"). else printf("Scocket is Created\n").PROGRAM: Manager : #include<stdio.h> main() { int csd.i.sin_family=AF_INET. servaddr.0). struct sockaddr_in servaddr.h> #include<sys/types.

scanf("%s".oid.rmsg.100.\n").rmsg). printf("\nThe time of Last Utilization for %s is %s".100. } else { printf("\nEnter the Object ID for the System\n").oid).100.0).rmsg). send(csd.oid. scanf("%s". System \n"). printf("\nThe Manufacturing date for %s is %s". printf("\n The window size of %s is %s". if(i==1) { printf("Enter the Object ID for Client\n"). scanf("%d".100.oid).0).0).TCP Connection\n"). recv(csd.100.. printf("\n 2..0). recv(csd.rmsg). recv(csd. printf("Enter the number for the type of informtion needed.0).&i).oid.rmsg.printf("\n 1.oid.rmsg.. send(csd.oid. } } 70 .

s_addr=htonl(INADDR_ANY)."3".SOCK_STREAM.(struct sockaddr*)&servaddr.sin_family=AF_INET.cliaddr. if(sd<0) printf("Can't Create \n"). printf("\nEnter the Server port"). servaddr.h> #include<netinet/in.sin_port=htons(sport).clilen. char oid[5][10]={"client1".Agent1 #include<stdio. sd=socket(AF_INET. servaddr.nsd. else printf("Socket is Created\n"). scanf("%d". struct sockaddr_in servaddr.sport. char wsize[5][5]={"5".sd2."6"}."client3".&sport).TCP Connection\n"). 71 . sd2=bind(sd.recvmsg[100].sd."15". char sendmsg[20].len. printf("I'm the Agent .0). printf("\n_____________________\n")."client5"}.h> #include<sys/types.h> main() { int i.sizeof(servaddr)).sin_addr. if(sd2<0) printf(" Can't Bind\n")."client2". servaddr."cleint4"."10".h> #include<string.

for (i=0.else printf("\n Binded\n").&clilen).i++) { if(strcmp(recvmsg. if(nsd<0) printf("Can't Accept\n"). clilen=sizeof(cliaddr).i<5. else printf("Accepted\n"). } } } Agent 2 72 .100.5).(struct sockaddr*)&cliaddr.0). nsd=accept(sd. break.recvmsg.wsize[i].0). recv(nsd.100. listen(sd.oid[i])==0) { send(nsd.

30pm"."11.clilen."14.30am"}.len."System2".81"."11. scanf("%d".12. if(sd<0) printf("Can't Create \n")."System5"}.cliaddr. sd=socket(AF_INET.s_addr=htonl(INADDR_ANY).#include<stdio.sport.SOCK_STREAM.07.77"}.h> main() { int i."System3". char oid[5][10]={"System1". char time[5][15]={"9am"."11am". printf("Enter the Server port").nsd."10-03-08".h> #include<string.h> #include<netinet/in.sd. char sendmsg[20]. printf("\n_____________________\n").sd2. else printf("Socket is Created\n").h> #include<sys/types. servaddr."17.&sport).0)."10pm".sin_addr.recvmsg[100]."System4".sin_family=AF_INET.03."12. 73 . struct sockaddr_in servaddr. char mdate[5][15]={"1-10-095". servaddr.07".

}}} 74 . if(sd2<0) printf(" Can't Bind\n").0).sin_port=htons(sport).5). sd2=bind(sd.recvmsg.oid[i])==0) { send(nsd. nsd=accept(sd. else printf("\n Binded\n"). listen(sd. recv(nsd.time[i].100. send(nsd. for(i=0.&clilen).0).(struct sockaddr*)&servaddr.0).i++) { if(strcmp(recvmsg.servaddr. break.i<5.100. clilen=sizeof(cliaddr). else printf("Accepted\n"). if(nsd<0) printf("Can't Accept\n").(struct sockaddr*)&cliaddr.mdate[i].sizeof(servaddr)).100.

..OUTPUT: Agent1: [mecse8@localhost mecse8]$ cc agent1./a1 I'm the Agent .c -o a1 [mecse8@localhost mecse8]$ . System Enter the number for the type of informtion needed.TCP Connection Enter the Server port _____________________ 65232 Socket is Created Binded Accepted [mecse8@localhost mecse8]$ Manager: [mecse8@localhost mecse8]$ . TCP Connection 2../m Enter the port 6523 Scocket is Created Connected 1. 1 Enter the Object ID for Client client1 The window size of client1 is 5[mecse8@localhost mecse8]$ 75 .

Agent 2: [mecse8@localhost mecse8]$ . 2 Enter the Object ID for the System System3 The Manufacturing date for System3 is 14./a2 Enter the Server port _____________________ 6523 Socket is Created Binded Accepted [mecse8@localhost mecse8]$ Manager : [mecse8@localhost mecse8]$ .. System Enter the number for the type of informtion needed.03..81 The time of Last Utilization for System3 is 11am 76 ..TCP Connection 2./m Enter the port 6523 Scocket is Created Connected 1.

RESULT: Thus the C program for simple network management protocols has been executed successfully. 77 .

The NS project is now a part of the VINT project that develops tools for simulation results display. NS began as a variant of the REAL network simulator in 1989 and has evolved substantially over the past few years. i. routing algorithms such as Dijkstra. NS has always included substantial contributions from other researchers. router queue management mechanism such as Drop Tail. Web. including wireless code from the UCB Daedelus and CMU Monarch projects and Sun Microsystems. Ns-2 has also an emulation feature. 78 . analysis and converters that convert network topologies generated by well-known generators to NS formats. It implements network protocols such as TCP and UDP. Xerox PARC. OVERVIEW: NS is an event driven network simulator developed at UC Berkeley that simulates variety of IP networks.EX NO: DATE: AIM: STUDY OF NETWORK SIMULATOR To study about NS2 . The network simulator ns-2 is a widely accepted discrete event network simulator. CBR and VBR. NS provides substantial support for simulation of TCP. routing. the ability to introduce the simulator into a live network and to simulate a desired network between real applications in real-time. NS also implements multicasting and some of the MAC layer protocols for LAN simulations. actively used for wired and wireless network simulations. Currently ns development is support through DARPA with SAMAN and through NSF with CONSER. Within the scope of this project we developed some methods and extensions to the ns-2 to combine wireless network simulation and network emulation. In 1995 ns development was supported by DARPA through the VINT project at LBL. and USC/ISI. Telnet. RED and CBQ.11 networks. UCB. and more.e. and multicast protocols over wired and wireless (local and satellite) networks. Currently. both in collaboration with other researchers including ACIRI. traffic source behavior such as FTP.Network Simulator INTRODUCTION: NS is a discrete event simulator targeted at networking research. It has a highly detailed model of the lower layers (Physical and MAC) of wireless IEEE 802.

This may sound like complicated job. but the plumbing OTcl modules actually make the job very easy. in a simplified user's view. Another major component of NS beside network objects is the event scheduler. This document talks briefly about the basic structure of NS. When a user wants to make a new network object. a user should write an OTcl script that initiates an event scheduler. modified little bit as needed. Simplified User's View of NS As shown in Figure 1. sets up the network topology using the network objects and the plumbing functions in the library. 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"). and network setup (plumbing) module libraries (actually. 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. 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.NS (version 2) written in C++ and OTcl (Tcl script language with Object-oriented extensions developed at MIT) is available. and tells traffic sources when to start and stop transmitting packets through the event scheduler. NS is Object-oriented Tcl (OTcl) script interpreter that has a simulation event scheduler and network component object libraries. and plumb the data path through the object. The term "plumbing" is used for a network setup. which usually are 79 . and explains in detail how to use NS mostly by giving examples. you program in OTcl script language. 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. he or she can easily make an object either by writing a new object or by making a compound object from the object library. In NS. to use NS. To setup and run a simulation network. The power of NS comes from this plumbing. In other words. Figure 1. plumbing modules are implemented as member functions of the base simulator object).

however this does not consume actual simulation time. the controls of the C++ objects are given to OTcl. Likewise. Figure 2 shows an object hierarchy example in C++ and OTcl. 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. the event scheduler and the basic network component objects in the data path are written and compiled using C++. which then passes the packet to an appropriate output link component. All the network components that need to spend some simulation time handling a packet (i. In this way. The scheduler after 20 microseconds dequeues the event and fires it to the switch component. 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. an object (not in the data path) can be entirely implemented in OTcl. For example. Figure 2. One thing to note in the figure is that for C++ objects that have an OTcl linkage forming a hierarchy. and let them do the appropriate action associated with packet pointed by the event.e. Another use of an event scheduler is timer. It is also possible to add member functions and variables to a C++ linked OTcl object. In order to reduce packet and event processing time (not simulation time). Network components communicate with one another passing packets. NS is written not only in OTcl but in C++ also. These compiled objects are made available to the OTcl interpreter through an OTcl linkage that creates a 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. 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.the ones who issued the events. For efficiency reason. there is a matching OTcl object hierarchy very similar to that of C++. NS separates the data path implementation from control path implementations. C++ and OTcl: The Duality 80 .

and also has a display speed controller. NAM has a nice graphical user interface similar to that of a CD player (play. OTcl) script. designing and running simulations in Tcl using the simulator objects in the OTcl library. which is a OO extended Tcl interpreter with network simulator libraries. NS produces one or more text-based output files that contain detailed simulation data. although the graphical information cannot be used for accurate simulation analysis. This section briefly examined the general structure and architecture of NS. rewind. Furthermore. 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. At this point.Figure 3. when a simulation is finished. As shown in Figure 1. Architectural View of NS Figure 3 shows the general architecture of NS. 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 of VINT project. This section shows a simple NS simulation script and explains what each line does. it can graphically present information such as throughput and number of packet drops at each link. fast forward. if specified to do so in the input Tcl (or more specifically. In this figure a general user (not an NS developer) can be thought of standing at the left bottom corner. Example 3 is an OTcl script that creates the simple network configuration and runs the simulation scenario in Figure 4. one might be wondering about how to obtain NS simulation results. pause and so on). The whole thing together makes NS. 81 .

A "tcp" agent is attached to n0. The duplex links between n0 and n2. 82 . and n1 and n2 have 2 Mbps of bandwidth and 10 ms of delay.7 Mbps of bandwidth and 20 ms of delay. the maximum size of a packet that a "tcp" agent can generate is 1KByte. A Simple Network Topology and Simulation Scenario This network consists of 4 nodes (n0. Each node uses a DropTail queue. n3) as shown in above figure.Figure 4. A "udp" agent that is attached to n1 is connected to a "null" agent attached to n3. The duplex link between n2 and n3 has 1. As default. A "null" agent just frees the packets received. A tcp "sink" agent generates and sends ACK packets to the sender (tcp agent) and frees the received packets. n1. n2. of which the maximum size is 10. and a connection is established to a tcp "sink" agent attached to n3.

Similarly. This member function of "Simulator" object is for the NAM display.Example 1. attach-agent)  Set network component parameters (mostly for compound objects)  Create connections between agents (ex. o Initialize the packet format (ignore this for now) o Create a scheduler (default is calendar scheduler) o 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. The "Simulator" object member function implementations are located in the "ns-2/tcl/lib/ns-lib. however some of them are for the NAM display. • $ns color fid color: is to set color of the packets for a flow specified by the flow id (fid). make connection between a "tcp" and "sink")  Specify NAM display options Most of member functions are for simulation setup and scheduling. • • 83 . an NS script starts with making a Simulator object instance. • set ns [new Simulator]: generates an NS simulator object instance. A Simple NS Simulation Script The following is the explanation of the script above. and assigns it to variable ns (italics is used for variables and values in this section).0 "finish". In general. proc finish {}: is called after this simulation is over by the command $ns at 5. post-simulation processes are specified. $ns namtrace-all file-descriptor: This member function tells the simulator to record simulation traces in NAM input format. the member function trace-all is for recording the simulation trace in a general format.tcl" file. In this function. and has no effect on the actual simulation. It also gives the file name that the trace will be written to later by the command $ns flush-trace.

Users can create a node by separately creating an address and a port classifier objects and connecting them together. $ns duplex-link node1 node2 bandwidth delay queue-type: creates two • 84 .tcl".tcl" and "ns-2/tcl/libs/ns-node. A node in NS is compound object made of address and port classifiers (described in a later section). look at the files: "ns-2/tcl/libs/ns-lib. this member function of Simulator object makes the job easier. To see how a node is created.• set n0 [$ns node]: The member function node creates a node. However.

users can comment these lines out and try the simulation. and attach them to nodes and agents respectively. In NS. Therefore. the next thing to do is to setup traffic agents such as TCP and UDP. traffic sources such as FTP and CBR. what this function does is call the attach member function of specified node.tcl" file. users can create any agent or traffic sources in this way. DropTail queue is used. a user should know the class names these objects (Agent/TCP. there are no specific Simulator object member functions that create these object instances. Please take a look at "ns-2/tcl/libs/ns-lib. Like a node. or NS documentation for more information.: The next couple of lines are used for the NAM display. At this point. a user can do the same thing by. mostly implemented in C++ and linked to OTcl. Agnet/TCPSink. Link source codes can be found in "ns-2/tcl/libs/ns-lib. Refer to the NS documentation to find out how to do this. the next thing is to establish a logical network connection 85 • • . the output queue of a node is implemented as a part of a link. a link is a compound object. $ns attach-agent node agent: The attach-agent member function attaches an agent object created to a node object. But in general. which attaches the given agent to itself.. This file contains the default configurable parameter value settings for available network objects. and users can create its sub-objects and connect them and the nodes. Therefore.tcl" files. If the reader wants to use a RED queue. $ns connect agent1 agent2: After two agents that will communicate with each other are created. Agents and traffic sources are in fact basic objects (not compound objects). To create agents or traffic sources. Application/FTP and so on). and connects the two specified nodes. therefore users should specify the queue-type when creating links. • $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. • Now that the basic network setup is done. the authors do not know how many of these kinds of member functions of Simulator objects are available and what they are. But one shortcut is to look at the "ns-2/tcl/libs/ns-default. 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 network objects).tcl". This information can be found in the NS documentation or partly in this documentation. In the above simulation script.tcl" and "ns2/tcl/libs/ns-link. Therefore. Actually.. for example. • set tcp [new Agent/TCP]: This line shows how to create a TCP agent. it works as a good indicator of what kind of network objects are available in NS and what are the configurable parameters.simplex links of specified bandwidth and delay. The NS implementation of a link is shown in a later section. simply replace the word DropTail with RED. $n0 attach $tcp. To see the effects of these lines. $ns duplex-link-op node1 node2 .tcl" and "ns-2/tcl/libs/ns-link.

This line establishes a network connection by setting the destination address to each others' network and port address pair.between them. 86 .

Class Hierarchy (Partial) The root of the hierarchy is the TclObject class that is the superclass of all OTcl library objects (scheduler. NsObject class is 87 . just knowing how much of the data to transfer. creates packets and sends them. the only thing left is to run the simulation. but it notifies the underlying agent that it has some amount of data to transmit.e. The Simulator object has many scheduling member functions. NETWORK COMPONENTS: Figure 6. This is done by $ns run. For example. timers and the other objects including NAM related ones). As an ancestor class of TclObject. simulation scheduling). the next thing to do is write a simulation scenario (i. usually a traffic source does not transmit actual data.Assuming that all the network configuration is done. network components. scheduling and post-simulation procedure specifications are done. In NS. However.1 "$cbr start" will make the scheduler call a start member function of the CBR traffic source object. $ns at 0. After all network configuration. 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. which starts the CBR to transmit data. and the agent.

Unicast nodes are the default nodes. A multicast node. based on the number of the possible output data paths.$ns rtproto type .the superclass of all basic network component objects that handle packets. The basic network components are further divided into two subclasses. The basic network objects that have only one output data path are under the Connector class. There are two types of nodes in NS. Session. cost. A unicast node has an address classifier that does unicast routing and a port classifier. in addition.  Unicast . DV. and switching objects that have possible multiple output data paths are under the Classifier class. Node (Unicast and Multicast) In NS. Connector and Classifier. the user can also select a specific routing protocol other than using a default one. NODE AND ROUTING: A node is a compound object composed of a node entry object and classifiers as shown in Figure 7.type: Static. Figure 7. 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. multi-pat 88 . has a classifier that classify multicast packets from unicast packets and a multicast classifier that performs multicast routing. which may compose compound network objects such as nodes and links. After specifying the node type.

If the simulator is directed to trace network activities (specified using $ns trace-all file or $ns namtraceall file). the TTL object calculates Time To Live parameters for each packet received and updates the TTL field of the packet.• Multicast . Link One thing to note is that an output queue of a node is actually implemented as a part of simplex link object. 89 .$ns mrtproto type . • Tracing In NS. DM. network activities are traced around simplex links. Finally. and packets dropped at a queue are sent to a Null Agent and are freed there. two simplex links in both directions are created as shown in Figure 8. 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. BST LINK: A link is another major compound object in NS. the links created after the command will have the following trace objects inserted as shown in Figure 9. ST.type: CtrMcast.$ns multicast (right after set $ns [new Scheduler]) . Figure 8. Packets dequeued from a queue are passed to the Delay object that simulates the link delay. When a user creates a link using a duplex-link member function of a Simulator object.

Monitoring Queue When a packet arrives. For example.e.e. need for queue monitoring).Figure 9. DeqT. A RED queue monitoring example is shown in the RED Queue Monitor Example section. he or she might be interested in what is going on inside a specific output queue. a snoop queue object notifies the queue monitor object of this event. Figure 10. Queue Monitor Basically. and passes the packet to the next network object. The queue monitor using this information monitors the queue. Inserting Trace Objects When each inserted trace object (i. DrpT and RecvT) receives a packet. Note that snoop queue objects can be used in parallel with tracing objects even though it is not shown in the above figure. EnqT. Although a user gets enough information from the trace. tracing objects are designed to record packet arrival time at which they are located. The trace format will be examined in the General Analysis Example section. Queue monitoring can be achieved using queue monitor objects and snoop queue objects as shown in Figure 10. it writes to the specified trace file without consuming any simulation time. 90 . 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.

As briefly mentioned in the "Simple Simulation Example" section. Packet Flow Example Note that the above figure does not show the exact behavior of a FTP over TCP. The network consist of two nodes (n0 and n1) of which the network addresses are 0 and 1 respectively. a stack composed of all registered headers is created when a packet is allocated by an agent. and an optional data space (see Figure 12). an FTP application (or traffic source) is attached to the TCP agent. such as the common header that is commonly used by any objects as needed. IP header. asking to send some amount of data. and the offset of each header in the stack is recorded. PACKET: A NS packet is composed of a stack of headers. a packet header format is initialized when a Simulator object is created. TCP header. the two most important network components (node and link) were examined. Figure 11 shows internals of an example simulation network setup and packet flow. where a stack of all registered (or possibly useable) headers. and a network object can access any header in the stack of a packet it processes using the corresponding offset value. RTP header (UDP uses RTP header) and trace header. What this means is that whether or not a specific header is used.PACKET FLOW EXAMPLE: Until now. A TCP agent attached to n0 using port 0 communicates with a TCP sink object attached to n1 port 0. Finally. 91 . It only shows the detailed internals of simulation network setup and a packet flow. Figure 11. is defined.

if you want to implement an application that talks to another application cross the network. 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. Although a packet can carry actual data (from an application) by allocating a data space. very few application and agent implementations support this. The second approach is shown as an example in a later section called "Add New Application and Agent". However. RESULT: Thus the details about NS2(Network Simulator 2) has been studied. This is because it is meaningless to carry data around in a non-real-time simulation. 92 . NS Packet Format Usually. you might want to use this feature with a little modification in the underlying agent implementation. a packet only has the header stack (and a data space pointer that is null).Figure 12.

packet switched radio networks. OPNET Modeler is intended for modeling. An example of use of OPNET is George Mason University (Quality of Service IP Network Simulation). Common uses are assessing and feasibility of new designs.. OPNET Modeler and OPNET Planner. Those processes and built-in modules in OPNET (source and destination modules.) are then configured with menus and organized into data flow diagrams that represent nodes using the graphical Node Editor. State and transitions are specified graphically using state-transition diagrams whereas conditions that specify what happen within each state are programmed with a C-like language called Proto-C. the Model Library. Process models are structured as a finite state machine. Using a graphical Network Editor. Features included in this generic simulator are an event-driven scheduled simulation kernel. THE PACKAGE The software comprises several tools and is divided in several parts. graphical specification of models and a hierarchical object-based modeling. At the lowest level.Network Simulator INTRODUCTION: OPNET (Optimized Network Engineering Tools) is a commercial tool from MIL3 Inc. 93 . As everyone should guess. optimizing already developed communication systems and predicting performance. nodes and links are selected to build up the topology of a communication network. OPNET is used by companies like Thomson-CSF or CNET which use it to model ATM networks and validate various layers protocols. and the Analysis tool. queues..EX NO: DATE: AIM: STUDY OF OPNET To study about OPNET . traffic generators. but it would take time for the computation. It is being developed for almost 15 years. no much technical detail are available about the internals. integrated analysis tools for interpreting and synthesizing output data. simulating and analyzing the performance of large communications networks. computer systems and applications. USE: Network with several hundreds of nodes can be simulated. The modeling methodology of OPNET is organized in a hierarchical structure. .

The Analysis Tool provides a graphical environment to view and manipulate data collected during simulation runs. Results can be analyzed for any network element. OPNET Planner is an application that allows administrators to evaluate the performance of communications networks and distributed systems, without programming or compiling. Planner analyses behavior and performance by discreteevent simulations. Models are built using a graphical interface. The user only chooses pre-defined models (from the physical layer to the application) from the library and sets attributes. The user cannot define new models, he should contact MIL3's modeling service. The modeling libraries are included with OPNET Modeler and OPNET Planner and contains protocols and analysis environments, among them ATM, TCP, IP, Frame Relay, FDDI, Ethernet, link models such as point-to-point or bus, queueing service disciplines such as First-in-First-Out (FIFO), Last-In-First-Out (LIFO), priority non-preemptive queueing, shortest first job, round-robin or preempt and resume. OPNET Modeler is the industry's leading environment for network modeling and simulation, allowing you to design and study communication networks, devices, protocols, and applications with unmatched flexibility and scalability. Modeler is used by the world's largest network equipment manufacturers to accelerate the R&D of network devices and technologies such as VoIP, TCP, OSPFv3, MPLS, IPv6, and more. Networking technology has become too complex for traditional analytical methods or "rules of thumb" to yield an accurate understanding of system behavior. Since 1986, OPNET Technologies Inc., has been the leader in developing predictive software solutions for networking professionals. OPNET software enables its users to optimize the performance and maximize the availability of communications networks and applications. OPNET is the state-of-art network simulation tool for modeling, simulating and analysing the performance of i. ii. Communication Networks, Distributed Systems Computer systems and Applications.

Product modules provide value-added capabilities to OPNET's intelligent network management software. Modules span a wide range of applications and receive regular updates under OPNET's maintenance program.

94

OPNET MODULES:
 Modeler  Terrain Modeling Module (TMM)  High Level Architecture (HLA)

MODELER:
OPNET Modeler is intended for modeling, simulating and analysing the performance of large communications networks, computer systems and applications. Common uses are assessing and feasibility of new designs, optimizing already developed communication systems and predicting performance. The modeling methodology of OPNET is organized in a hierarchical structure. At the lowest level, Process models are structured as a finite state machine. State and transitions are specified graphically using state-transition diagrams whereas conditions that specify what happen within each state are programmed with a C-like language called Proto-C. Those processes, and built-in modules in OPNET (source and destination modules, traffic generators, queues, ...) are then configured with menus and organized into data flow diagrams that represent nodes using the graphical Node Editor. Using a graphical Network Editor, nodes and links are selected to build up the topology of a communication network.

TERRAIN MODELING MODULE (TMM)
Building on the capabilities of OPNET's Wireless Module, the Terrain Modeling Module provides the next level of accuracy and control for wireless network design and planning. This module allows you to model environmental effects on wireless network communications anywhere. Featuring an open-source Longley-Rice model, the Terrain Modeling Module is ready to replicate any known atmospheric or topological conditions and their combined impact on signal propagation. Create elevation maps, line-of-sight profiles, and signal-power comparisons of mobile network models. Interfaces to read DTED and USGS DEM terrain data are provided. Open and flexible, the Terrain Modeling Module is supported by the standard Radio Transceiver Pipeline, which enables easy implementation of custom propagation models

95

HIGH LEVEL ARCHITECTURE (HLA)
The High-Level Architecture (HLA) Module supports building and running a federation of many simulators, each modeling some aspect of a composite system. The OPNET HLA Module enables OPNET simulations to model some portion (or the entirety) of the communications aspects of the HLA federation models. The OPNETHLA interface provides the various simulators (federates) the necessary mechanisms to share a common object representation (for persistent elements), to exchange messages (interactions), and to maintain appropriate time synchronization.

The module supports a large subset of the HLA interface, including:  Time management such that an OPNET simulation remains synchronized with overall HLA time  Generation and reception of RTI interactions using OPNET packet  Creation, destruction, or discovery of RTI objects during the simulation  Generation of RTI object attribute updates based on changes to OPNET attribute values  Automatic updates of OPNET attributes upon reception of RTI object attribute updates  A user-defined mapping specifying the relation between RTI and OPNET objects

RESULT:
Thus the Network Simulator-OPNET has been studied.
96

97 .

Sign up to vote on this title
UsefulNot useful