#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <signal.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/file.h>
#include <sys/wait.h>
#include <errno.h>
#include <ctype.h>

void main(int argc, char *argv[])
{ if (argc!=3)
  { fprintf(stderr, "usage: %s remote-host port-number\n", argv[0]);
    exit(1); }
  char remote_name[1000];
  strcpy(remote_name, argv[1]);
  int port_number;
  int n=sscanf(argv[2], "%d", &port_number);
  if (n!=1)
  { fprintf(stderr, "\"%s\" is not a valid port number\n", argv[2]);
    exit(1); }

  struct hostent * remote_info=gethostbyname(remote_name);
  if (remote_info==NULL)
  { fprintf(stderr, "(1) host \"%s\" not known\n", remote_name); 
    exit(1); }
  struct in_addr * remote_addr=(struct in_addr *)remote_info->h_addr;
  if (remote_addr->s_addr==NULL)
  { fprintf(stderr,"(2) host %s not known\n", inet_ntoa(*remote_addr)); 
    exit(1); }

  struct sockaddr_in dest_info;
  bzero(&dest_info, sizeof(dest_info));
  dest_info.sin_family=AF_INET;
  dest_info.sin_addr.s_addr=remote_addr->s_addr;
  dest_info.sin_port=htons(port_number);

  int sock=socket(AF_INET, SOCK_DGRAM, 0);
  if (sock<0)
  { perror("socket failure");
    exit(1); }

  printf("\n[destination is %s (%s) on port %d]\n",
          remote_name, inet_ntoa(*remote_addr), port_number);

  while (1)
  { sleep(2);
    unsigned char buff[10240];
    strcpy((char *)buff, "Start:");
    for (int i=0; i<100; i+=1)
      strcat((char *)buff, "0123456789");
    strcat((char *)buff, ":enD");
    int bufflen=strlen((char *)buff);
    int num=sendto(sock, buff, bufflen, 0, (struct sockaddr *)&dest_info, sizeof(dest_info));
    if (num<=0)
    { printf("[num=%d]\n", num);
      perror("sendto");
      sleep(1);
      continue; }
    printf("transmitted (%d)\n", num);
    sleep(5); }

  close(sock); }