/*
 *  This file implements the server side of the bandwidth test. The
 *  test measures the amount of time it takes to receive a certain
 *  amount of data when 100-byte packets are pumped from the client
 *  to the server at full speed
 */


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <signal.h>


#define UDP_BW_PORT     (16902)
#define PKT_SIZE        (100)
#define PKT_CNT         (10000)
static char buffer[PKT_SIZE];
static int goodCnt = 0;
static struct timeval startT, endT;
static int seq = 0;


static void
reportResult(void)
{
    long elapsed;
    long long bw;

    elapsed = ((endT.tv_sec - startT.tv_sec) * 1000000) + (endT.tv_usec - startT.tv_usec);
    bw = PKT_SIZE * PKT_CNT * 8;
    bw = (bw * 1000000) / elapsed;

    printf("Received %d bytes\n", PKT_SIZE * PKT_CNT);
    printf("Elapsed time %ld micro-seconds\n", elapsed);
    printf("Effective bandwidth is %ld b/s\n", bw);
    printf("Last sequence number %d\n", seq);
    printf("Packet lost rate %d percents\n", ((seq - PKT_CNT) * 100) / PKT_CNT
);
}


int
main(int argc, char *argv[])
{
    int sockfd, addr_len, i;
    struct sockaddr_in my_addr;
    struct timezone tz;

    if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }
    
    my_addr.sin_family = AF_INET;         // host byte order
    my_addr.sin_port = htons(UDP_BW_PORT);     // short, network byte order
    my_addr.sin_addr.s_addr = INADDR_ANY;
    memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct

    if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
        perror("bind");
        exit(1);
    }

    printf("start to receive data\n");
    startT.tv_sec = 0;
    startT.tv_usec = 0;
    for (i = 0; i < PKT_CNT; i++) {
        if (recvfrom(sockfd, buffer, PKT_SIZE, 0,
                (struct sockaddr *) &my_addr, &addr_len) != PKT_SIZE) {
            perror("recvfrom");
            exit(1);
        }

        if ((startT.tv_sec == 0) && (startT.tv_usec == 0)) {
            if (gettimeofday(&startT, &tz) < 0) {
                perror("gettimeofday");
                exit(1);
            }
        }
    }
    if (gettimeofday(&endT, &tz) < 0) {
        perror("gettimeofday");
        exit(1);
    }
    seq = ntohl(*((int *) &buffer[0]));

    reportResult();

done:
    printf("finish test\n\n");

    close(sockfd);

    return 0;
}
