/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef WIN32
#define FD_SETSIZE 1024
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/socket.h>
#include <netdb.h>
#endif

#include <errno.h>

#define PORT "12345"
#define BACKLOG 100

struct handler2;
typedef void (*handler)(int sd2, fd_set *sel, struct handler2 *h);
struct handler2
{
    handler fptr;
};

void accept_handler(int sd, fd_set *sel, struct handler2 *h);
void integer_handler(int sd2, fd_set *sel, struct handler2 *h);
void string_handler(int sd2, fd_set *sel, struct handler2 *h);

void accept_handler(int sd, fd_set *sel, struct handler2 *h)
{
    int sd2, slen;
    struct sockaddr remote;
    char addr[INET6_ADDRSTRLEN];
    /* accept */
    sd2 = accept(sd, 0, 0);
    if(sd2 < 0)
    {
        printf("Error accepting socket: %s\n", strerror(errno));
        exit(0);
    }
    slen = sizeof(remote);
    getpeername(sd2, &remote, &slen);
    if(remote.sa_family == AF_INET)
        printf("(connection from %s)\n", inet_ntop(AF_INET, &((struct sockaddr_in *)&remote)->sin_addr, addr, sizeof(addr)));
    if(remote.sa_family == AF_INET6)
        printf("(connection from %s)\n", inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&remote)->sin6_addr, addr, sizeof(addr)));
    /* next handler */
    FD_SET(sd2, sel);
    h[sd2].fptr = integer_handler;
}

void integer_handler(int sd2, fd_set *sel, struct handler2 *h)
{
    int status, ix, buflen;
    long int a, b, c, tmp;
    /* read a and b */
    buflen = sizeof(tmp);
    ix = 0;
    while(ix < buflen)
    {
        ix = ix + recv(sd2, (char *)&tmp + ix, buflen - ix, 0);
    }
    a = ntohl(tmp);
    buflen = sizeof(tmp);
    ix = 0;
    while(ix < buflen)
    {
        ix = ix + recv(sd2, (char *)&tmp + ix, buflen - ix, 0);
    }
    b = ntohl(tmp);
    /* calculate c and send */
    c = a + b;
    tmp = htonl(c);
    status = send(sd2, (char *)&tmp, sizeof(tmp), 0);
    if(status < 0)
    {
        printf("Error sending c: %s\n", strerror(errno));
        exit(0);
    }
    /* next handler */
    h[sd2].fptr = string_handler;
}

void string_handler(int sd2, fd_set *sel, struct handler2 *h)
{
    int status, ix, buflen;
    char *buf, *v, *v2, len;
    /* read v */
    recv(sd2, &len, sizeof(len), 0);
    buflen = len;
    buf = malloc(buflen);
    ix = 0;
    while(ix < buflen)
    {
        ix = ix + recv(sd2, buf + ix, buflen - ix, 0);
    }
    v = malloc(buflen + 1);
    memcpy(v, buf, buflen);
    v[buflen] = '\0';
    free(buf);
    /* calculate v2 and send */
    v2 = malloc(2 * strlen(v) + 1);
    strcpy(v2, v);
    strcat(v2, v);
    len = strlen(v2);
    status = send(sd2, &len, sizeof(len), 0);
    if(status < 0)
    {
        printf("Error sending v2: %s\n", strerror(errno));
        exit(0);
    }
    status = send(sd2, v2, len, 0);
    if(status < 0)
    {
        printf("Error sending v2: %s\n", strerror(errno));
        exit(0);
    }
    free(v);
    free(v2);
    /* close socket */
#ifdef WIN32
    closesocket(sd2);
#else
    close(sd2);
#endif
    /* next handler */
    FD_CLR(sd2, sel);
    h[sd2].fptr = NULL;
}

int main()
{
    int sd, status, i;
    struct addrinfo hints, *res;
    fd_set sel, sav;
    struct timeval tv;
    struct handler2 h[FD_SETSIZE];
#ifdef WIN32
    WSADATA WSAData;
    if(WSAStartup(0x0101, &WSAData) != 0)
    {
        printf("Error initializing\n");
        exit(0);
    }
#endif
    tv.tv_sec = 1;
    tv.tv_usec = 0;
    /* find port */
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET; //AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE; 
    status = getaddrinfo(NULL, PORT, &hints, &res);
    if(status != 0)
    {
        printf("Error finding port: %s\n", PORT);
        exit(0);
    }
    /* create socket */
    sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if(sd < 0)
    {
        printf("Error creating socket: %s\n", strerror(errno));
        exit(0);
    }
    /* bind */
    status = bind(sd, res->ai_addr, res->ai_addrlen);
    if(status < 0)
    {
        printf("Error binding socket: %s\n", strerror(errno));
        exit(0);
    }
    freeaddrinfo(res);
    /* listen */
    status = listen(sd, BACKLOG);
    if(status < 0)
    {
        printf("Error listening socket: %s\n", strerror(errno));
        exit(0);
    }
    FD_ZERO(&sel);
    FD_SET(sd, &sel);
    h[sd].fptr = accept_handler;
    for(;;)
    {
        /* select */
        sav = sel;
        status = select(FD_SETSIZE, &sel, NULL, NULL, &tv);
        if(status < 0)
        {
            printf("Error selecting: %s\n", strerror(errno));
            exit(0);
        }
        for(i = 0; i <= FD_SETSIZE; i++)
        {
            if(FD_ISSET(i, &sel)) 
            {
                h[i].fptr(i, &sav, h);
            }
        }
        sel = sav;
    }
    return 0;
}
