/* 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>

#include <sys/socket.h>
#include <netdb.h>
#include <unixio.h>
#include <errno.h>

#define HOST "localhost"
#define PORT "12345"

/* not super efficient to receive 1 char at a time, but it avoids a buffer */
int recv_line(int sd, char *buf, int buflen)
{
    int ix, len;
    ix = 0;
    buf[ix] = '\0';
    while(ix < buflen && strstr(buf, "\n") == NULL)
    {
        len = recv(sd, buf + ix, 1, 0);
        if(len == 0) return 0;
        ix = ix + len;
        buf[ix] = 0;
    }
    ix--;
    while(ix >= 0 && (buf[ix] == '\n' || buf[ix] == '\r'))
    {
        buf[ix] = 0;
        ix--;
    }
    return 1;
}

int main()
{
    int sd, stat;
    char *outmsg, inmsg[100];
    struct addrinfo hints, *res;
    /* lookup host */
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = 0;
    stat = getaddrinfo(HOST, PORT, &hints, &res);
    if(stat != 0)  printf("getaddrinfo stat=%d\n", stat);
    /* create socket */
    sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if(sd < 0) printf("socket stat=%d (%s)\n", errno, strerror(errno));
    /* connect to host */
    stat = connect(sd, res->ai_addr, res->ai_addrlen);
    if(stat != 0) printf("connect stat=%d (%s)\n", errno, strerror(errno));
    /* send message */
    outmsg = "Hi from C!\r\n";
    stat = send(sd, outmsg, strlen(outmsg), 0);
    if(stat < 0) printf("send stat=%d (%s)\n", errno, strerror(errno));
    /* receive all messages */
    while(recv_line(sd, inmsg, sizeof(inmsg)))
    {
        printf("|%s|\n", inmsg);
    }
    /* close socket */
    close(sd);
    return 0;
}
