/*
 *  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 <signal.h>


#define UDP_BW_PORT     (16902)
#define PKT_SIZE        (100)
#define PKT_CNT         (10000000)
static char buffer[PKT_SIZE];


int
main(int argc, char *argv[])
{
    int sockfd, i, interval, seq;
    struct sockaddr_in their_addr;

    if (argc != 3) {
        printf("argc should be 3\n");
        exit(1);
    }

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

    printf("start to send data\n");
    memset(buffer, 0, sizeof(buffer));
    interval = atoi(argv[2]);
    for (i = 0; i < PKT_CNT; i++) {
        seq = htonl(i);
        memcpy(buffer, (char *) &seq, 4);

        if (sendto(sockfd, buffer, PKT_SIZE, 0,
                (struct sockaddr *) &their_addr, sizeof(their_addr)) != PKT_SIZE) {
            perror("sendto");
            exit(1);
        }

        if ((i != 0) && ((i % 2500) == 0)) {
            printf("Sent 2,500 packets\n");
        }

        if (interval > 0) {
            if ((i != 0) && ((i % 10) == 0)) {
                /* sleep for the specified number of microseconds */
                usleep(interval * 10);
            }
        }
    }

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

    close(sockfd);

    return 0;
}
