/* Receive packets on an UDP port and prints the inter-arrival times...	  */
/* Useful for testing the sender program 				  */
/* This program DOES NOT require the RK (can be run on a plain linux box) */
/*			Luca Abeni (luca@sssup.it)			  */

#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/time.h>

long loops=0;
int port;
char name[80];
long unsigned int recvtime[10000];

int main(int argc,char **argv)
{
  int                     sockfd;
  struct sockaddr_in      serv_addr, cli_addr;
  fd_set fdvar;
  struct timeval tv,d1,d2,finishing;
  struct timeval *starting, *ip_end;
  int i=0;
  char buf[2000];
  int numfds;
  int done;
  FILE *f;

  /*
   * Open a UDP socket (an Internet datagram socket).
   */
  if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    perror("server: can't open datagram socket");
  
  if (argc < 2) port = 2030; 
  else port = atoi(argv[1]);
  strcpy(name,argv[0]);
  
  /*
   * Bind our local address so that the client can send to us.
   */
  
  bzero((char *) &serv_addr, sizeof(serv_addr));
  serv_addr.sin_family      = AF_INET;
  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  serv_addr.sin_port        = htons(port);

  if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
    perror("server: can't bind local address");

  done = 0;
  while (!done) {
    recv(sockfd,buf,1000,0);
    if (gettimeofday(&finishing,NULL) < 0) {
	    perror("GetTimeOfDay failed:");
	    exit(-1);
    }
    if (loops < 50) {
	    recvtime[loops] = finishing.tv_sec * 1000000 + finishing.tv_usec;
    } else {
	    done = 1;
    }
    printf("receiving %d at %lu\n", loops, recvtime[loops]);
    loops++;
  }

  f = fopen("res.txt", "w");
  for (i = 0; i < 100; i++) {
	  unsigned long int diff;

	  if (i > 0) {
		  diff = recvtime[i] - recvtime[i - 1];
	  } else {
		  diff = 0;
	  }
	  fprintf(f, "%d %lu\t%lu\n", i, recvtime[i], diff);
  }
  fclose(f);
 return loops;
}
