/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include <windows.h>
#include <errno.h>

void client(char *host, int port, char* msg)
{
    int sd, status, len, ix;
    short tmp;
    char resp[512];
    struct sockaddr local,remote;
    struct hostent *hostinfo;
    sd = socket(AF_INET, SOCK_STREAM, 0);
    if(sd < 0)
    {
        printf("Error creating socket: %s\n", strerror(errno));
        goto fin;
    }
    local.sa_family = AF_INET;
    memset(local.sa_data, 0, sizeof(local.sa_data));
    status = bind(sd, &local, sizeof(local));
    if(status < 0)
    {
        printf("Error binding socket: %s\n", strerror(errno));
        goto fin;
    }
    hostinfo = gethostbyname(host);
    if(!hostinfo)
    {
        printf("Error looking up host: %s\n", host);
        goto fin;
    }
    remote.sa_family = hostinfo->h_addrtype;
    memcpy(remote.sa_data + 2, hostinfo->h_addr_list[0], hostinfo->h_length);
    *((short *)remote.sa_data) = htons(port);
    status = connect(sd, &remote, sizeof(remote));
    if(status != 0)
    {
        printf("Error connecting to host: %s port: %d\n", host, port);
        goto fin;
    }
    tmp = strlen(msg);
    status = send(sd, (char *)&tmp, sizeof(tmp), 0);
    if(status < 0)
    {
        printf("Error sending request\n");
        goto fin;
    }
    status = send(sd, msg, strlen(msg), 0);
    if(status < 0)
    {
        printf("Error sending request\n");
        goto fin;
    }
    ix = 0;
    while ((len = recv(sd, resp + ix, sizeof(resp) - ix - 1, 0)) > 0)
    {
        ix = ix + len;
    }
    resp[ix] = '\0';
    printf("response = %s\n", resp);
fin:
    closesocket(sd);
}

int main(int argc,char *argv[])
{
    WSADATA WSAData;
    WSAStartup(0x0101, &WSAData);
    client("localhost", 1234, "Dette er en test!");
    WSACleanup();
    return 0;
}
