/* LICENSE:
  =========================================================================
    CMPack'04 Source Code Release for OPEN-R SDK 1.1.5-r2 for ERS7
    Copyright (C) 2004 Multirobot Lab [Project Head: Manuela Veloso]
    School of Computer Science, Carnegie Mellon University
    All rights reserved.
  ========================================================================= */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>

int main(int argc, char **argv) {

  if(argc!=3) {
    printf("Usage: test_sender host port\n");
    return 0;
  }

  sockaddr_in dest_addr;
  hostent *he;

  he = gethostbyname(argv[1]);
  if(he==NULL) {
    printf("Could not resolve host %s\n");
    argv[1];
  }

  int send_port = atoi(argv[2]);
  if(send_port < 1 || send_port > 65000) {
    printf("Expecting port between 1 and 65K\n");
    return -1;
  } else {
    printf("I will try  to create UDP sender to port %d on %s\n",
	   send_port, argv[1]);
  }
  
  // Let's create a socket to listen for datagrams
  int socket_fd;

  socket_fd = socket(PF_INET, SOCK_DGRAM, 0);
  if(socket_fd < 0) {
    printf("Unable to create a socket. Weird.\n");
    return -1;
  }

  dest_addr.sin_family = AF_INET;
  dest_addr.sin_addr = *(in_addr*)(he->h_addr);
  dest_addr.sin_port = htons(send_port);

  while(true) {
    char buf[] = "This is some test data.                                                                                                                                                       ";
    int size;
    
    int addr_size = sizeof(dest_addr);
    size = sendto(socket_fd, buf, strlen(buf), 0,
		  (sockaddr*)&dest_addr, addr_size);

    if(size > 0) {
      printf("Sent %d bytes to: %s\n", size, 
	     inet_ntoa(dest_addr.sin_addr));
    }

    ulong send_time = time(NULL);
    while(time(NULL)<send_time+1)
      ;
  }

 return 0;
}
