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

#include <errno.h>

#define SERVER "localhost"
#define SERVER_PORT "12345"
#define CLIENT_PORT "12346"
#define SIZE 7
#define MAX_SIZE 1000

int main()
{
    int sd, status, i, j, len, fromlen;
    char *buf1, *buf2;
    struct addrinfo hints, *local, *remote;
    struct sockaddr from;
#ifdef WIN32
    WSADATA WSAData;
    WSAStartup(0x0101, &WSAData);
#endif
    /* lookup client */
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_protocol = IPPROTO_UDP;
    hints.ai_flags = 0;
    status = getaddrinfo("localhost", CLIENT_PORT, &hints, &local);
    if(status != 0)
    {
        printf("Error looking up self\n");
        exit(0);
    }
    /* lookup server */
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_protocol = IPPROTO_UDP;
    hints.ai_flags = 0;
    status = getaddrinfo(SERVER, SERVER_PORT, &hints, &remote);
    if(status != 0)
    {
        printf("Error looking up server: %s\n", SERVER);
        exit(0);
    }
    /* create socket */
    sd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sd < 0)
    {
        printf("Error creating socket: %s\n", strerror(errno));
        exit(0);
    }
    /* bind socket */
    status = bind(sd, local->ai_addr, local->ai_addrlen);
    if(status < 0)
    {
        printf("Error binding socket: %s\n", strerror(errno));
        exit(0);
    }
    for(i = 0; i < 3; i++)
    {
        /* setup data */
        buf1 = malloc(SIZE);
        for(j = 0; j < SIZE; j++) buf1[j] = (i + j);
        /* send packet */
        len = sendto(sd, buf1, SIZE, 0, remote->ai_addr, remote->ai_addrlen);
        if(len < 0)
        {
            printf("Error sending: %s\n", strerror(errno));
            exit(0);
        }
        /* receive packet */
        buf2 = malloc(MAX_SIZE);
        fromlen = sizeof(from);
        len = recvfrom(sd, buf2, MAX_SIZE, 0, &from, &fromlen);
        if(len < 0)
        {
            printf("Error receiving: %s\n", strerror(errno));
            exit(0);
        }
        /* print data */
        for(j = 0; j < len; j++) printf(" %d", (int)buf2[j]);
        printf("\n");
        /* */
        free(buf1);
        free(buf2);
    }
    /* close socket */
#ifdef WIN32
    closesocket(sd);
    WSACleanup();
#else
    close(sd);
#endif
    return 0;
}
