Vous êtes sur la page 1sur 75

SOCKET PROGRAMMING TCP SOCKETS USING C //TCPServer #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #include<stdio.h> #include<string.h> #include<sys/types.h> #include<arpa/inet.

h> #define PORT 9000 int main(int argc,char *argv[]) { struct sockaddr_in client,server; int newsd,rc,n,clien,sd; char line[100]; sd=socket(AF_INET,SOCK_STREAM,0); server.sin_addr.s_addr=htonl(INADDR_ANY); server.sin_family=AF_INET; server.sin_port=htons(PORT); if((bind(sd,(struct sockaddr *)&server,sizeof(server)))<0) { printf("\nBind error\n"); exit(1); } listen(sd,5);

printf("Waiting for data on port:%u\n",PORT); clien=sizeof(client); newsd=accept(sd,(struct sockaddr *)&client,&clien); memset(line,0x0,100); n=recv(newsd,line,100,0); if(n<0) { printf("\nError during receiving\n"); exit(1); } printf("Received message is:%s\n",line); write(1,line,n); close(sd); exit(0); }

//TCPClient #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #include<stdio.h> #include<unistd.h> #define PORT 9000 #define MAX 100 int main(int argc,char *argv[])

{ struct sockaddr_in server,client,local; struct hostent *h; int sd,n,r; char msg[MAX]; h=gethostbyname(argv[1]); server.sin_family=h->h_addrtype; memcpy((char *)&server.sin_addr.s_addr,h->h_addr_list[0],h->h_length); server.sin_port=htons(PORT); sd=socket(AF_INET,SOCK_STREAM,0); local.sin_family=AF_INET; local.sin_addr.s_addr=htonl(INADDR_ANY); local.sin_port=htons(0); r=bind(sd,(struct sockaddr *)&local,sizeof(server)); if(r>0) { printf("\nbind error"); exit(0); } r=connect(sd,(struct sockaddr *)&server,sizeof(server)); if(r>0) { printf("\nConnect error"); exit(1); }

printf("Enter the message"); fgets(msg,100,stdin); r=send(sd,msg,strlen(msg)+1,0); if(r<0) printf("\nCan't send data"); else printf("\nNo of bytes send:%d",r); close(sd); exit(0); }

OUTPUT

TCPServer [student@localhost s4mca11]$cc tcpserver.c [student@localhost s4mca11]$ ./a.out Waiting for data on port: 9000 Received message is: hai hai

TCPClient [student@localhost s4mca11]$cc tcpclient.c [student@localhost s4mca11]$ ./a.out localhost Enter the message: hai No of bytes send: 6

RESULT The program for TCP sockets using C is done successfully and the output is verified

SOCKET PROGRAMMING UDP SOCKET USING C //UDPServer #include<unistd.h> #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<netdb.h> #include<sys/ipc.h> #include<sys/socket.h> #define PORT 8000 #define MAX 100 int main(int argc,char *argv[]) { int sd,r,n,len; struct sockaddr_in client,remote; char msg[MAX]; sd=socket(AF_INET,SOCK_DGRAM,0); remote.sin_family=AF_INET; remote.sin_addr.s_addr=htonl(INADDR_ANY); remote.sin_port=htons(PORT); setsockopt(sd,SOL_SOCKET,SO_REUSEADDR,0,0); r=bind(sd,(struct sockaddr*)&remote,sizeof(remote)); write(1,"\nServer is running...\n",23); write(1,"\nReceived messages are:\n",24); while(1)

{ memset(msg,0x0,MAX); len=sizeof(client); n=recvfrom(sd,msg,MAX,0,(struct sockaddr*)&client,&len); write(1,msg,10); write(1," ",1); sendto(sd,"Hello client",15,0,(struct sockaddr*)&client,sizeof(client)); write(1,"\n",1); } exit(0); } //UDPClient #include<unistd.h> #include<netinet/in.h> #include<netdb.h> #include<string.h> #define PORT 8000 #define MAX 100 int main(int argc,char *argv[]) { int sd,r,i,n,len; char msg[100]; struct sockaddr_in client,remote; struct hostent *h; write(1,"\nClient is running...\n",23);

sd=socket(AF_INET,SOCK_DGRAM,0); h=gethostbyname(argv[1]); memcpy((char*)&remote.sin_addr.s_addr,h->h_addr_list[0],h->h_length); remote.sin_family=h->h_addrtype; remote.sin_port=htons(PORT); client.sin_addr.s_addr=htonl(INADDR_ANY); client.sin_port=htons(0); client.sin_family=AF_INET; setsockopt(sd,SOL_SOCKET,SO_REUSEADDR,0,0); r=bind(sd,(struct sockaddr*)&client,sizeof(client)); for(i=2;i<argc;i++) sendto(sd,argv[i],strlen(argv[i]),0,(struct sockaddr*)&remote,sizeof(remote)); len=sizeof(remote); n=recvfrom(sd,msg,MAX,0,(struct sockaddr*)&remote,&len); write(1,"\nMessage from server:",25); write(1,msg,n); write(1," ",1); exit(0); }

OUTPUT UDPServer [student@localhost s4mca11]$ cc udpserver.c [student@localhost s4mca11]$ ./a.out Server Is Running..

Received Messages Are: Welcome Hello UDPClient [student@localhost s4mca11]$ cc udpclient.c [student@localhost s4mca11]$ ./a.out localhost Welcome Client Is Running Message from server Hello Client [student@localhost s4mca11]$ ./a.out localhost Hello Client IS Running... Message from server Hello Client

RESULT The program for UDP sockets using C is done successfully and the output is verified

SOCKET APPLICATION- DAYTIME SOCKETS //DAY TIME SERVER #include<stdio.h> #include<stdlib.h> #include<netdb.h> #include<sys/un.h> #include<netinet/in.h> #include<sys/socket.h> #include<sys/types.h> #include<errno.h> #include<time.h> main() { char str[1024],c; int listenfd,connfd,recv_bytes,l,b; struct sockaddr_in saddr,cliaddr; socklen_t clilen; char buf[BUFSIZ]; time_t ticks; listenfd=socket(AF_UNIX,SOCK_STREAM,0); memset(&saddr,0,sizeof(saddr)); saddr.sin_family=AF_UNIX; saddr.sin_addr.s_addr=htonl(INADDR_ANY); saddr.sin_port=htons(5422); printf("\nInitialised");

b=bind(listenfd,(struct sockaddr *)&saddr,sizeof(saddr)); if(b<0) { printf("\nError in binding"); exit(1); } printf("\nbound"); l=listen(listenfd,3); if(l==-1) { printf("\nListened"); exit(1); } printf("\nListening"); clilen=sizeof(cliaddr); if((connfd=accept(listenfd,(struct sockaddr *)&cliaddr,&clilen))==-1) { printf("\Error in Accepting"); exit(0); } printf("\nAccepted"); while(1) { recv_bytes=recv(connfd,str,1024,0); str[recv_bytes]='\0';

if(strcmp(str,"q")==0) break; printf("%s\n",str); fflush(stdout); } close(connfd); return 0; } //DAYTIME CLIENT #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<netdb.h> #include<netinet/in.h> #include<sys/socket.h> #include<errno.h> #include<time.h> main() { char str[1024]; int sockfd,n; time_t t; time(&t); printf("\nDeclared"); struct sockaddr_in saddr;

if((sockfd=socket(AF_UNIX,SOCK_STREAM,0))<0) printf("socket Error"); memset(&saddr,0,sizeof(saddr)); saddr.sin_family=AF_UNIX; saddr.sin_port=htons(5422); printf("\nInitialised"); if(connect(sockfd,(struct sockaddr *)&saddr,sizeof(saddr))<0) { printf("connect error"); exit(1); } printf("\nconnected"); printf("%s",ctime(&t)); strcpy(str,ctime(&t)); while(1) { send(sockfd,str,1024,0); scanf("%s",str); if(strcmp(str,"q")==0) { send(sockfd,str,1024,0); break; }} printf("\nSent"); close(sockfd);}

OUTPUT DayTimeServer [student@localhost s4mca9]$ cc dayserv.c [student@localhost s4mca9]$ ./a.out Initialised bound Listening AcceptedThu Mar 22 10:37:29 2012

DayTimeClient [student@localhost s4mca9]$ cc dayclient.c [student@localhost s4mca9]$ ./a.out Declared Initialised connectedThu Mar 22 10:37:29 2012

RESULT The program for daytime sockets is done successfully and the output is verified

SLIDING WINDOW PROTOCOL //Server #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<string.h> #include<stdlib.h> #include<arpa/inet.h> #include<unistd.h> #define SIZE 4 main() { int id,lfd,i,j,status,n; char str[20],frame[20],temp[20],ack[20]; socklen_t len; struct sockaddr_in server,client; id=socket(AF_INET,SOCK_STREAM,0); if(id<0) perror("Error"); bzero(&server,sizeof(server)); server.sin_family=AF_INET; server.sin_port=htons(8535); server.sin_addr.s_addr=htonl(INADDR_ANY);

if(bind(id,(struct sockaddr *)&server,sizeof(server))<0) perror("bind error\n"); listen(id,5); len=sizeof(&client); lfd=accept(id,(struct sockaddr *)&client,&len); if(lfd<0) { write(1,"accept error",12); _Exit(1); } printf("\nEnter the text:"); scanf("%s",str); i=0; while(i<strlen(str)) { memset(frame,0,20); strncpy(frame,str+i,SIZE); printf("\nTransmitting Frames\n"); n=strlen(frame); for(j=0;j<n;j++) { printf("%d",i+j); sprintf(temp,"%d",i+j); strcat(frame,temp); }

printf("\n"); write(lfd,frame,sizeof(frame)); read(lfd,ack,20); sscanf(ack,"%d",&status); if(status==-1) printf("\nTransmission is successful"); else { printf("Received Error in %d\n\n",status); printf("\n\nRetransmittting frame"); for(j=0;;) { frame[j]=str[j+status]; j++; printf("%d",j+status); if((j+status)%4==0) break; } printf("\n"); frame[j]='\0'; n=strlen(frame); for(j=0;j<n;j++) { sprintf(temp,"%d",j+status); strcat(frame,temp);

} write(lfd,frame,sizeof(frame)); } i+=SIZE; } write(lfd,frame,sizeof("exit")); printf("\nExiting"); sleep(2); close(lfd); close(id); } //Client #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<string.h> #include<unistd.h> #include<stdlib.h> int main() { int c,id,lfd,choice; char str[20],err[20]; struct sockaddr_in server,client; if((id=socket(AF_INET,SOCK_STREAM,0))==-1)

perror("socket error"); bzero(&server,sizeof(server)); server.sin_family=AF_INET; server.sin_port=htons(8535); c=connect(id,(struct sockaddr *)&server,sizeof(server)); for(;;) { read(id,str,20); if(!strcmp(str,"exit")) { printf("\nExiting\n"); break; } printf("\n\nReceived %s \n\n Want to report an error?(1-->y 0-->n)",str); scanf("%d",&choice); if(!choice) write(id,"-1",sizeof("-1")); else { printf("Enter the sequence of frame where errror has occured:"); scanf("%s",err); write(id,err,sizeof(err)); read(id,str,20); printf("\n\nReceived the retransmitted frames %s\n\n",str); } } close(id); return 0; }

OUTPUT SlidingServer [admin@localhost s4mca9]$cc slidingserver.c [admin@localhost s4mca9]$ ./a.out Enter the text:hai Transmitting Frames 012 Transmission is successful Exiting[admin@localhost s4mca9]$ SlidingClient [admin@localhost s4mca9]$ cc slidingclient.c [admin@localhost s4mca9]$ ./a.out

Received hai012 Want to report an error?(1-->y 0-->n)0 Received hai012 Want to report an error?(1-->y 0-->n)

RESULT The program for sliding window protocol is done successfully and the output is verified

ROUTING PROTOCOL #include<stdio.h> int main() { int n,i,j,k,a[10][10],b[10][10]; printf("\nEnter the number of nodes:"); scanf("%d",&n); for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("\nEnter the distance between the host %d%d:",i+1,j+1); scanf("%d",&a[i][j]); } } for(i=0;i<n;i++) { for(j=0;j<n;j++) printf("%d\t",a[i][j]); printf("\n"); } for(k=0;k<n;k++) { for(i=0;i<n;i++) {

for(j=0;j<n;j++) { if(a[i][j]>a[i][k]+a[k][j]) a[i][j]=a[i][k]+a[k][i]; } } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { b[i][j]=a[i][j]; if(i==j) b[i][j]=0; } } printf("\nThe output matrix is:\n"); for(i=0;i<n;i++) { for(j=0;j<n;j++) printf("%d\t",b[i][j]); printf("\n"); } return 0; }

OUTPUT [student@localhost veena]$cc routing.c [student@localhost veena]$ ./a.out Enter the number of nodes:3 Enter the distance between the host 11:5 Enter the distance between the host 12:2 Enter the distance between the host 13:3 Enter the distance between the host 21:4 Enter the distance between the host 22:1 Enter the distance between the host 23:6 Enter the distance between the host 31:2 Enter the distance between the host 32:5 Enter the distance between the host 33:7 5 4 2 2 1 5 3 6 7

The output matrix is: 0 4 2 2 0 5 3 6 0

RESULT The program for routing protocol is done successfully and the output is verified

RPC -USING C //rpctime.x program RPCTIME { version RPCTIMEVERSION { long GETTIME()=1; }=1; }=2000001;

//rpctime_client.c #include "rpctime.h" void rpctime_1(char *host) { CLIENT *clnt; long *result_1,a,b; char *gettime_1_arg; #ifndef DEBUG clnt=clnt_create(host,RPCTIME,RPCTIMEVERSION,"udp"); if(clnt==NULL) { clnt_pcreateerror(host); exit(1); } #endif

result_1=gettime_1((void *)&gettime_1_arg,clnt); if(result_1==(long *)NULL) { clnt_perror(clnt,"call failed"); } else printf("%d |%s",*result_1,ctime(result_1)); printf("Enter two numbers"); scanf("%d%d",&a,&b); result_1=a+b; printf("result is%d",result_1); #ifndef DEBUG clnt_destroy(clnt); #endif } int main(int argc,char *argv[]) { char *host; if(argc<2) { printf("usage:%s s server_host\n",argv[0]); exit(1); } host=argv[1]; rpctime_1(host);

exit(0); } //rpctime_server.c #include "rpctime.h" long *gettime_1_svc(void *argp,struct svc_req *rqstp) { static long result; time(&result); return &result; } //rpctime_cntl.c #include<memory.h> #include "rpctime.h" static struct timeval TIMEOUT={25,0}; long *gettime_1(void *argp,CLIENT *clnt) { static long clnt_res; memset((char *)&clnt_res,0,sizeof(clnt_res)); if(clnt_call(clnt,GETTIME,(xdrproc_t)xdr_void,(caddr_t)argp,(xdrproc_t)xdr_long, (caddr_t)&clnt_res,TIMEOUT)!=RPC_SUCCESS) { return(NULL); } return(&clnt_res); }

//rpctime.h #ifndef_RPCTIME_H_RPCGEN #define_RPCTIME_H_RPCGEN #include<rpc/rpc.h> #ifdef_cplusplus extern"C" { #endif #define RPCTIME 2000001 #define RPCTIMEVERSION 1 #if defined(_STDC_)||defined(_cplusplus) #define GETTIME 1 extern long *gettime_1(void *,CLIENT *); extern long *gettime_1_svc(void *,struct svc_req *); extern int rpctime_1_freeresult(SVCXPRT *,xdrproc_t,caddr_t); #else #define GETTIME 1 extern long *gettime_1(); extern long *gettime_1_svc(); extern int rpctime_1_freeresult(); #endif #ifdef_cplusplus } #endif #endif

//rpctime_cntl #include<memory.h> #include "rpctime.h" static struct timeval TIMEOUT={25,0}; long *gettime_1(void *argp,CLIENT *clnt) { static long clnt_res; memset((char *)&clnt_res,0,sizeof(clnt_res)); if(clnt_call(clnt,GETTIME,(xdrproc_t)xdr_void,(caddr_t)argp,(xdrproc_t)xdr_long, (caddr_t)&clnt_res,TIMEOUT)!=RPC_SUCCESS) { return(NULL); } return(&clnt_res); } //rpctime_svc #include "rpctime.h" #include<stdio.h> #include<stdlib.h> #include<rpc/pmap_clnt.h> #include<string.h> #include<memory.h> #include<sys/socket.h> #include<netinet/in.h> #ifndef SIG_PF

#define SIG_PF void(*)(int) #endif static void rpctime_1(struct svc_req *rqstp,register SVCXPRT *transp) { union { int fill; }argument; char *result; xdrproc_t_xdr_argument,_xdr_result; char *(*local)(char *,struct svc_req *); switch(rqstp->rq_proc) { case NULLPROC: (void)svc_sendreply(trnsp,(xdrproc_t)xdr_void,(char *)NULL); return; case GETTIME: _xdr_argument=(xdrproc_t)xdr_void; _xdr_result=(xdrproc_t)xdr_long; local=(char *)(*)(char *,struct svc_req *))gettime_1_svc; break; default: svcerr_noproc(transp); return; } memset((cahr *)&argument,0,sizeof(argument));

if(!svc_getargs(transp,(xdrproc_t)_xdr_argument,(caddr_t)&argument)) { svcerr_decode(transp); return; } result=(*local)((cahr *)&argument,rqstp); if(result!=NULL && !svc_sendreply(transp,(xdrproc_t)_xdr_result,result)) { svcerr_systemerr(transp); } if(!svc_freeargs(transp,(xdrproc_t)_xdr_argument,(caddre_t)&argument)) { fprintf(stderr,"%s","unable to free arguments"); exit(1); } return; } int main(int argc,cahr **argv) { register SVCXPRT *transp; pmap_unset(RPCTIME,RPCTIMEVERSION); transp=svcudp_create(RPC_ANYSOCK); if(transp==NULL) { fprintf(stderr,"%s","cannot create udp service");

exit(1); if(!svc_register(transp,RPCTIME,RPCTIMEVERSION,rpctime_1,IPPROTO_UDP)) { fprint(stderr,"%s","unable to register(RPCTIME,RPCTIMEVERSION,udp)"); exit(1); } transp=svctcp_create(RPC_ANYSOCK,0,0); if(transp==NULL) { fprintf(stderr,"%s","cannot create tcp service"); exit(1); } if(!svc_register(transp,RCTIME,RPCTIMEVERSION,rpctime_1,IPPROTO_TCP)) { fprintf(stderr,"%s","unable to register(RPCTIME,RPCTIMEVERSION,tcp)"); exit(1); } sbc_run(); fprint(stderr,"%s","svc_run returned"); exit(1); }

OUTPUT

[student@localhost s4mca11]$ rpcgen -C rpctime.x [student@localhost s4mca11]$ cc -c rpctime_client.c -o rpctime_clien.o [student@localhost s4mca11]$ cc -o client rpctime_client.o rpctime_clnt.c -Incl [student@localhost s4mca11]$ cc -c rpctime_server.c -o rpctime_server.o [student@localhost s4mca11]$ cc -o server rpctime_server.o rpctime_svc.c -Incl [student@localhost s4mca11]$ ./server& [4] 9431 [student@localhost s4mca11]$ ./client 127.0.0.1 1332399514 |Thu Mar 22 12:28:34 2012 Enter two numbers:12 24 result is:36

RESULT The program for remote procedure call using C is done successfully and the output is verified

DNS #include<stdio.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<netdb.h> #include<arpa/inet.h> int main(int argc,char *argv[]) { struct addrinfo hints,*res,*p; int status; char ipstr[INET6_ADDRSTRLEN]; if(argc!=2) { fprintf(stderr,"usage:showip hostname\n"); return 1; } memset(&hints,0,sizeof(hints)); hints.ai_family=AF_UNSPEC; hints.ai_socktype=SOCK_STREAM; if((status=getaddrinfo(argv[1],NULL,&hints,&res))!=0) { fprintf(stderr,"getaddrinfo:%s\n",gai_strerror(status)); return 2; }

printf("IP addresses for %s\n\n",argv[1]); for(p=res;p!=NULL;p=p->ai_next) { void *addr; char *ipver; if(p->ai_family==AF_INET) { struct sockaddr_in *ipv4=(struct sockaddr_in *)p->ai_addr; addr=&(ipv4->sin_addr); ipver="IPV4"; } else { struct sockaddr_in6 *ipv6=(struct sockaddr_in6 *)p->ai_addr; addr=&(ipv6->sin6_addr); ipver="IPV6"; } inet_ntop(p->ai_family,addr,ipstr,sizeof(ipstr)); printf("%s%s\n",ipver,ipstr); } freeaddrinfo(res); return 0; }

OUTPUT [student@localhost s4mca11]$ cc dns.c [student@localhost s4mca11]$ ./a.out www.google.com IP addresses for www.google.com: IPv4:173.194.38.144 IPv4:173.194.38.145 IPv4:173.194.38.146 IPv4:173.194.38.147 IPv4:173.194.38.148

RESULT The program for domain name system is done successfully and the output is verified

HTTP SERVER
AIM: To develop an application HTTP SERVER PROCEDURE Step 1: Start telnet application with IP 192.168.2.100 Step2: Login to user named mc. Step3: Create a new file using vi editor with filename like abcd.html Step4: Save the file and quit. Step5: To add the hyper links create another file using the above method. Step6: Save and quit. Step 7: Display the list of files using ls in the prompt. Step 8: In the server the files will be stored in the path: Computer->file system->home->mc Step9:Copy the file and paste it in the location: Computer->file system->var->www->html->mca Step 10: In the client system open Internet Explorer. In the address line type http://192.168.2.100/mca/abcd.html Step 11: The page will be loaded and displayed. Step 12: Click the hyperlink, then the next page will be displayed Step 13: Close the window Step 14: Exit Telnet

HTTP SERVER abcd.html <html> <title>http example</title> <head>HTTP program </head> <body> <h1>Welcome to my web <a href="abcd1.html">Click</a> </body> </html>

abcd1.html <html> <title> http</title> <body> <h1> NARAYANA GURU COLLEGE OF ENGINEERING </h1> </body> </html>

[mc@localhost ~]$ ls abcd1.html Run: abcd.html

RESULT The program for HTTP Server is done successfully and the output is verified

E-MAIL SERVER
AIM To develop E-mail server application PROCEDURE Sending Mail Step1: Start Telnet application with IP 192.168.2.100 Step2: Login to any user Student or Admin Step 3: Using mail , send mail to another user using - $mail<username> Step4: Specify subject and type the message Step 5: Press ctrl+D , then Cc: will be displayed and then press enter . Step 6: Exit Step 7: Stop. Receiving mail Step1: Start Telnet application with IP 192.168.2.100 Step2:Login to any user Student or Admin Step3:To get the mail ,type mail in the prompt Step4: The list of received mail will be displayed with number. Step 5: To view the mail type the respective number like &1 or&2 etc Step 6: The message will be displayed. Step 7: Press ctrl +Z Step 8: Exit

E-MAIL SERVER Sending Mail [admin@localhost ~]$ mail student Subject: hi This is a mail sending from admin to student Cc: [admin@localhost ~]$

Receiving Mail [student@localhost ~]$ mail Mail version 8.1 6/6/93. Type ? for help. "/var/spool/mail/student": 3 messages 3 new >N 1 admin@localhost.loca Tue Apr 10 14:27 19/699 "haiiii" N 2 admin@localhost.loca Tue Apr 10 14:29 17/676 "testtttt" N 3 admin@localhost.loca Tue Apr 10 14:31 16/699 "hi" &3 Message 3: From admin@localhost.localdomain Tue Apr 10 14:31:56 2012 Date: Tue, 10 Apr 2012 14:31:56 +0530 From: admin <admin@localhost.localdomain> To: student@localhost.localdomain Subject: hi

This is a mail sending from admin to student &

RESULT The program for email server is done successfully and the output is verified

CHAT APPLICATION #include<sys/socket.h> #include<netinet/in.h> #include<stdio.h> #define SERV_TCP_PORT 3500 int main(int argc,char *argv[]) { int sockfd,new,clen; struct sockaddr_in,serv_add,cli_add; char buffer[4096]; sockfd=socket(AF_INET,SOCK_STREAM,0); serv_add.sin_family=AF_INET; serv_add.sin_addr.s_addr=INADDR_ANY; serv_add.sin_port=htons(SERV_TCP_PORT); bind(sockfd,(struct sockaddr*)&serv_add,sizeof(serv_add)); listen(sockfd,5); clen=sizeof(cli_add); new=accept(sockfd,(struct sockaddr*)&cli_add,&clen); do { bzero(buffer,4096); read(new,buffer,4096); printf("\nClient:%s"); bzero(buffer,4096); printf("server:");

fgets(buffer,4096,stdin); write(new,buffer,4096); } while(strcmp(buffer,"bye\n")!=0); close(sockfd); return 0; } //Chat client #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #define SERV_TCP_PORT 3500 int main(int argc,char *argv[]) { int sockfd; struct sockaddr_in,serv_add; struct hostent *server; char buffer[4096]; sockfd=socket(AF_INET,SOCK_STREAM,0); serv_add.sin_family=AF_INET; serv_add.sin_addr.s_addr=inet_addr("127.0.0.1"); serv_add.sin_port=htons(SERV_TCP_PORT); connect(sockfd,(struct sockaddr*)&serv_add,sizeof(serv_add)); do

{ bzero(buffer,4096); printf("\nClient:%s"); fgets(buffer,4096,stdin); write(sockfd,buffer,4096); bzero(buffer,4096); read(sockfd,buffer,4096); printf("server:%s",buffer); fgets(buffer,4096,stdin); } while(strcmp(buffer,"bye\n")!=0); close(sockfd); return 0; }

OUTPUT chatserver.c [student@localhost s4mca11]$ cc chatserver.c [student@localhost s4mca11]$ ./a.out Client:hai Server:hello Client:how are you Server:fine Client:bye Server:bye chatclient.c [student@localhost s4mca11]$ cc chatclient.c [student@localhost s4mca11]$ ./a.out Client:hai server:hello Client:how are you server:fine Client:bye server:bye

RESULT The program for chat application is done successfully and the output is verified

SOCKET PROGRAMMING- TCP SOCKETS USING JAVA //TCPServer import java.io.*; import java.net.*; class TCPServer { public static void main(String arg[])throws IOException { String fromclient; String toclient; ServerSocket server=new ServerSocket(9001); System.out.println("\nTen server waiting for client on port 9001"); while(true) { Socket connected=server.accept(); System.out.println("\nThe client +":"+connected.getPort()+"is connected"); "+" "+connected.getInetAddress()

BufferedReader infromuser=new BufferedReader(new InputStreamReader(System.in)); BufferedReader infromclient=new InputStreamReader(connected.getInputStream())); BufferedReader(new

PrintWriter outtoclient=new PrintWriter(connected.getOutputStream(),true); while(true) { System.out.println("\nSEND type Q or q to quit"); toclient=infromuser.readLine(); if(toclient.equals("q")||toclient.equals("Q"))

{ outtoclient.println(toclient); connected.close(); break; } else { outtoclient.println(toclient); } fromclient=infromuser.readLine(); if(fromclient.equals("q")||fromclient.equals("Q")) { connected.close(); break; } else { System.out.println("\nRECEIVED:"+fromclient); } } } } }

//TCPClient import java.io.*; import java.net.*; class TCPClient { public static void main(String arg[])throws IOException { String fromserver; String toserver; Socket clientsocket=new Socket("localhost",9001); BufferedReader infromuser=new BufferedReader(new InputStreamReader(System.in)); PrintWriter outtoserver=new PrintWriter(clientsocket.getOutputStream(),true); BufferedReader infromserver=new InputStreamReader(clientsocket.getInputStream())); while(true) { fromserver=infromserver.readLine(); if(fromserver.equals("q")||fromserver.equals("Q")) { clientsocket.close(); break; } else { System.out.println("\nRECEIVED:"+fromserver); BufferedReader(new

System.out.println("\nSEND(type Q or q to quit)"); toserver=infromuser.readLine(); if(toserver.equals("Q")|| toserver.equals("q")) { outtoserver.println(toserver); clientsocket.close(); break; } else { outtoserver.println(toserver); } } } }}

OUTPUT F:\ geethu >javac TCPServer.java F:\ geethu >java TCPServer Ten server waiting for client on port 9001 The client localhost/127.0.0.1:1047is connected SEND type Q or q to quit Hai F:\ geethu >javac TCPClient.java F:\ geethu >java TCPClient RECEIVED:hai SEND(type Q or q to quit) Q

RESULT The program for tcp sockets using java is done successfully and the output is verified

SOCKET PROGRAMMING UDP SOCKET USING JAVA //UDPServer import java.io.*; import java.net.*; class Udpserver { public static void main(String args[])throws Exception { byte[] receive_data=new byte[1024]; byte[] send_data=new byte[1024]; int recv_port; DatagramSocket server_socket=new DatagramSocket(3008); System.out.println("\nUDP Server waiting for client on port 3000"); while(true) { DatagramPacket receive_packet=new DatagramPacket(receive_data,receive_data.length); server_socket.receive(receive_packet); String data=new String(receive_packet.getData(),0,receive_packet.getLength()); InetAddress IPAddress=receive_packet.getAddress(); recv_port=receive_packet.getPort(); if(data.equals("Q") || data.equals("q")) break; else System.out.println("IPAddress)"+recv_port+"said: "+data); } }}

//UDPClient import java.io.*; import java.net.*; class Udpclient { public static void main(String args[])throws Exception { byte[] send_data=new byte[1024]; BufferedReader infrmuser=new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientsocket=new DatagramSocket(1070); InetAddress IPAddress=InetAddress.getByName("127.0.0.1"); while(true) { System.out.println("Type something(q or Q to Quit)"); String data=infrmuser.readLine(); if(data.equals("q") || data.equals("Q")) break; else { send_data=data.getBytes(); send_packet=new

DatagramPacket DatagramPacket(send_data,send_data.length,IPAddress,3008); clientsocket.send(send_packet); } }clientsocket.close(); } }

OUTPUT F:\ geethu >javac Udpserver.java F:\ geethu >java Udpserver UDP Server waiting for client on port 3000 IPAddress)1070said: hello F:\ geethu >javac Udpclient.java F:\ geethu >java Udpclient Type something(q or Q to Quit) hello Type something(q or Q to Quit) q

RESULT The program for udp sockets using java is done successfully and the output is verified

ECHO SERVER //Echo Server import java.net.*; import java.io.*; import java.lang.*; public class EchoServer { public static void main(String args[])throws Exception { byte[] str=new byte[1024]; DatagramSocket ds=new DatagramSocket(5000); System.out.println(Server waiting for client on port 5000); DatagramPacket dp=new DatagramPacket(str,str.length); ds.receive(dp); String s=new String(dp.getdata(),0,dp.getLength()); System.out.println(Message:+s); ds.close(); DatagramSocket ds1=new DatagramSocket(); InetAddress ia1=InetAddress.getLocalHost(); byte[] str1=new byte[1024]; String echomsg=s; str1=echomsg.getBytes(); DatagramPacket dp1=new DataGramPacket(str1,str1.length,ia1,5001); ds1.send(dp1); }}

//EchoClient import java.net.*; import java.io.*; import java.lang.*; public class EchoClient { Public static void main(String args[])throws Exception { DatagramSocket ds=new DatagramSocket(); InetAddress i1-InetAddress.getLocalHost(); byte[] str=new byte[1024]; byte[] str1=new byte[1024]; String messagesend=new String(args[0]); str=messagesends.getBytes(); DatagramPacket dp=new DatagramPacket(str,str.length,ia,5000); ds.send(dp); ds.close(); DatagramSocket ds1=new DatagramSocket(5001); DatagramPacket dp1=new DatagramPacket(str1,str.length); ds1.receive(dp1) String s1=new String(dp1.getData(),0,dp1.getLength()); System.out.println(Message returned:+s1.trim()); } }

OUTPUT EchoServer E:\ geethu >javac echoserver.java E:\ geethu >java echoserver Server waiting for client on port 5000 Message:Hello EchoClient E:\ geethu >javac echoclient.java E:\ geethu >java echoclient Hello Friends Message returned:Hello

RESULT The program for echo server is done successfully and the output is verifed

RPC //rmiimpl import java.rmi.*; import java.io.*; import java.rmi.server.UnicastRemoteObject; public class rmiimpl extends UnicastRemoteObject implements rmiintf { public rmiimpl()throws RemoteException {} public int add(int a,int b)throws RemoteException { return a+b; } } //rmiintf import java.rmi.*; public interface rmiintf extends Remote { int add(int a,int b) throws RemoteException; } //rmiserver import java.rmi.*; import java.net.*; public class rmiserver {

public static void main(String args[])throws Exception { rmiimpl rm=new rmiimpl(); Naming.rebind("addserver",rm); } } //rmiclient import java.rmi.*; import java.io.*; public class rmiclient { public static void main(String args[])throws Exception { String addserverurl="addserver"; rmiintf addserverintf=(rmiintf)Naming.lookup(addserverurl); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("\nEnter the first number:"); int i1=Integer.parseInt(br.readLine()); BufferedReader br1=new BufferedReader(new InputStreamReader(System.in)); System.out.println("\nEnter the second number:"); int i2=Integer.parseInt(br1.readLine()); System.out.println("\nFirst number:"+i1); System.out.println("\nSecond number:"+i2); System.out.println("\nSum ="+addserverintf.add(i1,i2)); }}

OUTPUT F:\geethu>javac rmiserver.java F:\ geethu >java rmiserver F:\ geethu >javac rmiimpl.java F:\ geethu >javac rmiintf.java F:\ geethu >javac rmiclient.java F:\ geethu >rmic rmiimpl F:\ geethu >start rmiregistry F:\ geethu >java rmiclient Enter the first number: 10 Enter the second number: 25 First number:10 Second number:25 Sum =35 F:\geethu>javac rmiserver.java F:\geethu>java rmiserver

RESULT The program for remote procedure call using java is done successfully and the output is verified

SLIDING WINDOW PROTOCOL import java.io.*; import java.net.*; class sliding { int pak,winsize,pn; public sliding() throws Exception { DataInputStream ds = new DataInputStream(System.in); System.out.println("Enter the windowsize"); winsize = Integer.parseInt(ds.readLine()); System.out.println("Enter the total no of packets"); pak= Integer.parseInt(ds.readLine()); if(pak<winsize) { System.out.println("Windowsize is greater than packet"); System.exit(0); } System.out.println("Do you want to kill any packet(Y/N)"); String k = ds.readLine(); if(k.equals("y")) { System.out.println("Enter the packet number to kill"); pn=Integer.parseInt(ds.readLine()); }

} public void Selrepeat(int p) { System.out.println("Selective repeat of packet " + pn); System.out.println("Packet" + pn + "send"); System.out.println("Packet" + pn + "received"); System.out.println("Acknowledgement " + pn + "Received"); } public void trans()throws Exception { int dis = 0 , dis1= 0; for(int i = 1; i<= pak; i++) { for(int j=1;j<=winsize && i<=pak; j++, i++) { if(i == pn) { dis =1; System.out.println("Packet" + pn + "Discarded"); System.out.println("Remaining packet to be send in this section is " + (winsize -j)); if(j==winsize) dis1=1; Thread.sleep(2000); } else

{ System.out.println("Packet" +i + "set"); System.out.println("Packet" + i + "Receiver"); System.out.println("Acknowledgement " + i + "Received"); if(dis1 == 1) { dis1=0; continue; } if(dis == 1) { Selrepeat(pn); dis = 0; } } } } } public static void main(String args[])throws Exception { sliding s=new sliding(); s.trans(); } }

OUTPUT F:\geethu>javac sliding.java F:\geethu>java sliding Enter the windowsize : 2 Enter the total no of packets: 7 Do you want to kill any packet(Y/N): y Enter the packet number to kill : 1 Packet1Discarded Remaining packet to be send in this section is 1 Packet2set Packet2Receiver Acknowledgement 2Received Selective repeat of packet 1 Packet1send Packet1received Acknowledgement 1Received Packet4set Packet4Receiver Acknowledgement 4Received Packet5set Packet5Receiver Acknowledgement 5Received Packet7set Packet7Receiver Acknowledgement 7Received

RESULT The program using sliding window protocol is done successfully and the output is verified

MULTI USER CHAT SERVER #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> main() { int i,sd,sd2,nsd,clilen,sport,len; char sendmsg[20],rcvmsg[20]; struct sockaddr_in servaddr,cliaddr; printf(Enter the port no:\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 printf("\n Binded\n"); listen(sd,5); do { printf("Enter the client no to communicate\n"); scanf("%d",&i); if(i==0) exit(0); printf("Client %d is connected\n",i); clilen=sizeof(cliaddr); nsd=accept(sd,(struct sockaddr*)&cliaddr,&clilen); if(nsd<0) printf("Can't Accept\n"); else printf("Accepted\n"); do { recv(nsd,rcvmsg,20,0);

printf("%s",rcvmsg); fgets(sendmsg,20,stdin); len=strlen(sendmsg); sendmsg[len-1]='\0'; send(nsd,sendmsg,20,0); wait(20); }while(strcmp(sendmsg,"bye")!=0); }while(i!=0); } CLIENT - 1 #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> main() { int csd,cport,len; char sendmsg[20],revmsg[20]; struct sockaddr_in servaddr; printf("Enter the port no:\n"); scanf("%d",&cport); csd=socket(AF_INET,SOCK_STREAM,0); if(csd<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(cport); if(connect(csd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) printf("Can't Connect\n"); else printf("Connected\n"); do { fgets(sendmsg,20,stdin); len=strlen(sendmsg); sendmsg[len-1]='\0'; send(csd,sendmsg,20,0); wait(20); recv(csd,revmsg,20,0); printf("%s",revmsg); }

while(strcmp(revmsg,"bye")!=0); } CLIENT - 2 #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> main() { int csd,cport,len; char sendmsg[20],revmsg[20]; struct sockaddr_in servaddr; printf("Enter the port no:\n"); scanf("%d",&cport); csd=socket(AF_INET,SOCK_STREAM,0); if(csd<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(cport); if(connect(csd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) printf("Can't Connect\n"); else printf("Connected\n"); do { fgets(sendmsg,20,stdin); len=strlen(sendmsg); sendmsg[len-1]='\0'; send(csd,sendmsg,20,0); wait(20); recv(csd,revmsg,20,0); printf("%s",revmsg); } while(strcmp(revmsg,"bye")!=0); }

OUTPUT SERVER SIDE: [1me2@localhost ~]$ vi Multiuserserver.c [1me2@localhost ~]$ cc Multiuserserverc [1me2@localhost ~]$ ./a.out Enter the port no 8543 socket is created Binded Enter the client to communicate: 1 Client 1 is connected Accepted hiiiii Byeeeeee Enter the client no to communicate: 2 client 2 is connected Accepted hiiiiiiiiii hello Enter the client no to communicate: 0 CLIENT SIDE 1: [1me2@localhost ~]$ vi multiuserclient1.c [1me2@localhost ~]$ cc multiuserclient1.c [1me2@localhost ~]$ ./a.out Enter the port no 8543 Socket is created Connected hiiiiii Byeeeee CLIENT SIDE 2: [1me2@localhost ~]$ vi multiuserclient2.c [1me2@localhost ~]$ cc multiuserclient2.c [1me2@localhost ~]$ ./a.out Enter the port no 8543 Socket is created Connected Hiiiiiiiii hello

RESULT The program for multi user chat is done successfully and the output is verified

SIMULATION OF SIMPLE NETWORK MANAGEMENT PROTOCOLS AGENT1 #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> main() { int i,sd,sd2,nsd,clilen,sport,len; char sendmsg[20],recvmsg[100]; char oid[5][10]={"client1","client2","client3","cleint4","client5"}; char wsize[5][5]={"5","10","15","3","6"}; struct sockaddr_in servaddr,cliaddr; printf("I'm the Agent - TCP Connection\n"); printf("\nEnter 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 printf("\n Binded\n"); listen(sd,5); clilen=sizeof(cliaddr); nsd=accept(sd,(struct sockaddr*)&cliaddr,&clilen); if(nsd<0) printf("Can't Accept\n"); else printf("Accepted\n"); recv(nsd,recvmsg,100,0); for (i=0;i<5;i++) { if(strcmp(recvmsg,oid[i])==0) { send(nsd,wsize[i],100,0); break;

}}} AGENT 2 #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> #include<string.h> main() { int i,sd,sd2,nsd,clilen,sport,len; char sendmsg[20],recvmsg[100]; char oid[5][10]={"System1","System2","System3","System4","System5"}; char mdate[5][15]={"1-10-095","10-03-08","14.03.81","11.07.07","17.12.77"}; char time[5][15]={"9am","10pm","11am","12.30pm","11.30am"}; 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 printf("\n Binded\n"); listen(sd,5); clilen=sizeof(cliaddr); nsd=accept(sd,(struct sockaddr*)&cliaddr,&clilen); if(nsd<0) printf("Can't Accept\n"); else printf("Accepted\n"); recv(nsd,recvmsg,100,0); for(i=0;i<5;i++) { if(strcmp(recvmsg,oid[i])==0) { send(nsd,mdate[i],100,0); send(nsd,time[i],100,0); break; }}}

MANAGER #include<stdio.h> #include<sys/types.h> #include<netinet/in.h> main() { int csd,cport,len,i; char sendmsg[20],rcvmsg[100],rmsg[100],oid[100]; struct sockaddr_in servaddr; printf("Enter the port\n"); scanf("%d",&cport); csd=socket(AF_INET,SOCK_STREAM,0); if(csd<0) printf("Can't Create\n"); else printf("Scocket is Created\n"); servaddr.sin_family=AF_INET; servaddr.sin_addr.s_addr=htonl(INADDR_ANY); servaddr.sin_port=htons(cport); if(connect(csd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) printf("Can't Connect\n"); else printf("Connected\n"); printf("\n 1.TCP Connection\n"); printf("\n 2. System \n"); printf("Enter the number for the type of informtion needed....\n"); scanf("%d",&i); if(i==1) { printf("Enter the Object ID for Client\n"); scanf("%s",oid); send(csd,oid,100,0); recv(csd,rmsg,100,0); printf("\n The window size of %s is %s",oid,rmsg); } else { printf("\nEnter the Object ID for the System\n"); scanf("%s",oid); send(csd,oid,100,0); recv(csd,rmsg,100,0); printf("\nThe Manufacturing date for %s is %s",oid,rmsg); recv(csd,rmsg,100,0); printf("\nThe time of Last Utilization for %s is %s",oid,rmsg); }}

OUTPUT AGENT1: [1me14@localhost ~]$ vi Agent1.c [1me14@localhost ~]$ cc Agent1.c [1me14@localhost ~]$ ./a.out I'm the Agent - TCP Connection Enter the Server port _____________________ 8543 Socket is created Binded Accepted MANGER: [1me14@localhost ~]$ vi Manager.c [1me14@localhost ~]$ cc Manger.c [1me14@localhost ~]$ ./a.out Enter the port 8543 Socket is Created Connected 1.TCP Connection 2. System Enter the number for the type of information needed: 1 Enter the Object ID for Client: Client1 The window size of client1 is 5 AGENT2: [1me14@localhost ~]$ vi Agent2.c [1me14@localhost ~]$ cc Agent2.c [1me14@localhost ~]$ ./a.out Enter the Server port _____________________ 8543 Socket is Created Binded Accepted

RESULT

The program for simulation of network management protocols is done successfully and the output is verified

Vous aimerez peut-être aussi