Code for Client server Application in c
54Mathematical Operation performing on Server and sending back result back to client—
Client side----
math.c---
#include stdio.h
#include sys/types.h
#include sys/socket.h
#include unistd.h
#include netinet/in.h
#include arpa/inet.h
int main()
{
int s1,s2,size,calc;
struct sockaddr_in server,client;
char msg1[100];
s1 = socket(AF_INET,SOCK_STREAM,0);
printf("Waiting for client.....");
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port=htons(3901);
int status = bind(s1,(struct sockaddr *)&server,sizeof(server));
if(status>0)
printf("\n port is already bind");
listen(s1,5);
size = sizeof(client);
s2 = accept(s1,(struct sockaddr *)&client,&size);
printf("\n connected to server \n");
struct math
{
int no1;
int no2;
char ch;
}m1;
recv(s2,&m1,sizeof(m1),0);
switch(m1.ch)
{
case '+':
calc=m1.no1+m1.no2;
break;
case '*':
calc=m1.no1*m1.no2;
break;
case '/':
calc=m1.no1/m1.no2;
break;
case '-':
calc=m1.no1-m1.no2;
break;
}
send(s2,&calc,sizeof(calc),0);
close(s1);
close(s2);
}
Server side---
mathc.c---
#include stdio.h
#include unistd.h
#include sys/types.h
#include sys/socket.h
#include netinet/in.h
#include arpa/inet.h
int main()
{
int s2,calc;
struct sockaddr_in server;
char msg[100];
s2 =socket(AF_INET,SOCK_STREAM,0);
server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=htons(3901);
connect(s2,(struct sockaddr*)&server,sizeof(server));
struct math
{
int no1;
int no2;
char ch;
}m1;
printf("Enter equation:");
scanf("%d %c %d",&m1.no1,&m1.ch,&m1.no2);
send(s2,&m1,sizeof(m1),0);
recv(s2,&calc,sizeof(calc),0);
printf("answer = %d",calc);
close(s2);
}
PrintShare it! — Rate it: up down flag this hub








