Vous êtes sur la page 1sur 71

EX NO:2 DATE:

CLIENT SERVER APPLICATION FOR CHAT

AIM To develop a client server application for chat. ALGORITHM SERVER 1. Include all the header files needed to create a socket. 2. Create a socket by specifying its family, type and protocol. 3. Declare the size, family, port number and address of the socket. 4. Then bind the socket with the address that is specified. 5. Socket listens whether there is any request from the client. 6. If there is any request accept the connection. 7. Receive the message that is being given by the client. 8. Get the reply from user and send it to client. 9. Repeat from step7 until the user enters q. 10. Close the connection on receiving the message q. CLIENT 1. Create a socket by specifying its family, type and protocol. 2. Declare the size, family, port number and address of the socket that is being created. 3. Connect the client to the server. 4. Get the message from the user and send it to the server. 5. Receive the reply message from the server and display it to the user. 6. Repeat from step4 until the user enters q. 7. Close the connection on receiving the message q.

PROGRAM: SERVER: #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=7698; 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("\n Error:Socket Creation"); return 0; } bzero((char*)&ser,sizeof(ser)); 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("\n Server 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("\n error : client accepts the problem"); return 0; } close(sd); close(nsd); return 0; }

CLIENT: #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=7698; char c[30]="\0",buf1[1024]="\0",buf[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("port 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"); 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; }

10

SAMPLE OUTPUT:

SERVER: -bash-3.2$ cc chatserver.c -bash-3.2$ ./a.out Port address is 7698 Server module Client accepts Client:hai Enter the string:hello Client:good Enter the string:q

CLIENT: -bash-3.2$ cc chatclient.c -bash-3.2$ ./a.out Port address is 7698 Client module Enter the string:hai Server:hello Enter the string:good Enter the string:q

11

DEPT OF I.T PREPARATION PERFORMANCE RECORD TOTAL 30 30 40 100

RESULT: Thus the chat application program is executed successfully and verified.

12

EX. NO: 3 DATE :

IMPLEMENTATION OF FTP

AIM: To write a client server program to implement file transfer.

ALGORITHM: SERVER: 1. Include various header files to create socket. 2. Create a socket by specifying its family, type and protocol. 3. Declare the size, family, port number and address of the socket. 4. Then bind the socket with the respected address that is specified. 5. Socket listens whether there is any request from the client. 6. If there is any request accept the connection. 7. Read and transfer file to the client. CLIENT: 1. Create a socket by specifying its family, type and protocol. 2. Connect the client to the server. 3. Give the source file name that is to be read. 4. Give the destination file name to which the data should be transferred. 5. Send the source file name. 6. Client receives the contents of file.

13

PROGRAM: SERVER: #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,i,port=6987; char c[30]="\0",fname[30]; 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)); printf("\nport address is: %d",port); ser.sin_family=AF_INET; ser.sin_port=htons(port); ser.sin_addr.s_addr=htonl(INADDR_ANY);

14

if(bind(sd,(struct sockaddr*)&ser,sizeof(ser))<0) { printf("\nError:binding"); return 0; } i=sizeof(cli); listen(sd,1); printf("\nServer module\n"); nsd=accept(sd,(sd,(struct sockaddr*)&cli),&i); if(nsd==-1) { printf("\nError:client accepts problem"); return 0; } printf("\nClient accepted"); i=recv(nsd,fname,30,0); fname[i]='\0'; fp=fopen(fname,"rb"); printf("\nFile reading...."); while(1) { i=fread(&c,1,30,fp); c[i]='\0'; send(nsd,c,30,0); printf("%s",c);

15

strcpy(c,"\0"); { if(i<30) break; } } send(nsd,"EOF",4,0); printf("\nFile has been transferred\n"); fclose(fp); close(sd); close(nsd); return 0; }

CLIENT: #include<unistd.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> #include<sys/socket.h> #include<stdio.h> #include<arpa/inet.h> int main() { int sd,nsd,i,port=6987;

16

char c[30]="\0",fname[30],file[30]; struct sockaddr_in ser; FILE *fp; if((sd=socket(AF_INET,SOCK_STREAM,0))<0) { printf("\n Error:Socket Creation"); return 0; } bzero((char*)&ser,sizeof(ser)); printf("\n port 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))<0) { printf("\nError Binding"); return 0; } printf("\nclient module"); printf("\nenter source:"); scanf("%s",fname); printf("\nenter dest:"); scanf("%s",file); send(sd,fname,30,0); fp=fopen(file,"W");

17

printf("receiving...\n"); while(1) { i=recv(sd,c,30,0); c[i]='\0'; printf("%s",c); fwrite(&c,strlen(c),1,fp); strcpy(c,"\0"); if(strcmp(c,"EOF")) break; } printf("\nfile transferred"); fclose(fp); close(sd); return 0; }

18

OUTPUT:

SERVER -bash-3.2$ cc ftpserver.c -bash-3.2$ ./a.out Port number is 6987 Server module Client accepts File reading hello

CLIENT -bash-3.2$ cc ftpclient.c -bash-3.2$ ./a.out Port number is 6987 Client module Enter the source file name : r1 Enter the destination file name : r2 Receivinghello File transferred

19

DEPT OF I.T PREPARATION PERFORMANCE RECORD TOTAL 30 30 40 100

RESULT Thus the client server program for file transfer is executed.

20

EX NO:4 DATE:

SIMULATION OF OSPF ROUTING PROTOCOL

AIM: To write a C program for the simulation of OSPF routing protocol

ALGORITHM: 1. Include the necessary header files. 2. Define the maximum distance of node from the source. 3. Define create graph function. 4. Enter source node and destination node. 5. Within create graph function, enter the number of vertices and weight for the graph. 6. If both origin and destination is zero, then quit. 7. Else find the shortest path and display in matrix format. 8. Then enter the source and destination node. 9. Search for the temporary node with minimum distance and make it permanent. 10. Continue the step9 until the shortest distance is found. 11. Display the shortest distance.

PROGRAM #include<stdio.h> #define MAX 10 #define TEMP 0 #define PERM 1 #define infinity 9999

21

struct node { int predecessor,dist,status; }; int adj[MAX][MAX],n; void main() { int i,j,source,dest,path[MAX],shortdist,count; clrscr(); create_graph(); printf("The adjacency matrix is:\n"); display(); while(1) { printf("Enter source node(0 to quit):"); scanf("%d",&source); printf("enter destination node(0 to quit):"); scanf("%d",&dest); if(source==0||dest==0) exit(1); count=findpath(source,dest,path,&shortdist); if(shortdist!=0) { printf("shortest distance is: %d\n",shortdist); printf("shortest path is:");

22

for(i=count;i>1;i--) printf("%d->",path[i]); printf("%d",path[i]); printf("\n"); } else printf("there is no path from source to destination node\n"); } } create_graph() { int i,max_edges,origin,destin,wt; printf("enter number of vertices:"); scanf("%d",&n); max_edges=n*(n-1); for(i=1;i<=max_edges;i++) { printf("enter edge %d (0 0 to quit):",i); scanf("%d %d",&origin,&destin); if((origin==0)&&(destin==0)) break; printf("enter weight for this edge:"); scanf("%d",&wt); if(origin>n||destin>n||origin<=0||destin<=0) {

23

printf("invalid edge!\n"); i--; } else adj[origin][destin]=wt; } return 0; } display() { int i,j; for(i=1;i<=n;i++) { for(j=1;j<=n;j++) printf("%3d",adj[i][j]); printf("\n"); } return 0; } int findpath(int s,int d,int path[MAX],int *sdist) { struct node state[MAX]; int i,min,count=0,current,newdist,u,v; *sdist=0; for(i=1;i<=n;i++)

24

{ state[i].predecessor=0; state[i].dist=infinity; state[i].status=TEMP; } state[s].predecessor=0; state[s].dist=0; state[s].status=PERM; current=s; while(current!=d) { for(i=1;i<=n;i++) { if(adj[current][i]>0&&state[i].status==TEMP) { newdist=state[current].dist+ adj[current][i]; if(newdist<state[i].dist) { state[i].predecessor=current; state[i].dist=newdist; } } } min=infinity; current=0;

25

for(i=1;i<=n;i++) { if(state[i].status==TEMP&&state[i].dist<min) { min=state[i].dist; current=i; } } if(current==0) return 0; state[current].status=PERM; } while(current!=0) { count++; path[count]=current; current=state[current].predecessor; } for(i=count;i>1;i--) { u=path[i]; v=path[i-1]; *sdist+=adj[u][v]; } return(count); }

26

SAMPLE INPUT AND OUTPUT enter number of vertices:3 enter edge 1 (0 0 to quit):1 2 enter weight for this edge:3 enter edge 2 (0 0 to quit):2 1 enter weight for this edge:2 enter edge 3 (0 0 to quit):2 3 enter weight for this edge:4 enter edge 4 (0 0 to quit):3 2 enter weight for this edge:5 enter edge 5 (0 0 to quit):1 3 enter weight for this edge:2 enter edge 6 (0 0 to quit):3 1 enter weight for this edge:5 The adjacency matrix is: 0 3 2 2 0 4 5 5 0 Enter source node(0 to quit):2 enter destination node(0 to quit):1 shortest distance is: 2 shortest path is:2->1 Enter source node(0 to quit):

27

DEPT OF I.T PREPARATION PERFORMANCE RECORD TOTAL 30 30 40 100

RESULT: Thus the C program for the simulation of OSPF routing protocol is written and executed.

28

EX NO: 5 DATE:

DNS RESOLVER

AIM: To write a C program to implement DNS resolver.

ALGORITHM: 1. Include all the header files that support address conversion mechanism. 2. Get the input from the user. 3. If it is the hostname, print the corresponding IP address and type, length and alias name of the host using the gethostbyname function. 4. If it is an IP address, then print the corresponding name of the host using the gethostbyaddr functions.

PROGRAM: #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<netdb.h> #include<stdio.h> int main() { int choice,i; char name[50]; struct hostent *h;

29

struct in_addr **addr_list; struct in_addr addr; printf("\n1.Name 2.Address"); scanf("%d",&choice); switch(choice) { case 1: printf("\nEnter the name of the site:"); scanf("%s",&name); h=gethostbyname(name); if(h==NULL) { printf("\n Error Site name doesn't exist"); printf("%s",h_errno); exit(0); } printf("\n The IP address is %s",inet_ntoa(*(struct in_addr*) h->h_addr)); break; case 2: printf("\n Enter the IP address"); scanf("%s",&name); if(inet_aton(name,&addr)==0) { printf("%s IP address is not valid",name); exit(0);

30

} h=gethostbyaddr(&addr,sizeof(addr),AF_INET); printf("\n Host name is %s",h->h_name); break; } printf("\n Address type is %d",h->h_addrtype); printf("\n Length is %d",h->h_length); for(i=0;h->h_aliases[i]!=NULL;i=i++) { printf("\n Alias name %d is %s",i+1,h->h_aliases[i]); } addr_list=(struct in_addr**)h->h_addr_list; for(i=0;addr_list[i]!=NULL;i++) { printf("\n Address list is %s",inet_ntoa(*addr_list[i])); } return 0; }

31

SAMPLE INPUT AND OUTPUT -bash-3.2$ cc dnsprogram.c -bash-3.2$ ./a.out 1.Name 2.Address 1

Enter the name of the site:www.google.com

The IP address is 209.85.231.104 Address type is 2 Length is 4 Alias name 1 is www.google.com Address list is 209.85.231.104

-bash-3.2$ ./a.out

1.Name 2.Address 2

Enter the IP address209.85.231.104

Host name is maa03s01-in-f104.1e100.net Address type is 2 Length is 4 Address list is 209.85.231.104-bash-3.2$

32

DEPT OF I.T PREPARATION PERFORMANCE RECORD TOTAL 30 30 40 100

RESULT: Thus the C program to implement DNS resolver is written and executed.

33

EX.NO: 6 DATE:

SIGNAL HANDLING AND HANDLING ZOMBIE

AIM: To write a C program for implementing signal handling and handling zombie. ALGORITHM: SERVER: 1. Include all the various header files needed to create the socket and to handle the Signal 2. Create a socket by specifying its family, type and protocol. 3. Bind the socket with the specified address. 4. Socket listens whether there is any request from the client. 5. Call the signal() function to handle the Zombie signal. 6. If there is any request accept the connection. 7. Call the fork() function to handle the connection. 8. Read the content that is given by the client and send it back to the client. 9. Terminate the child process if the connection it handles is closed. 10. Print the process id of the child process which is being closed.

CLIENT: 1. Create a socket by specifying its family, type and protocol. 2. Establish the connection to the server. 3. Get the content from the user using fgets() function 4. Send it to the server using write() function. 5. Receive the content that is sent by server. 6. Repeat from step3 until the connection is closed.

34

PROGRAM: SERVER #include<unistd.h> #include<stdio.h> #include<sys/socket.h> #include<netinet/in.h> #include<string.h> #include<sys/types.h> #include<arpa/inet.h> #include<sys/errno.h> #include<signal.h> #define MAXLINE 10000 int main(int argc,char**argv) { int LISTENQ,listenfd,connfd,port=8008; void sig_chld(); pid_t childpid; socklen_t clilen; struct sockaddr_in cliaddr,servaddr; listenfd=socket(AF_INET,SOCK_STREAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(port); bind(listenfd,(struct SA*)&servaddr,sizeof(servaddr));

35

listen(listenfd,LISTENQ); signal(SIGCHLD,sig_chld); for(;;) { clilen=sizeof(cliaddr); connfd=accept(listenfd,(struct SA*)&cliaddr,&clilen); if((childpid=fork())==0) close(listenfd); str_echo(connfd); sig_chld(); exit(0); } close(connfd); } void str_echo(int sockfd) { ssize_t n; char buf[MAXLINE]; again: while((n=read(sockfd,buf,MAXLINE))>0) write(sockfd,buf,n); if(n<0&&errno==EINTR) goto again; if(n<0) printf("str_echo:read error");

36

} void sig_chld(int signo) { pid_t pid; int stat; pid=wait(&stat); printf("child %d termination\n",pid); return; }

CLIENT #include<unistd.h> #include<stdio.h> #include<sys/socket.h> #include<netinet/in.h> #include<string.h> #include<sys/types.h> #include<arpa/inet.h> #include<sys/errno.h> #define MAXLINE 100 int main(int argc,char**argv) { int sockfd,port=8008; struct sockaddr_in servaddr; if(argc!=2)

37

printf("usage:tcpcli<IPaddress>"); sockfd=socket(AF_INET,SOCK_STREAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(port); inet_pton(AF_INET,argv[1],&servaddr.sin_addr); connect(sockfd,(struct SA*)&servaddr,sizeof(servaddr)); str_cli(stdin,sockfd); exit(0); } void str_cli(FILE*fp,int sockfd) { char sendline[MAXLINE],recvline[MAXLINE]; while(fgets(sendline,MAXLINE,fp)!=NULL) { write(sockfd,sendline,strlen(sendline)); if(read(sockfd,recvline,MAXLINE)==0) printf("str_cli:server terminated prematurely"); fputs(recvline,stdout); } }

38

SAMPLE INPUT AND OUTPUT: SERVER: -bash-3.2$ cc server.c -bash-3.2$ ./a.out Child -1 termination Child 20798 termination Child -1 termination

CLIENT: -bash-3.2$ cc client.c -bash-3.2$ ./a.out localhost Hai Hai Hello Hello ^C -bash-3.2$

39

DEPT OF I.T PREPARATION PERFORMANCE RECORD TOTAL 30 30 40 100

RESULT: Thus the C program for implementing signal handling and handling zombie is written and executed.

40

EX.NO: 7 DATE:

MULTIPLEXED TCP SERVER AND CLIENT

AIM: To write a C Program to implement multiplexed TCP server and client.

ALGORITHM: SERVER: 1. Include all the various header files needed to create a socket and use select() function. 2. Create a socket by specifying its family, type and protocol. 3. Declare the size, family, port no and address of the socket. 4. Then bind the socket with the respected address that is specified. 5. Socket listens whether there is any request from the client. 6. If there is any request accept the connection using the macro function provided with select() function. 7. Repeat the step 6 until the number of connection reaches FD_SETSIZE.

CLIENT: 1. Create a socket by specifying its family, type, protocol. 2. Declare the size, family, port no and address of the socket that is being created. 3. Connect the client to the server using the macro functions provided with the select() function.

41

PROGRAM SERVER #include<unistd.h> #include<sys/types.h> #include<sys/errno.h> #include<netinet/in.h> #include<string.h> #include<sys/select.h> #define MAXLINE 5000 #define LISTENQ 5000 #define FD_SETSIZE 220 #define SERV_PORT 7669 int main(int argc,char **argv) { int i,maxi,maxfd,listenfd,connfd,sockfd; int nready,client[FD_SETSIZE]; ssize_t n; fd_set rset,allset; char buf[MAXLINE]; socklen_t clilen; struct sockaddr_in cliaddr,servaddr; if((listenfd=socket(AF_INET,SOCK_STREAM,0))<0) { printf("error on socket fn"); return 0;

42

} bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(SERV_PORT); if((bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr)))<0) { printf("error on bind"); return 0; } listen(listenfd,LISTENQ); maxfd=listenfd; maxi=-1; for(i=0;i<FD_SETSIZE;i++) client[i]=-1; FD_ZERO(&allset); FD_SET(listenfd,&allset); for(;;) { rset=allset; nready=select(maxfd+1,&rset,NULL,NULL,NULL); if(nready>0) printf("The select is called and client is waiting"); if(FD_ISSET(listenfd,&rset)) {

43

clilen=sizeof(cliaddr); connfd=accept(listenfd,(struct sockaddr*)&cliaddr,&clilen); for(i=0;i<FD_SETSIZE;i++) if(client[i]<0) { client[i]=connfd; break; } if(i==FD_SETSIZE) printf("TOO MANY CLIENTS.."); FD_SET(connfd,&allset); if(connfd>maxfd) maxfd=connfd; if(i>maxi) maxi=i; if(--nready<=0) continue; } for(i=0;i<=maxi;i++) { if((sockfd=client[i])<0) continue; if(FD_ISSET(sockfd,&rset)) { if((n=read(sockfd,buf,MAXLINE))==0)

44

{ close(sockfd); FD_CLR(sockfd,&allset); client[i]=-1; } else write(sockfd,buf,n); if(--nready<=0) break; } } } }

CLIENT #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> #include<stdlib.h> #include<sys/socket.h> #define SERV_PORT 7669 #define MAXLINE 5000 #define max(a,b) ((a)>(b)? (a): (b)) int main(int argc,char **argv )

45

{ int sockfd; struct sockaddr_in servaddr; if(argc!=2) printf("Usage Error,Enter IP addr."); sockfd=socket(AF_INET,SOCK_STREAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(SERV_PORT); inet_pton(AF_INET,argv[1],&servaddr.sin_addr); connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); str_cli(stdin,sockfd); exit(0); } void str_cli(FILE *fp,int sockfd) { int maxfdp1; fd_set rset; char sendline[MAXLINE],recvline[MAXLINE]; FD_ZERO(&rset); for(;;) { FD_SET(fileno(fp),&rset); FD_SET(sockfd,&rset); maxfdp1=max(fileno(fp),sockfd)+1;

46

select(maxfdp1,&rset,NULL,NULL,NULL); if(FD_ISSET(sockfd,&rset)) { if(read(sockfd,recvline,MAXLINE)==0) printf("str_cli:server terminated prematurely"); fputs(recvline,stdout); } if(FD_ISSET(fileno(fp),&rset)) { if(fgets(sendline,MAXLINE,fp)==NULL) return; write(sockfd,sendline,strlen(sendline)); } } }

47

SAMPLE OUTPUT: SERVER: -bash-3.2$ cc mser.c -bash-3.2$ ./a.out

CLIENT 1: -bash-3.2$ cc mcli.c -bash-3.2$ ./a.out localhost hi hi

CLIENT 2: -bash-3.2$ cc mcli.c -bash-3.2$ ./a.out localhost hello hello

48

DEPT OF I.T PREPARATION PERFORMANCE RECORD TOTAL 30 30 40 100

RESULT: Thus the C Program to implement multiplexed TCP server and client is written and executed.

49

EX.NO: 8 DATE:

IMPLEMENTATION OF RPC

AIM: To write a C program to implement the Remote Procedure call.

ALGORITHM REMOTE HOST 1. Include all the various header files needed to create the socket. 2. Create a socket by specifying its family, type and protocol. 3. Bind the socket with the specified address. 4. Socket listens whether there is any request from client 5. If there is any request accept the connection. 6. Get the input from the client, based on the arithmetic operator choose the function to be executed. 7. Print the result of the executed function to the host which called the function. LOCAL HOST: 1. Create a socket by specifying its family, type and protocol. 2. Establish the connection to the server. 3. Get the content from the user using fgets() function. 4. Send it to the server using send() function. 5. Receive the result of the executed function that is sent by the server.

50

PROGRAM Remote host #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=5347; int a,b; int len,k; char c[30]="\0",buf1[1024]="\0",buf[1024]="\0",cmd[10]; struct sockaddr_in ser; struct sockaddr_in cli; FILE *fp; if((sd=socket(AF_INET,SOCK_STREAM,0))<0) { printf("\n error:socket creation"); return 0; } bzero((char*)&ser,sizeof(ser)); ser.sin_family=AF_INET; ser.sin_port=htons(port);

51

ser.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(sd,(struct sockaddr*)&ser,sizeof(ser))<0) { printf("\n error:Binding"); return 0; } i=sizeof(cli); listen(sd,1); printf("\n REMOTE MODULE\n"); if((nsd=accept(sd,(sd,(struct sockaddr*)&cli),&i))==-1) { perror(accept); exit(0); } if((i=recv(nsd,buf1,sizeof(buf1),0))==-1) { perror("send"); } a=atoi(&buf1[0]); b=atoi(&buf1[2]); switch(buf1[1]) { case '+' : printf("\n Result = %d\n",add1(a,b)); break; case '-' : printf("\n Result = %d\n",sub1(a,b));

52

break; case '*' : printf("\n Result = %d\n",mul1(a,b)); break; case '/' : printf("\n Result = %d\n",div1(a,b)); break; } exit(0); if(nsd==-1) { printf("\n Error:client accepts the problem"); return 0; } close(sd); close(nsd); return 0; } add1(int x,int y) { return(x+y); } sub1(int x,int y) { return(x-y); } mul1(int x,int y)

53

{ return(x*y); } div1(int x,int y) { return(x/y); }

Local Host #include<unistd.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> #include<sys/socket.h> #include<stdio.h> #include<arpa/inet.h> #include<errno.h> int main() { int sd,nsd,i,port=5347; char c[30]="\0", buf1[1024]="\0",buf[1024]="\0"; struct sockaddr_in ser; FILE *fp; if((sd=socket(AF_INET,SOCK_STREAM,0))<0) {

54

printf("\nError:socket creation"); return 0; } bzero((char*)&ser,sizeof(ser)); printf("\n port 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("\n LOCAL HOST\n"); while(1) { printf("RPC COMMAND:"); fgets(buf1,sizeof(buf1),stdin); if(buf1[0]=='q') { exit(0); } if((i=send(sd,buf1,sizeof(buf1),0))==-1) { perror("send");

55

break; } exit(0); } close(sd); return 0; }

56

SAMPLE INPUT AND OUTPUT

LOCAL HOST -bash-3.2$ cc rpccli.c -bash-3.2$ ./a.out

port address is 5349 LOCAL HOST RPC COMMAND:9/3

REMOTE HOST -bash-3.2$ cc rpcser.c -bash-3.2$ ./a.out

REMOTE MODULE

Result = 3

57

DEPT OF I.T PREPARATION PERFORMANCE RECORD TOTAL 30 30 40 100

RESULT: Thus the C program to implement the Remote Procedure Call is written and executed.

58

EX NO:9 DATE:

DOWNLOADING A FILE FROM HTTP SERVER

AIM To write a program to download a file from HTTP server. ALGORITHM 1. Get the host name from user by gethostbyname() function. 2. Establish the connection to the host by calling connect() function. 3. Use GET method to download the content of the specified page. 4. Read and Print the source code of the server.

PROGRAM #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #include<errno.h> char buffer[6096]; char buf[6096]; void error(char *msg) { perror(msg); exit(0); }

59

int main(int argc,char *argv[]) { int sockfd,portno,n; struct sockaddr_in serv_addr; struct hostent *server; char buffer[4096]; portno=80; sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd<0) error("ERROR opening socket"); server=gethostbyname("www.yahoo.com"); if(server==NULL) { fprintf(stderr,"ERROR,no such host\n"); exit(0); } bzero((char *)&serv_addr,sizeof(serv_addr)); serv_addr.sin_family=AF_INET; bcopy((char *)server->h_addr,(char *)&serv_addr.sin_addr.s_addr,server->h_length); serv_addr.sin_port=htons(portno); if(connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0) error("ERRORCORRECTION"); strcpy(buffer,"GET http://www.google.com\r\n\r\nUser-Agent:App\r\n\nHost:192.168 .0.254"); n=send(sockfd,buffer,strlen(buffer),0);

60

if(n<0) error("ERROR writing to socket"); bzero(buf,4096); while((n=recv(sockfd,buf,sizeof(buf),0))!=0) { buf[6095]='\0'; printf("Received:%s",buf); } close(sockfd); return 0; }

61

SAMPLE INPUT AND OUTPUT

-bash-3.2$ cc downldweb.c -bash-3.2$ ./a.out Received:<HEAD><TITLE>Not Found</TITLE></HEAD> <BODY BGCOLOR="white" FGCOLOR="black"> <FONT FACE="Helvetica,Arial"><B> </B></FONT> </BODY>

62

DEPT OF I.T PREPARATION PERFORMANCE RECORD TOTAL 30 30 40 100

RESULT Thus the program to download a file from HTTP server is written and executed.

63

EX NO:10 DATE:

TRACE ROUTE PROGRAM

AIM To write a C program to perform the traceroute function. ALGORITHM 1. Traceroute is a computer network tool for measuring the route path and transit times of packets across an internet protocol(IP) network. 2. execl stands for execute and leave which means that a process will get executed and then terminated by execl. 3. Using fork() function create child process. 4. If the processid is 0,then it will execute child process. 5. execl() function is used to overwrite the child process with the traceroute command. 6. If the processid is not equal to 0, parent process is enabled and it waits until child completes its process and then it displays childpid.

PROGRAM: #include<stdio.h> #include<sys/types.h> #include<unistd.h> #include<string.h> int main(void) { int status; int pid; pid=fork();

64

if(pid==0) { execl("/bin/traceroute", "traceroute", "www.yahoo.com", NULL); printf("\n\nCHILD PROCESS"); exit(0); } else { wait(&status); printf("\n\nPARENT"); printf("\n\nchild returned %d\n",status); } return 0; }

65

SAMPLE INPUT AND OUTPUT -bash-3.2$ cc traceroutepgm.c -bash-3.2$ ./a.out traceroute to www.yahoo.com (69.147.125.65), 30 hops max, 60 byte packets 1 192.168.0.1 (192.168.0.1) 2.559 ms 2.550 ms 2.541 ms 2 115.248.132.161 (115.248.132.161) 5.672 ms 5.666 ms 5.655 ms 3 115.248.107.82 (115.248.107.82) 20.279 ms 20.274 ms 20.263 ms 4 *** 5 62.216.147.73 (62.216.147.73) 39.587 ms 39.582 ms 39.572 ms 6 *** 7 *** 8 xe-0-2-0.0.cji01.nyc005.flagtel.com (85.95.25.89) 238.796 ms 240.184 ms 2 30.778 ms 9 80.81.64.146 (80.81.64.146) 230.801 ms 231.836 ms 231.813 ms 10 ae-6.pat2.dce.yahoo.com (216.115.102.176) 262.856 ms 236.663 ms 229.884 m s 11 ae-1-d151.msr2.re1.yahoo.com (216.115.108.23) 246.819 ms ae-1-d141.msr1.re1 .yahoo.com (216.115.108.19) 229.608 ms ae-2-d141.msr1.re1.yahoo.com (216.115.10 8.59) 238.740 ms 12 te-8-1.bas-a1.re1.yahoo.com (66.196.112.205) 254.542 ms te-7-2.bas-a1.re1.y ahoo.com (66.196.112.207) 244.621 ms 254.982 ms

PARENT child returned 0

66

DEPT OF I.T PREPARATION PERFORMANCE RECORD TOTAL 30 30 40 100

RESULT: Thus the C program to perform the traceroute function is written and executed

67

EX NO:11 DATE:

STUDY OF NETWORK SIMULATOR - NS2

AIM: To study the NS2 network simulator. THEORY: 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]

68

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 */ 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

69

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 linked-list 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.

70

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 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 realtime capability in ns is still under development, but is used to introduce an ns simulated network into a real-world topology to experiment with easily-configured 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 1 bit exponent 11 bits
71

mantissa 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: 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.

72

$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 traceobject 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.

73

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

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.

74

DEPT OF I.T PREPARATION PERFORMANCE RECORD TOTAL 30 30 40 100

RESULT: Thus the NS2 network simulator is studied.

75

Vous aimerez peut-être aussi