Skip to content

Instantly share code, notes, and snippets.

@coder3101
Created December 20, 2018 13:50
Show Gist options
  • Save coder3101/9d15f8d1870599294314e6d99be23665 to your computer and use it in GitHub Desktop.
Save coder3101/9d15f8d1870599294314e6d99be23665 to your computer and use it in GitHub Desktop.
This is a simple Remote Procedural Calling (RPC) Server. When Executed it listens for client and computes the factorial of the number requested by the client. For Client Code See rpc-client.c gist
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 12345 //Our Server will listen on this port
// This is a function that will be executed and the parameter will be recieved from client.
unsigned long int factorial(int a){
if(a <= 1) return 1;
else return factorial(a-1)*a;
}
// It converts client request into integer.
unsigned long int remote_function(char* buffer){
int a = atoi(buffer);
return factorial(a);
}
int main() {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
printf("Socket Created\n");
// Forcefully attaching socket to the port
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt))){
perror("setsockopt");
exit(EXIT_FAILURE);
}
printf("Socket Attached\n");
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY; //listen on all active interfaces
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 10000
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0){
perror("bind failed");
exit(EXIT_FAILURE);
}
printf("Socket is listening on all interface on port %d\n",PORT);
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
printf("Serving Client : %d\n",new_socket);
const char* info = "SERVER :: You are connected to computer\nSERVER :: Send your number whose factorial is expected ? \n";
send(new_socket, info, strlen(info), 0);
valread = read(new_socket , buffer, 1024);
printf("Client Requested factorial of : %s\n",buffer);
printf("Computing factorial of : %s",buffer);
//Executing the remote function.
char result[21];
sprintf(result, "%lu", remote_function(buffer));
printf("\nReturning to client : %s\n",result);
send(new_socket, result, strlen(result), 0);
close(new_socket);
printf("Closing connection from client\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment