#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define ERR(a) fprintf(stderr, "Error: %s\n", a)
uint32_t fib(uint32_t n)
{
if (n <= 2)
return 1;
else
return fib(n-1) + fib(n-2);
}
int main()
{
int server;
struct addrinfo hints, *info;
int client;
struct sockaddr_in client_addr;
socklen_t addr_size;
uint32_t n, fib_n;
memset((void *) &hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, "4000", &hints, &info);
server = socket(info->ai_family, info->ai_socktype, info->ai_protocol);
if (server < 0)
{
ERR("could not get a socket!");
return -1;
}
if (bind(server, info->ai_addr, info->ai_addrlen) < 0)
{
ERR("could not bind to socket!");
return -1;
}
if (listen(server, 5) < 0)
{
ERR("problem in listening!");
return -1;
}
addr_size = sizeof(client_addr);
client = accept(server, (struct sockaddr *) &client_addr, &addr_size);
if (client < 0)
{
ERR("could not accept client socket!");
return -1;
}
do
{
recv(client, (void *) &n, sizeof(uint32_t), 0);
printf("Received %d from the client\n", n);
fib_n = fib(n);
send(client, (void *) &fib_n, sizeof(uint32_t), 0);
printf("Sent fib(%d) = %d to the client\n", n, fib_n);
} while(n > 0);
close(client);
close(server);
return 0;
}