Calculator Program in C using TCP

Saurabh Kushwah
Nov 1 · 3 min read

Basic demonstration of socket programming where client send an expression s ( 9 * 9 ) and the server returns the result.

Implementation in C

Server.c

// Server.c
#include <stdlib.h> // for basic memmory allocation and deallocation
#include <stdio.h> // for file read and write
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>

#define MAX 100
#define PORT 8080
#define SA struct sockaddr



void doCalculation(int sockfd)
{
char buff[MAX]; // to store message from client
int n; // for traversing buffer buff

float a , b , result ;
char ch ;


// infinite loop for chat
for (;;) {

result = 0.00 ;
a = 0 ;
b = 0 ;
bzero(buff, MAX); // empties the buffer

// read the message from client and copy it in buffer
if ( read(sockfd, buff, sizeof(buff) ) == 0 ){

printf(" --- Failed To Read \n --- Maybe Socket Is Closed .. \n -- Exiting \n ");
return;

}

if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}

sscanf( buff , "%f%c%f" , &a, &ch, &b );

printf("\n\n Operation Requested is %f %c %f \n",a,ch,b);



switch( ch ){

case '+' : result = a + b ;
break ;
case '-' : result = a - b ;
break ;
case '*' : result = a * b ;
break ;
case '/' : result = a / b ;
break ;
default : write( sockfd , "Invalid Token. " , sizeof("Invalid Token. ") );

}

write(sockfd,&result,sizeof(result));

}



}


int main()
{
int sockfd, connfd, len; // create socket file descriptor
struct sockaddr_in servaddr, cli; // create structure object of sockaddr_in for client and server

// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0); // creating a TCP socket ( SOCK_STREAM )

if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");

// empty the
bzero(&servaddr, sizeof(servaddr));

// assign IP, PORT
servaddr.sin_family = AF_INET; // specifies address family with IPv4 Protocol
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); // binds to any address
servaddr.sin_port = htons(PORT); // binds to PORT specified

// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");

// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");

len = sizeof(cli);

// Accept the data packet from client and verification
connfd = accept(sockfd, (SA*)&cli, &len); // accepts connection from socket

if (connfd < 0) {
printf("server acccept failed...\n");
exit(0);
}
else
printf("server acccept the client...\n");

// Function for recieving Expression and
doCalculation(connfd);

// After transfer close the socket
close(sockfd);
}

Client.c

// Write CPP code here 
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>

#define MAX 100
#define PORT 8080
#define SA struct sockaddr

void sendCalculation(int sockfd)
{
char buff[MAX]; // to store expression from client
for( ;; ){
bzero(buff,MAX); // empty the buffer

printf("\n\nEnter Expression ( exit ) : ");
scanf("%s",buff);
write(sockfd , buff , sizeof(buff) ); // write to the stream
if(strncmp("exit",buff,4) == 0 ){

printf("Exiting ...\n");
return ;

}
bzero(buff,MAX);
read(sockfd,buff,sizeof(buff));
printf("Operation Result : %f",*((float*)buff)); // convert char ptr to float ptr then to float
}
}

int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;

// socket create and varification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");

bzero(&servaddr, sizeof(servaddr));

// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);

// connect the client socket to server socket
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");

// function for sending Expression
sendCalculation(sockfd);

// close the socket
close(sockfd);
}

Source Code

https://github.com/saurabh-kushwah/Practicals/tree/master/Computer%20Networks/Socket%20Programming%20in%20C/TCP%20-%20Calculator

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade