/* 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_PORT "12345"
#define MAX_SIZE 1000

int main()
{
    int sd, status, i, len, fromlen;
    char *buf1, *buf2;
    struct addrinfo hints, *local;
    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", SERVER_PORT, &hints, &local);
    if(status != 0)
    {
        printf("Error looking up self\n");
        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(;;)
    {
        /* receive packet */
        buf1 = malloc(MAX_SIZE);
        fromlen = sizeof(from);
        len = recvfrom(sd, buf1, MAX_SIZE, 0, &from, &fromlen);
        if(len < 0)
        {
            printf("Error receiving: %s\n", strerror(errno));
            exit(0);
        }
        /* work on data */
        buf2 = malloc(len);
        for(i = 0; i < len; i++)
        {
            buf2[i] = buf1[i] + 1;
        }
        /* send packet */
        len = sendto(sd, buf2, len, 0, &from, fromlen);
        if(len < 0)
        {
            printf("Error sending: %s\n", strerror(errno));
            exit(0);
        }
        /* */
        free(buf1);
        free(buf2);
    }
    /* close socket */
#ifdef WIN32
    closesocket(sd);
    WSACleanup();
#else
    close(sd);
#endif
    return 0;
}
