Sunteți pe pagina 1din 37

SUDHARSAN ENGINEERING COLLEGE SATHIYAMANGALAM-622 501

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

COMPUTER NETWORKS LAB MANUAL


III YEAR V SEMESTER

HANDLED BY

O.S.Jannath Nisha

1. Socket Creation
Aim: To create a Socket Using Unix socket Programming function calls. Procedure: 1. Creation of TCP socket TCP socket is created using IPV4 family AF_INET with SOCK_STREAM 2. Creation of UDP socket UDP socket is created using IPV4 family AF_INET with SOCK_DGRAM 3. Successful Creation of socket returns a file descriptor value for TCP and UDP. 1.// Creation of Socket #include <sys/socket.h> int main() { int sd,c; printf("1.UDP\n2.TCP/IP\n"); printf("\n Enter your option"); scanf("%d",&c); switch(c) { case 1: sd=socket(AF_INET,SOCK_DGRAM,0); if(sd<0) printf("error"); else printf("UDP socket has been created ,SD is %d\n",sd) break; case 2: sd=socket(AF_INET,SOCK_STREAM,0); if(sd<0) printf("error"); else printf("TCP socket has been created ,SD is %d\n",sd) break; } return 0; }

Sample i/p and o/p: $ cc sock.c $ ./a.out Enter your choice 1 TCP 2 UDP TCP socket is successfully created UDP socket is successfully created Result: Thus the socket for TCP and UDP is created successfully.

2. ARP Implementation
Aim: To write a c program to simulate ARP and RARP Algorithm: 1. Get the input ip address or mac address using switch case. 2. In case1, the input ip address is verified and equivalent mac address is displayed. 3. In case2, for given mac address is verified and equivalent ip address is displayed. 4. if input is not correct print the statement incorrect address. Program #include<stdio.h> #include<conio.h> #include<string.h> char ip[40],mc[40]; void main() { int i,flag=0; int choice; char ipaddr[40][40]={"172.16.2.30","172.15.2.31"}; char mcaddr[40][40]={"AD234FG234","FG456FG789"}; printf("\n 1.ARP 2.RARP 3.EXIT"); printf("\n enter your choice:"); scanf("%d",&choice); do { switch(choice) { case 1: printf("\n enter ip address:"); scanf("%s",ip); if(flag==0) { for(i=0;i<5;i++) { if(strcmp(ip,ipaddr[i])==0) { printf("%s\n",mcaddr[i]); flag=1; } }

} else { printf("ip incorrect"); break; } case 2: printf("enter the mc address:"); scanf ("%s",mc); if(flag==0) { for(i=0;i<5;i++) { if(strcmp(mc,mcaddr[i])==0) { printf("%s",ipaddr[i]); flag=0; } } } else printf("mc is incorrect"); break; case 3: exit(0); } }while(i<=3); getch(); }

RESULT: Thus the program for ARP was written and executed.

3. CRC Computation
Aim: To write a program that computes CRC Computation. Algorithm: CRC Computation: 1. Read the frame with m bits M(x). 2. Let r be the degree of G(x). Append r zero bits to the low-order end of the frame. 3. Divide the bit string corresponding to G(x) into xr M(x) using Mod-2 division. 4. Subtract the remainder from the bit string corresponding to xr M(x) using Mod-2 subtraction. 5. The result is the check summed frame to be transmitted T(x). #include<stdio.h> #include<conio.h> void main() { int da[20],di[20],te[20],tem[20],l; int i,j,m,n,data,div,t,k,e; clrscr(); printf("\nEnter the total bit of data and divisor"); scanf("%d %d",&data,&div); m=data+div-1; printf("\nEnter the data:"); for(i=0;i<data;i++) { scanf("%d",&da[i]);te[i]=da[i]; } for(i=data;i<m;i++) { te[i]=0; } printf("\nEnter the divisor"); for(i=0;i<div;i++) { scanf("%d",&di[i]); } l=div;t=0; k=0; for(i=0;i<data;i++) { e=0;t=0; for(j=1;j<div;j++) { if(((da[j]==1)&&(di[j]==1))||((da[j]==0)&&(di[j]==0))) { 7

tem[j-1]=0; if(e!=1) { k=k+1; t=t+1; i=i+1; } } else { tem[j-1]=1; e=1; } } j=0; for(e=t;e<div-1;e++) { da[j]=tem[e]; j++; } for(j=j;j<div;j++) { if(l>=data+1) { da[j]=0; } else { da[j]=te[l]; l=l+1; } } } printf("\n The CRC BITS are\t "); for(i=0;i<div-1;i++) { printf(" %d",tem[i]); } getch(); } Result: Thus the CRC computation has been done.

4. Hamming Code for Error Handling


Aim: To write a program that computes hamming code for error handling. Algorithm: Bit Stuffing: 1. Read the binary file. 2. Divide the file into several frames. 3. Each frame should begin and end with some special bit pattern. 4. Stuff the frame with the escape byte before a flag byte in the data. Eg: Original Stuffed bits : : 00111111111111010 0011111011111011010

#include<stdio.h> #include<conio.h> void main() { int n,in[5][24],stuff[5][50],c[10],destuff[5][50],d[10]; int i=0,k=0,j=0,l=0; clrscr(); printf("\n Bitstuffing and bit destuffing \n Enter the no of frames"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the data for frame%d",i); for(j=0;j<24;j++) { if((j==0)||(j==7)||(j==16)||(j==23)) in[i][j]=0; else if((j>0)&&(j<8)||(j>16)&&(j<23)) in[i][j]=1; else scanf("%d",&in[i][j]); } } for(i=0;i<n;i++) { printf("\n\t Frame %d is",i); for(j=0;j<24;j++) { if((j==8)||(j==16))

printf("\t"); printf("%d",in[i][j]); } } // Bit Stuffing // for(i=0;i<n;i++) { k=0; j=0; while(j!=24) { if((j>=0)&&(j<=7)||(j>=16)&&(j<=23)) { stuff[i][k++]=in[i][j]; j++; } else if((in[i][j]==1)&&(in[i][j+1]==1)&&(in[i][j+2]==1)&&(in[i][j+3]==1)&&(in[i] [j+4]==1)) { stuff[i][k++]=in[i][j]; stuff[i][k++]=in[i][j+1]; stuff[i][k++]=in[i][j+2]; stuff[i][k++]=in[i][j+3]; stuff[i][k++]=in[i][j+4]; stuff[i][k++]=0; j=j+5; } else { stuff[i][k++]=in[i][j]; j++; } } c[i]=k; } printf("\n\t\t the stuffed data is:\n"); for(i=0;i<n;i++) { printf("\n\tframe %d:",i); for(j=0;j<c[i];j++) { if((j==8)||(j==c[i]-8)) printf("\t"); printf("%d",stuff[i][j]); }

10

} getch(); // Bit Destuffing// for(i=0;i<n;i++) { l=0; j=0; while(j!=c[i]) { if((j<8)||(j>=c[i]-8)) { destuff[i][l++]=stuff[i][j]; j++; } else if((in[i][j]==1)&&(in[i][j+1]==1)&&(in[i][j+2]==1)&&(in[i][j+3]==1)&&(in[i] [j+4]==1)) { destuff[i][l++]=stuff[i][j]; destuff[i][l++]=stuff[i][j+1]; destuff[i][l++]=stuff[i][j+2]; destuff[i][l++]=stuff[i][j+3]; destuff[i][l++]=stuff[i][j+4]; j=j+6; } else { destuff[i][l++]=stuff[i][j]; j++; } } d[i]=l; } printf("\n\t\t the destuffed data is:\n"); for(i=0;i<n;i++) { printf("\n\tframe %d:",i); for(j=0;j<d[i];j++) { if((j==8)||(j==16)) printf("\t"); printf("%d",destuff[i][j]); } getch(); }

11

} ---------------------------------------------------------------------------Bitstuffing and bit destuffing Enter the no of frames2 Enter the data for frame01 0 0 1 1 1 1 1 Enter the data for frame10 1 0 1 0 1 0 1 Frame 0 is01111110 10011111 Frame 1 is01111110 01010101 the stuffed data is: frame 0:01111110 100111110 frame 1:01111110 01010101 the destuffed data is: frame 0:01111110 10011111 frame 1:01111110 01010101 01111110 01111110 01111110 01111110 01111110 01111110

-----------------------------------------------------------------------------Sample Output Enter the total bit of data and divisor8 4 Enter the data: 1 0 0 1 1 0 0 1 Enter the divisor1 1 0 1 The CRC BITS are Result: Thus the hamming code has been done. 111

12

5. Simulation of Sliding-Window protocol Aim: To simulate the one bit Sliding Window Protocol. Algorithm: 1. From one node A, it should send series of frames sequentially numbered modulo some maximum value. 2. Establishes multiple buffers and informs sender in the receiving side. 3. Sending side Transmits packets for all available buffers Only waits if no signal arrives before transmission completes 3. And on the receiving side, it sends signals as packets arrives.

UDP Server #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<errno.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #define MYPORT 4950 13

#define MAXBUFLEN 100 int main(void) { int i,sockfd; struct sockaddr_in my_addr; struct sockaddr_in their_addr; socklen_t addr_len; int numbytes; char buf[MAXBUFLEN]; if((sockfd=socket(PF_INET,SOCK_DGRAM,0))==-1) { perror("Socket"); exit(1); } my_addr.sin_family=AF_INET; my_addr.sin_port =htons(MYPORT); my_addr.sin_addr.s_addr=INADDR_ANY; memset(&(my_addr.sin_zero),'\0',8); if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1) { perror("bind"); exit(1); } i=0; while(i<3) { addr_len=sizeof(struct sockaddr); if((numbytes=recvfrom(sockfd,buf,MAXBUFLEN-1,0,(struct sockaddr *)&their_addr,&a ddr_len))==-1) { perror("recvfrom"); exit(1); } if(numbytes==0) { sendto(sockfd,"NOT Sent",15,0,(struct sockaddr *)&their_addr,sizeof(struct socka ddr)); } else { sendto(sockfd,"1",25,0,(struct sockaddr *)&their_addr,sizeof(struct sockaddr)); printf("packet from:\t%s\n",inet_ntoa(their_addr.sin_addr)); printf("Size:\t\t%d bytes\n",numbytes); buf[numbytes]='\0'; printf("data:\t\t%s\n\n",buf);

14

} i++; strcpy(buf,"\0"); } close(sockfd); return 0; } -----------------------------------------------------------------------------------------------UDP Client #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<errno.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<netdb.h> #define MAXBUFLEN 100 #define SERVERPORT 4950 int main(int argc,char *argv[]) { int sockfd,i,n; char data[5][20]; char buf[MAXBUFLEN]; struct sockaddr_in their_addr; struct hostent *he; int numbytes; socklen_t addr_len; if(argc!=2) { fprintf(stderr,"usage:talker hostname meaasge\n"); exit(1); } if((he=gethostbyname(argv[1]))==NULL) { perror("gethostbyname"); exit(1); } if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1) { perror("socket"); exit(1); }

15

their_addr.sin_family=AF_INET; their_addr.sin_port=htons(SERVERPORT); their_addr.sin_addr=*((struct in_addr *)he->h_addr); memset(&(their_addr.sin_zero),'\0',8); printf("Enter the number of framesto send"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the %d data",i); scanf("%s",data[i]); } i=0; while(i<n) { if((numbytes=sendto(sockfd,data[i],strlen(data[i]),0,(struct sockaddr *)&their_a ddr,sizeof(struct sockaddr)))==-1) { addr_len=sizeof(struct sockaddr); exit(0); } addr_len=sizeof(struct sockaddr); numbytes=recvfrom(sockfd,buf,MAXBUFLEN-1,0,(struct sockaddr *)&their_addr,&addr_ len); printf("Acknowledgement received for frame%d:%s\n",i,buf); if(strcmp(buf,"1")==0) { i++; } } close(sockfd); return 0; } ---------------------------------------------------------------------------------------------Sample Output Server Side [rajkumar@psnacet rajkuamar]$ cc udpser.c [rajkumar@psnacet rajkuamar]$ ./a.out packet from: 127.0.0.1 Size: 7 bytes data: welcome packet from: 127.0.0.1

16

Size: data:

2 bytes to

packet from: 127.0.0.1 Size: 8 bytes data: Networks Client Side [rajkumar@psnacet rajkuamar]$ cc udpcli.c [rajkumar@psnacet rajkuamar]$ ./a.out localhost Enter the number of framesto send3 Enter the 0 datawelcome Enter the 1 datato Enter the 2 dataNetworks Acknowledgement received for frame0:1 Acknowledgement received for frame1:1 Acknowledgement received for frame2:1 Result: Thus the sliding window protocol has been simulated.

17

6. Client Server Application for Chat Aim: Write a program to create a client server application for chat. Algorithm: Server-side: 1. Create a TCP socket and bind the server with the well-known port. 2. The server blocks in the call to accept and waiting for a client connection to complete. 3. For each client fork spawns a child and the child handles the new client. 4. The child closes the listening socket and the parent closes the connected socket. Client-side: 1. Create a TCP socket and fill in with Servers IP address and port number. 2. Make a connection with the server. 3. Use sscanf to convert the two arguments from text strings to long integers and then snprintf to convert the result into a text string. 4.Send text data from server to client vice versa. //Server Program #include<unistd.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> #include<sys/socket.h> #include <stdio.h> int main() { int sd,nsd,cpid,n,i,port=6200; char c[30]="\0",buf1[1024]="\0",buf[1024]="\0"; struct sockaddr_in ser; struct sockaddr_in cli; FILE *fp; if ((sd=socket(AF_INET,SOCK_STREAM,0))<0) { printf("\nError:Socket Creation"); return 0; } bzero((char*)&ser,sizeof(ser)); 18

ser.sin_family=AF_INET; ser.sin_port=htons(port); ser.sin_addr.s_addr=htonl(INADDR_ANY); if (bind(sd,(struct sockaddr*)&ser,sizeof(ser))<0) { printf("\nError:Binding"); return 0; } i=sizeof(cli); listen(sd,1); printf("\nServer Module\n"); if((nsd=accept(sd,(sd,(struct sockaddr*)&cli),&i))==-1) { perror("accept"); exit(0); } while(1) { if((i=recv(nsd,buf1,sizeof(buf1),0))==-1) { perror("send"); break; } printf("client:%s\n",buf1); printf("server"); fgets(buf,sizeof(buf),stdin); if((i=send(nsd,buf,sizeof(buf),0))==-1) { perror("recv"); break; } if(buf[0]=='q') exit(0); } if (nsd==-1) { printf("\nError:Client accepts the problem"); return 0; } close(sd); close(nsd); return 0; } ---------------------------------------------------------------------

19

//Client Program #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> #include<sys/socket.h> #include<arpa/inet.h> #include<errno.h> int main() { int sd,nsd,i,port=6200; char c[30]="\0",buf[1024]="\0",buf1[1024]="\0"; FILE *fp; struct sockaddr_in ser; if ((sd=socket(AF_INET,SOCK_STREAM,0))<0) { printf("\nError:Socket Creation"); return 0; } bzero((char *)&ser,sizeof(ser)); printf("\nPort Address is %d",port); ser.sin_family=AF_INET; ser.sin_port=htons(port); ser.sin_addr.s_addr=htonl(INADDR_ANY); if (connect(sd,(struct sockaddr*)&ser,sizeof(ser))==-1) { printf("\nError:Binding"); return 0; } printf("Client Module\n"); while(1) { printf("client"); fgets(buf1,sizeof(buf1),stdin); if(buf1[0]=='q') { exit(0); } if((i=send(sd,buf1,sizeof(buf1),0))==-1) { perror("send");

20

break; } strcpy(buf1,"\0"); if((i=recv(sd,buf,sizeof(buf),0))==-1) { perror("recv"); break; } printf("server%s\n",buf); } close(sd); return 0; } ---------------------------------------------------------------------------------------------Sample Output: Client Side: AA: hai KK: hello AA: Im in london Server Side: KK: Hai AA: where r u? KK: is it? Result: Thus the client server application-chat has been done.

21

7. File transfer using RS-232 interface Aim: Write a program for transferring files over RS232 PIN Details: S.No 1 2 3 4 5 6 7 8 Abbreviation TD RD CTS DCD DSR DTR RTS RI Expansion Transmit Data Receive Data Clear To Send Serial data o/p Serial data i/p Modem is ready to exchange Function

Data Carrier Detect When the modem detect a carrier from the modem at other end of phone line.This line becomes active. Data Set Ready This tells the UART that the modem is ready to establish the link. Data Transfer This is opposite to DSR.This tells modem Ready that the UART is ready to link. Ready To Send This line informs modem that UART is ready to exchange data Ring Indicator Active when modem detects a ringing signal from PSTN.

Algorithm: 1. Use the RS232 probe. 2. Connect the female DB-9 Connectors to one system. 3. The other end of the probe is connected to COM1 of other system. 4. Make sure that the same COM ports are used for connection i.e Port1 : 3F8 and Port2 : 2F8 5. Write the program in C representing the corresponding ports. 6. Call the function int86 with 0x14,dx,ax registers as arguments. 7. Do the operations in read mode and write mode. #include<dos.h> #include<stdio.h> #include<conio.h>

22

#include<time.h> #define PORT1 0x3F8 void main(void) { int c,send,i=0; char ch; FILE *fp; char fname[40]="",str[30]; clrscr(); /* Turn off interrupts of Port1 to use software testing mode */ outportb(PORT1+1,0); /* Now we set baud rate to 2400 bps */ outportb(PORT1+3,0x80); /* SET DLAB ON */ /*Divisor Latch Low Byte */ outportb(PORT1+0,0x03); /*Divisor Latch High Byte */ outportb(PORT1+1,0x00); /* 8 Bits, No Parity, 1 Stop Bit */ outportb(PORT1+3,0x03); /* Set the FIFO control Register */ outportb(PORT1+2,0xC7); /* Set the Modem control Register for auxillary output ,force register to send, data terminal ready */ outportb(PORT1+4,0x0B); printf("\nTransmit/Recieve(t/r)?"); send=(getch()=='t')?1:0; printf("\nEnter the filename"); scanf("%s",fname); if(!send) { fp=fopen(fname,"w+"); printf("\nFile receiving"); do { c=inportb(PORT1+5); if(c&1) { ch=inportb(PORT1); delay(100); printf("\t%c",ch); fprintf(fp,"%c",ch); } } while(ch!='$'); printf("\nFile received");

23

getchar(); } else { fp=fopen(fname,"r"); printf("\nFile Transferring"); do { ch=fgetc(fp); outportb(PORT1,ch); delay(100); printf("\t%c",ch); } while(ch!='$'); printf("\nFile transferred"); getchar(); } } ------------------------------------------------------------------------------------------------Sample i/p and o/p: Terminal(1): Transmit/Receive(t/r) Enter the file name aaa.txt File transferred C:/>type aaa.txt Hai How are you. Terminal(2): Transmit/Receive(t/r) Enter the file name bbb.txt File received C:/>type bbb.txt Hai How are you. Result: Thus the file has been transferred using RS232.

24

25

8. Shortest Path Algorithm Aim: To write a c program to find shortest path of a network. Algorithm: 1.Specify the number of nodes. 2.Give appropriate weightage to each node transactions. 3. Get the value of source and destination node. 4. Call the function shortest path to display the shortest path. 5. Print the shortest path or distance betweeb nodes. Program #include<stdio.h> #include<conio.h> #include<limits.h> #define max 10 #define text 2 #define perm 1 # define inf INT_MAX int shpath(int[10][10],int,int,int); typedef struct node { int pred; int length; int label; }node; int i,k,min,count; int path[10],dist =10; int rpath[10]; void main() { int a[max][max]; int i,j,from,to,count,n; int choice; clrscr(); printf("\n OUTPUT\n ******\n Enter the nodes"); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { printf("\n Enter the weight from node %d to the node %d :",i,j);

26

scanf("%d",&a[i][j]); } } do { for(i=0;i<10;i++) { path[i]=0; } dist =0; clrscr(); printf("\n MATRIX REPRESENTATION OF A NODE-NODE DISTANCE"); printf("\n ****** ************** ** * ********* ********\n"); for(i=1;i<=n;i++) { printf("\t %d",i); } printf("\n\n"); for(i=1;i<=n;i++) { printf("%d",i); for(j=1;j<=n;j++) { printf("\t%d",a[i][j]); } printf("\n"); } printf("\n Enter the source node:"); scanf("%d",&from); printf("\n Enter the dest node:"); scanf("%d",&to); count = shpath(a,n,from,to); if(dist) { printf("\n The shortest path is :"); printf("%d",from); for(i=2;i<=count;i++) { printf("-> %d",path[i]); } printf("\n"); printf("Minimum distance from node %d to node %d is %d",from,to,dist); getch(); } else {

27

printf("\n Minimum distance is:0"); getch(); } printf("\n\n Press 1 to continue:"); scanf("%d",&choice); }while(choice==1); } int shpath(int a[10][10],int n,int s,int t) { node state[max]; for(i=1;i<=n;i++) { state[i].pred=0; state[i].length=inf; state[i].label = text; } state[s].pred=0; state[s].length=0; state[s].label=perm; k=s; do { for(i=1;i<=n;i++) { if((a[k]>0)&&(state[i].label == text)) { if(state[k].length+a[k][i]<state[i].length) { state[i].pred=k; state[i].length = state[k].length+a[k][i]; } } } min=inf; k=0; for(i=1;i<=n;i++) { if(state[i].label == text && state[i].length<min) { min = state[i].length; k=i; } } if(k==0) { return(0);

28

} state[k].label=perm; }while(k!=t); k=t; count =0; do { count = count+1; rpath[count]=k; k=state[k].pred; }while(k!=0); for(i=1;i<=count;i++) { path[i]=rpath[count-i+1]; } for(i=1;i<count;i++) { dist = dist+a[path[i]][path[i+1]]; } return count; } //return count; //}

RESULT: Thus the program to find shortest path of a network was executed and verified.

29

9. STOP AND WAIT ARQ Aim: To write the program for the simulation of stop amd wait ARQ . Algorithm: 1. The sender sends the frame to the receiver and wait for its acknowledgement. 2. After getting the acknowledgement the sender sends next frame and wait for the acknowledgement. 3. If the frame on acknowledgement is lost, acknowledgement transmitted in to the receiver. 4. Repeat process 3&4 until all frames are transmitted. 5. Execute and verify the program. Program #include<stdio.h> #include<conio.h> #include<process.h> #include<string.h> char sen[20][100],rec[20][100]; int t,d; void main() { char op,i; int nf; sen[0][0]=NULL; while(1) { clrscr(); printf("\n\tMain Menu\n\t**** ****\n\n1.Sending detail\n2.Execute\n3.exit"); printf("\n\nEnter the option <1,2,3>...\t"); scanf("%s",&op); if(op=='1') { printf("Enter the no. of frame:\t"); scanf("%d",&nf); for(i=0;i<nf;i++) { printf("Enter the %d frame data:\t",i+1); scanf("%s",&sen[i]);

30

} printf("\nEnter the waitting time for transmission:\t"); scanf("%d",&d); } else if(op=='2') { if(sen[0][0]==NULL) { printf("Following error is occur:\t No data at sender..."); } else { printf("\n\t\tSENDER\t\t\tRECEIVER"); printf("\n\t\t******\t\t\t********"); if(d==100) { for(i=0;i<nf;i++) { t=0; printf("\n\nSending the %d frame by sender",i+1); printf("\tReceiver receive the %d frame",i+1); while(t<=100) { printf("\t\t\t\tReceiving is '%d%' completed\r",t); delay(100); t++; } printf("\n\n\t\t\t\tReceiving is completed"); strcpy(rec[i],sen[i]); printf("\n\t\t\t\t%d Frame data is:\t",i+1); printf("%s",sen[i]); printf("\n\n\t\t\t\treceiver sending the ack"); sleep(3); printf("\nsender receive the ack"); sleep(2); } sen[0][0]=NULL; printf("\n\nProcess is completed..."); } else {

31

printf("\n\nTransmission error is occured . . .\nPlease Enter the data again...\n"); } } } else if(op=='3') { break; } else printf("\nInvalid option"); getch(); } }

RESULT: Thus the Stop and Wait protocol was written and executed.

32

10. Study of Network Simulators - NS2, Glomosin,Opnet The Class Simulator The overall simulator is described by a Tcl class Simulator. It provides a set of interfaces for configuring a simulation and for choosing the type of event scheduler used to drive the simulation. A simulation script generally begins by creating an instance of this class and calling various methods to create nodes, topologies, and configure other aspects of the simulation. A subclass of Simulator called OldSim is used to support ns v1 backward compatibility. The procedures and functions described in this chapter can be found in ~ns/tcl/lib/ns-lib.tcl, ~ns/scheduler.{cc,h}, and,~ns/heap.h. Simulator Initialization When a new simulation object is created in tcl, the initialization procedure performs the following operations: _ initialize the packet format (calls create_packetformat) _ create a scheduler (defaults to a calendar scheduler) _ create a null agent (a discard sink used in various places) The packet format initialization sets up field offsets within packets used by the entire simulation The scheduler runs the simulation in an event-driven manner and may be replaced by alternative schedulers which provide somewhat different semantics. The null agent is created with the following call: set nullAgent_ [new Agent/Null] This agent is generally useful as a sink for dropped packets or as a destination for packets that are not counted or recorded. Schedulers and Events The simulator is an event-driven simulator. There are presently four schedulers available in the simulator, each of which is implemented using a different data structure: a simple linked-list, heap, calendar queue (default), and a special type called real-time. Each of these are described below. The scheduler runs by selecting the next earliest event, executing it to completion, and returning to execute the next event.Unit of time used by scheduler is seconds. Presently, the simulator is single-threaded, and only one event in execution at any given time. If more than one event are scheduled to execute at the same time, their execution is performed on the first scheduled - first dispatched manner. Simultaneous events are not reordered anymore by schedulers (as it was in earlier versions) and all schedulers should yeild the same order of dispatching given the same input. No partial execution of events or pre-emption is supported. An event generally comprises a firing time and a handler function. The actual definition of an event is found in ~ns/scheduler.h: class Event { public: Event* next_; /* event list */

33

Handler* handler_; /* handler to call when event ready */ double time_; /* time at which event is ready */ int uid_; /* unique ID */ Event() : time_(0), uid_(0) {} }; /* * The base class for all event handlers. When an events scheduled * time arrives, it is passed to handle which must consume it. * i.e., if it needs to be freed it, it must be freed by the handler. */ class Handler { public: virtual void handle(Event* event); }; Two types of objects are derived from the base class Event: packets and at-events. An at-event is a tcl procedure execution scheduled to occur at a particular time. This is frequently used in simulation scripts. A simple example of how it is used is as follows: ... set ns_ [new Simulator] $ns_ use-scheduler Heap $ns_ at 300.5 "$self complete_sim" ... This tcl code fragment first creates a simulation object, then changes the default scheduler implementation to be heap-based (see below), and finally schedules the function $self complete_sim to be executed at time 300.5 (seconds)(Note that this particular code fragment expects to be encapsulated in an object instance procedure, where the appropriate reference to $self is correctly defined.). At-events are implemented as events where the handler is effectively an execution of the tcl interpreter. The List Scheduler The list scheduler (class Scheduler/List) implements the scheduler using a simple linkedlist structure. The list is kept in time-order (earliest to latest), so event insertion and deletion require scanning the list to find the appropriate entry. Choosing the next event for execution requires trimming the first entry off the head of the list. This implementation preserves event execution in a FIFO manner for simultaneous events.

The Heap scheduler The heap scheduler (class Scheduler/Heap) implements the scheduler using a heap structure. This structure is superior to the list structure for a large number of events, as insertion and deletion times are in O(log n) for n events. This implementation in ns v2 is borrowed from the MaRS-2.0 simulator [1]; it is believed that MaRS itself borrowed

34

the code from NetSim [14], although this lineage has not been completely verified. The Calendar Queue Scheduler The calendar queue scheduler (class Scheduler/Calendar) uses a data structure analogous to a one-year desk calendar, in which events on the same month/day of multiple years can be recorded in one day. It is formally described in [6], and informally described in Jain (p. 410) [15]. The implementation of Calendar queues in ns v2 was contributed by David Wetherall (presently at MIT/LCS). The Real-Time Scheduler The real-time scheduler (class Scheduler/RealTime) attempts to synchronize the execution of events with real-time. It is currently implemented as a subclass of the list scheduler. The real-time capability in ns is still under development, but is used to introduce an ns simulated network into a real-world topology to experiment with easilyconfigured network topologies, cross-traffic, etc. This only works for relatively slow network traffic data rates, as the simulator must be able to keep pace with the real-world packet arrival rate, and this synchronization is not presently enforced. Precision of the scheduler clock used in ns Precision of the scheduler clock can be defined as the smallest time-scale of the simulator that can be correctly represented. The clock variable for ns is represented by a double. As per the IEEE std for floating numbers, a double, consisting of 64 bits must allocate the following bits between its sign, exponent and mantissa fields. sign exponent mantissa 1 bit 11 bits 52 bits Any floating number can be represented in the form (X_2n) where X is the mantissa and n is the exponent. Thus the precision of timeclock in ns can be defined as (1=2(52)). As simulation runs for longer times the number of remaining bits to represent the time educes thus reducing the accuracy. Given 52 bits we can safely say time upto around (2(40)) can be represented with considerable accuracy. Anything greater than that might not be very accurate as you have remaining 12 bits to represent the time change. However (2(40)) is a very large number and we donot anticipate any problem regarding precision of time in ns. Commands: Synopsis: ns <otclfile> <arg> <arg>.. Description: Basic command to run a simulation script in ns. The simulator (ns) is invoked via the ns interpreter, an extension of the vanilla otclsh command shell. A simulation is defined by a OTcl script (file). Several examples of OTcl scripts can be found under ns/tcl/ex directory. The following is a list of simulator commands commonly used in simulation scripts:

35

set ns_ [new Simulator] This command creates an instance of the simulator object. set now [$ns_ now] The scheduler keeps track of time in a simulation. This returns schedulers notion of current time. $ns_ halt This stops or pauses the scheduler. $ns_ run This starts the scheduler. $ns_ at <time> <event> This schedules an <event> (which is normally a piece of code) to be executed at the specified <time>. e.g $ns_ at $opt(stop) "puts NS EXITING.. ; $ns_ halt" or, $ns_ at 10.0 "$ftp start" $ns_ cancel <event> Cancels the event. In effect, event is removed from schedulers list of ready to run events. $ns_ create-trace <type> <file> <src> <dst> <optional arg: op> This creates a trace-object of type <type> between <src> and <dst> objects and attaches trace-object to <file> for writing trace-outputs. If op is defined as "nam", this creates nam tracefiles; otherwise if op is not defined, ns tracefiles are created on default. $ns_ flush-trace Flushes all trace object write buffers. $ns_ gen-map This dumps information like nodes, node components, links etc created for a given simulation. This may be broken for some scenarios (like wireless). $ns_ at-now <args> This is in effect like command "$ns_ at $now $args". Note that this function may not work because of tcls string number resolution. These are additional simulator (internal) helper functions (normally used for developing/changing the ns core code) : $ns_ use-scheduler <type> Used to specify the type of scheduler to be used for simulation. The different types of scheduler available are List, Calendar, Heap and RealTime. Currently Calendar is used as default. $ns_ after <delay> <event> Scheduling an <event> to be executed after the lapse of time <delay>. $ns_ clearMemTrace

36

Used for memory debugging purposes. $ns_ is-started This returns true if simulator has started to run and false if not. $ns_ dumpq Command for dumping events queued in scheduler while scheduler is halted. $ns_ create_packetformat This sets up simulators packet format.

37

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