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

extern struct in6_addr in6addr_any;

struct sockaddr_in6 sin6;

main(argc, argv)
	int             argc;
	char          **argv;
{
	unsigned int	hops = 0;
	int             s, cc, ch;
	char            buf[1024];
	struct in6_addr addr6;
	u_int		ifi = 0;
	extern char	*optarg;
	extern int	optind;

	addr6 = in6addr_any;
	if ((s = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		perror("socket");
		exit(1);
	}
	while ((ch = getopt(argc, argv, "h:t:i:")) != -1)
		switch(ch) {
		    case 'h':
		    case 't':
			hops = atoi(optarg);
			break;
		    case 'i':
			if (sscanf(optarg, "%u\0", &ifi) != 1) {
				ifi = if_nametoindex(optarg);
				if (ifi == 0)
					fprintf(stderr,
						"unknown %s interface name\n",
						optarg);
			}
			break;
		}
	argc -= optind;
	argv += optind;
	if (argc != 1) {
		fprintf(stderr, "groupe manque\n");
		exit(-1);
	}
	if (hops > 0)
		if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
			       &hops, sizeof(hops)) < 0) {
			perror("setsockopt IPV6_MULTICAST_HOPS");
			return (0);
		}
	if (ifi)
		if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_IF,
			       &ifi, sizeof(u_int)) < 0) {
			perror("setsockopt IPV6_MULTICAST_IF");
			return (0);
		}

	(void) inet_pton(AF_INET6, *argv, &addr6);

#ifdef SIN6_LEN
	sin6.sin6_len = sizeof(sin6);
#endif
	sin6.sin6_family = AF_INET6;
	sin6.sin6_addr = addr6;
	sin6.sin6_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 *)&sin6, sizeof(sin6)) < 0)
				perror("sendto");
			fprintf(stderr, "-%d->\n", cc);
		} else {
			fprintf(stderr, ".\n", cc);
			return (0);
		}
	}
}
