#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

struct sockaddr_in msin;

main(argc, argv)
	int             argc;
	char          **argv;
{
	unsigned char   ttl;
	int             s, cc, ch;
	char            buf[1024];
	u_long          addr;
	extern char	*optarg;
	extern int	optind;

	ttl = 0;
	addr = htonl(INADDR_ANY);
	if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		perror("socket");
		exit(1);
	}
	while ((ch = getopt(argc, argv, "t:i:")) != -1)
		switch(ch) {
		    case 't':
			ttl = atoi(optarg);
			break;
		    case 'i':
			addr = inet_addr(optarg);
			break;
		}
	argc -= optind;
	argv += optind;
	if (argc != 1) {
		fprintf(stderr, "groupe manque\n");
		exit(-1);
	}
	if (ttl > 0)
		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
			       &ttl, sizeof(ttl)) < 0) {
			perror("setsockopt IP_MULTICAST_TTL");
			return (0);
		}
	if (addr != htonl(INADDR_ANY))
		if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
			       &addr, sizeof(addr)) < 0) {
			perror("setsockopt IP_MULTICAST_IF");
			return(0);
		}

	addr = inet_addr(*argv);

	msin.sin_family = AF_INET;
	msin.sin_addr.s_addr = addr;
	msin.sin_port = htons(54321);

	for (;;) {
		cc = read(0, buf, 1024);
		if (cc < 0) {
			perror("read file");
			return (cc);
		} else if (cc > 0) {
			if (sendto(s, buf, cc, 0,
				   (struct sockaddr *)&msin, sizeof(msin)) < 0)
				perror("sendto");
			fprintf(stderr, "-%d->\n", cc);
		} else {
			fprintf(stderr, ".\n", cc);
			return (0);
		}
	}
}
