/*
 *  This file implements the client side of the packet loss test. The
 *  test measures packet loss by sending a UDP packet with a 100-byte
 *  payload to the server. Each packet includes a sequence number,
 *  which allows the server to compute the packet loss rate and
 *  distribution. The purpose of this test is to simulate real-life
 *  packet loss situations for VoIP traffic
 */


#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_PKTLOSS_PORT    (16901)
#define PKT_SIZE            (100)
#define PKT_CNT             (10000)
static char buffer[PKT_SIZE];


static void
initBuffer(char *buf, int seq, int len)
{
    int pos;

    seq = htonl(seq);
    memcpy(buf, (char *) &seq, 4);

    for (pos = 4; pos < len; pos++) {
        buf[pos] = (char) pos;
    }
}


int
main(int argc, char *argv[])
{
    int sockfd, i, interval;
    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_PKTLOSS_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");
    for (i = 0; i < PKT_CNT; i++) {
        initBuffer(buffer, i, PKT_SIZE);

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

        /* sleep for the specified number of milliseconds */
        interval = atoi(argv[2]);
        usleep(interval * 1000);
    }

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

    close(sockfd);

    return 0;
}
