THIS PROGRAM FOR SINGLE SERVER-MULTI CLIENT IN SAME NETWORK.IF YOU WANT TO MAKE THIS CODE FOR DIFFERENT SYSTEM THEN YOU NEED TO CHANGE IP ADDRESS OF ACCORDING TO SERVER'S IP ADDRESS
SERVER PROGRAM
CLIENT PROGRAM
/********************************************************************************/
/* Title :: Client Socket Programm */
/* */
/* This is CLIENT program */
/* */
/* Auther : Kaneria Dhaval */
/* */
/* Usage : ~$ gcc -w -o client client.c */
/* ./client */
/* */
/********************************************************************************/
SERVER PROGRAM
#include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<stdlib.h> #include<stdio.h> #include<string.h> int main() { int sockfd,confd,n,clilen; char buff[256]; struct sockaddr_in server, client; sockfd =socket(AF_INET,SOCK_STREAM,0); printf("Socket OK.\n"); server.sin_family = AF_INET; server.sin_port = htons(9000); server.sin_addr.s_addr = inet_addr("127.0.0.1"); bind(sockfd,(struct sockaddr*)&server,sizeof(server)); printf("Bind OK.\n"); listen(sockfd,4); printf("Listening OK.\n\n"); clilen=sizeof(client); //confd=accept(sockfd,(struct sockaddr*)&client,&clilen); //printf("Accept OK.\n"); while(1) { confd=accept(sockfd,(struct sockaddr*)&client,&clilen); printf("Accept OK.\n"); printf("Waiting for Client's Message.\n"); bzero(buff,256); n = read(confd,buff,256); if(buff[0]=='q') { close(confd); break; } printf("CLIENT : %s",buff); n = write(confd,"Message Received.",17); } close(sockfd); }
CLIENT PROGRAM
/********************************************************************************/
/* Title :: Client Socket Programm */
/* */
/* This is CLIENT program */
/* */
/* Auther : Kaneria Dhaval */
/* */
/* Usage : ~$ gcc -w -o client client.c */
/* ./client */
/* */
/********************************************************************************/
#include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<stdlib.h> #include<stdio.h> #include<string.h> int main(){ int sockfd,confd,n,len; char buff[256]; struct sockaddr_in server,client; len = sizeof(struct sockaddr_in); sockfd = socket(AF_INET, SOCK_STREAM, 0); printf("Socket OK.\n"); server.sin_family = AF_INET; server.sin_port = htons(9000); server.sin_addr.s_addr = inet_addr("127.0.0.1"); confd=connect(sockfd,(struct sockaddr*)&server,sizeof(server)); printf("Connection OK.\n"); while(1) { printf("\nMessage : "); fgets(buff,256,stdin); n=write(sockfd,buff,strlen(buff)); printf("> Message Sent.\n"); if(buff[0]=='q') { close(confd); break; } bzero(buff,sizeof(buff));n=read(sockfd,buff,sizeof(buff)); printf("Server : %s",buff); } close(sockfd); return 0; }
No comments:
Post a Comment