Client Server Program in C | CodeTextPro - CodeTextPro | Free Web Tutorial

Codetextpro Provides free Web tutorial, HTML, CSS, C, C++, Java, JavaScript, PHP, MySql, Python, Program, Programming Notes, Programming Questions and more.

Programming

Wednesday, January 16, 2019

Client Server Program in C | CodeTextPro

Client-Server Program


In this program, you will learn how to chat client to the server.

How to run client server program in c

client.c


#include<stdio.h>
#include<errno.h>
#include<sys/socket.h>
#include<resolv.h>

#include<errno.h>

#include<stdlib.h>
#include<string.h>
#include<stdarg.h>
#define MAXBUF  1024

int main(int count,char *strings[])

{
 int sockfd,bytes_read;
 struct sockaddr_in dest;
 char buffer[MAXBUF];
 if(count<3 || count>4)
{
  fprintf(stderr,"usage:%s<IP_addr><port>[<send_msg>]\n",strings[0]);
 exit(0);
}
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
exit(errno);
}
 bzero(&dest,sizeof(dest));
 dest.sin_family=AF_INET;
if(inet_aton(strings[1],&dest.sin_addr)==0)
{
perror(strings[1]);
exit(errno);
}
dest.sin_port=htons(atoi(strings[2]));
if(connect(sockfd,(struct sockaddr*)&dest,sizeof(dest))!=0)
{
perror("connect");
exit(errno);
}
if(count==4)
{
sprintf(buffer,"%s\n",strings[3]);
send(sockfd,buffer,strlen(buffer),0);
}
do
{
bzero(buffer,MAXBUF);
bytes_read=recv(sockfd,buffer,MAXBUF,0);
if(bytes_read>0)
printf("%s",buffer);
}
while(bytes_read>0);
close(sockfd);
return 0;
}



server.c


#include<stdio.h>
#include<errno.h>
#include<sys/socket.h>
#include<resolv.h>
#include<arpa/inet.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
#define MY_PORT 9999
#define MAXBUF  1024

int main(int count,char *strings[])

{
  int sockfd;
  struct sockaddr_in self;
  char buffer[MAXBUF];

if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)

{
perror("socket");
exit(errno);
}
   bzero(&self,sizeof(self));
   self.sin_family=AF_INET;
   self.sin_port=htons(MY_PORT);
   self.sin_addr.s_addr=INADDR_ANY;

if(bind(sockfd,(struct sockaddr*)&self,sizeof(self))!=0)

{
  perror("socket--bind");
  exit(errno);
 }
printf("bind success");
if(listen(sockfd,20)!=0)
{
perror("listen");
exit(errno);
}
while(1)
{
int clientfd;
struct sockaddr_in client_addr;
int addrlen=sizeof(client_addr);
clientfd=accept(sockfd,(struct sockaddr*)&client_addr,&addrlen);
printf("%s:%d coonected",inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));
send(clientfd,buffer,recv(clientfd,buffer,MAXBUF,0),0);
close(clientfd);
}
close(sockfd);
return 0;

}


No comments:

Post a Comment