An iterative client server program

Submitted on Sat, 06/12/2021 - 10:42
#Server

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc,char *argv[]){
int server_socket=socket(AF_INET,SOCK_STREAM,0);
int conn;
char str[1024];
char istr[1024];
int port=atoi(argv[2]);
struct sockaddr_in srv_addr,c_addr;
memset(&srv_addr,0,sizeof(srv_addr));
srv_addr.sin_family=AF_INET;
srv_addr.sin_port=htons(port);
inet_aton(argv[1],&srv_addr.sin_addr);
int ibind=bind(server_socket,(struct sockaddr*)&srv_addr,sizeof(srv_addr));
if(ibind==-1){
printf("Server binding could not occur.\n");exit(1);
}
else if(ibind==0){
printf("Server binding successful.\n");
}
if(listen(server_socket,10)==0){
printf("server listening for connection:\n");
}
for(;;){
socklen_t clen=sizeof(c_addr);
int csocket=accept(server_socket,(struct sockaddr*)NULL,NULL);

int cpeer=getpeername(csocket,(struct sockaddr*)&c_addr,&clen);
recv(csocket,str,1024,0);


while(str[0]!=10){
printf("\nclient at ");
printf("%s:",inet_ntoa(c_addr.sin_addr));
printf("%d-",ntohs(c_addr.sin_port));
printf(" %s",str);
printf("Server: ");
fgets(istr,1024,stdin);
send(csocket,istr,1024,0);
recv(csocket,str,1024,0);
}
printf("\nclient closed connection with blank message.\n");
char istr[1024]="\n";
send(csocket,istr,1024,0);
close(csocket);
}
close(server_socket);
return 0;
}

 

#Client

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
int main(int argc,char *argv[]){
int client_socket = socket(AF_INET,SOCK_STREAM,0);
int port=atoi(argv[2]);
struct sockaddr_in serv_addr;
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(port);
inet_aton(argv[1],&serv_addr.sin_addr);
int con_status=connect(client_socket,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
if(con_status==-1){
printf("error in connection to server\n");
exit(1);
}
else if(con_status==0){
printf("connection with server established.\n");
}
char str[1024];
char istr[1024];
while(1){
printf("\nClient: ");
fgets(istr,1024,stdin);
send(client_socket,istr,1024,0);
recv(client_socket,str,1024,0);
if(str[0]==10) {
printf("\nconnection closed\n");
close(client_socket);
exit(1);
}
printf("\nServer; %s",str);
}
return 0;
}