#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

#define LOCAL_SERVER_PORT 8024
#define MAX_MSG 512

int main(int argc, char *argv[]) {
  FILE *statf;
  int sd, rc, n, cliLen;
  struct sockaddr_in cliAddr, servAddr;
  char msg[MAX_MSG];
  unsigned char tempstr[8];
  long port_to_use;

  switch(argc) {
    case 0x02:
    sscanf(argv[1], "%s", &tempstr);
    port_to_use=atol(tempstr);
    break;
    default:
    port_to_use=LOCAL_SERVER_PORT;
    break;
  }

  sd=socket(AF_INET, SOCK_DGRAM, 0);
  if(sd<0) {
    printf("%s: cannot open socket \n",argv[0]);
    exit(1);
  }

  servAddr.sin_family = AF_INET;
  servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servAddr.sin_port = htons(port_to_use);
  rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
  if(rc<0) {
    printf("%s: cannot bind port number %d \n", argv[0], port_to_use);
    exit(1);
  }

  printf("gboxtrace: waiting for trace data on port UDP %u\n", port_to_use);

  statf = fopen("./debug.txt", "w");

  while(1) {
    memset(msg,0x0,MAX_MSG);
    cliLen = sizeof(cliAddr);
    n = recvfrom(sd, msg, MAX_MSG, 0,(struct sockaddr *) &cliAddr, &cliLen);
    printf("%s",msg);
    fprintf(statf,"%s",msg);
  }

fclose(statf);
return 0;

}
