/* 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
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netdb.h>
#endif

#include <errno.h>

#define HOST "localhost"
#define PORT 12345

void recv_line(int sd, char *buf, int buflen)
{
    int ix;
    ix = 0;
    buf[ix] = '\0';
    while(ix < buflen && strstr(buf, "\r\n") == NULL)
    {
        ix = ix + recv(sd, buf + ix, buflen - ix, 0);
        buf[ix] = '\0';
    }
}

int main()
{
    int sd, status, buflen;
    long int a, b, c;
    char *buf, *v, *v2;
    struct sockaddr_in remote;
    struct hostent *hostinfo;
#ifdef WIN32
    WSADATA WSAData;
    WSAStartup(0x0101, &WSAData);
#endif
    /* lookup host */
    hostinfo = gethostbyname(HOST);
    if(!hostinfo)
    {
        printf("Error looking up host %s: %s\n", HOST, strerror(errno));
        exit(0);
    }
    /* create socket */
    sd = socket(AF_INET, SOCK_STREAM, 0);
    if(sd < 0)
    {
        printf("Error creating socket: %s\n", strerror(errno));
        exit(0);
    }
    /* connect to host */
    remote.sin_family = hostinfo->h_addrtype;
    memcpy(&remote.sin_addr, hostinfo->h_addr_list[0], hostinfo->h_length);
    remote.sin_port = htons(PORT);
    status = connect(sd, (struct sockaddr *)&remote, sizeof(remote));
    if(status != 0)
    {
        printf("Error connecting to host %s port %d: %s\n", HOST, PORT, strerror(errno));
        exit(0);
    }
    /* send a and b */
    a = 123;
    b = 456;
    buflen = 24;
    buf = malloc(buflen);
    sprintf(buf, "%ld %ld\r\n", a, b);
    status = send(sd, buf, strlen(buf), 0);
    if(status < 0)
    {
        printf("Error sending a and b: %s\n", strerror(errno));
        exit(0);
    }
    free(buf);
    /* receive c and print */
    buflen = 13;
    buf = malloc(buflen);
    recv_line(sd, buf, buflen);
    sscanf(buf, "%ld\r\n", &c);
    printf("%ld\n", c);
    free(buf);
    /* send v */
    v = "ABC";
    buflen = strlen(v) + 3;
    buf = malloc(buflen);
    sprintf(buf, "%s\r\n", v);
    status = send(sd, buf, buflen, 0);
    if(status < 0)
    {
        printf("Error sending v: %s\n", strerror(errno));
        exit(0);
    }
    free(buf);
    /* receive v2 and print */
    buflen = 258;
    buf = malloc(buflen);
    recv_line(sd, buf, buflen);
    v2 = malloc(strlen(buf) + 1);
    sscanf(buf, "%s\r\n", v2);
    printf("%s\n", v2);
    free(buf);
    free(v2);
    /* close socket */
#ifdef WIN32
    closesocket(sd);
    WSACleanup();
#else
    close(sd);
#endif
    return 0;
}
