/*
 * recvdata.c
 * Daten ueber einen socket empfangen und auf stdout ausgeben
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netdb.h>
#include "defs.h"
void
Usage(char *name)
{
        fprintf(stderr, "Aufruf: %s [-t] adresse port\n", name);
        fprintf(stderr, "\t -t: TCP verwenden\n");
        exit(1);
}
        
int
main(int argc, char **argv)
{
        int sock, err, bytesRead, ch, i, debug=0;
        char buf[PACKETSIZE];
        char *hostName, *portName;
        struct addrinfo hints, *address;
        int socketType = SOCK_DGRAM;
        while((ch = getopt(argc, argv, "dt")) != EOF) {
                switch(ch) {
                case 't':       socketType = SOCK_STREAM;
                                break;
                case 'd':       debug = 1;
                                break;
                default:        Usage(argv[0]);
                }
        }
        if(argc - optind != 2)
                Usage(argv[0]);
        hostName = argv[optind++];
        portName = argv[optind++];
        memset(&hints, 0, sizeof(struct addrinfo));
        hints.ai_socktype = socketType;
        hints.ai_flags = (AI_CANONNAME | AI_PASSIVE);
        err = getaddrinfo(hostName, portName, &hints, &address);
        if(err != 0) {
                fprintf(stderr, "getaddrinfo(): %d\n", err);
                exit(1);
        }
        sock = socket(address->ai_family, address->ai_socktype,
                address->ai_protocol);
        if(sock < 0 ) {
                perror("socket()");
                exit(1);
        }
        if(bind(sock, address->ai_addr, address->ai_addrlen) < 0) {
                perror("bind()");
                exit(1);
        }
        if(socketType == SOCK_STREAM) {
                struct sockaddr cliAddr;
                int newSock, cliAddrLen = sizeof(cliAddr);
                if(listen(sock, 5) == -1) {
                        perror("listen()");
                        exit(1);
                }
                newSock = accept(sock, &cliAddr, &cliAddrLen);
                if(newSock == -1) {
                        perror("accept()");
                        exit(1);
                }
                sock = newSock;
        }
        i = 0;
        while((bytesRead = read(sock, buf, sizeof(buf))) > 0) {
                fwrite(buf, bytesRead, 1, stdout);
                if(debug) {
                        if(++i % 10 == 0) {
                                fputc('.', stderr);
                                fflush(stderr);
                        }
                }
        }
        if(bytesRead < 0) {
                perror("read()");
                exit(1);
        }
        return 0;
}