/* udp_i.c -- inject packets into the network for test */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#include <stdio.h>
#include <string.h>

#define BUFSIZE 1024
#define UDP_PORT 10094

int on = 1;
int off = 0;

main(argc, argv)
	int argc;
	char *argv[];
{
	int sock, portno;
	char buf[BUFSIZE], *buftext;
	struct sockaddr_in to;
	struct hostent *hp, *gethostbyname();
	int gethostname();
	char myhost[65], *the_host;

	/* Set defaults */
	gethostname(myhost,65);
	the_host = myhost;
	portno = UDP_PORT;

	/* Test arguments */
	if(argc>2){
		fprintf(stderr,"Usage: %s [<hostname> [<portnumber>]]\n",argv[0]);
		exit(1);
	}
	if(argc>1)the_host = argv[1];
	if(argc>2)portno = atoi(argv[2]);

	/* Find the host number */
	hp = gethostbyname(the_host);
	if (hp == 0){
		fprintf(stderr,"%s: unknown host\n",argv[1]);
		exit(2);
	}

	/* Create socket */
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock<0) {
		perror("opening raw socket");
		exit(1);
	}

/*	if(setsockopt(sock, SOL_SOCKET, SO_DONTROUTE, &on, sizeof on)<0){
		perror("setting socket options");
		exit(1);
	}
*/
	bzero((char *)&to, sizeof to);
	bcopy(hp->h_addr_list[0], (char *)&to.sin_addr, hp->h_length);
	to.sin_family = AF_INET;
	to.sin_port = htons(portno);

	/* give the user a prompt */
	putchar('>');
	fflush(stdout);

	/* fill in as much of the header as we care about for now */
	buf[12] = 44;
	buf[13] = 72;
	buf[14] = 6;
	buf[15] = 134;
	buf[16] = 44;
	buf[17] = 72;
	buf[18] = 6;
	buf[19] = 131;

	buftext = buf + 40;

	/* Loop until we hit EOF */
	while(fgets(buftext,BUFSIZE-40,stdin) != NULL){
		if (sendto(sock, buf, (strlen(buftext)+40), 0, (struct sockaddr *)&to, sizeof to) < 0) {
			perror("writing of udp socket");
			close(sock);
			exit(4);
		}
		putchar('>');
		fflush(stdout);
	}

	/* all done, close the socket and exit */
	close(sock);
	exit(0);
}
