#include <sys/types.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 <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

extern struct in6_addr in6addr_any;

struct sockaddr_in6 sin6;
int s;

#define  IPPORT 54321

Error(c, s)
	char           *c;
	int             s;
{
	perror(c);
	close(s);
	exit(1);
}

void BrokenPipe(Signal, Code, SignalContextPtr)
	int             Signal, Code;
	struct sigcontext *SignalContextPtr;
{
	signal(SIGPIPE, BrokenPipe);
	return;
}

main(argc, argv)
	int             argc;
	char           *argv[];
{
	struct ipv6_mreq mreq;
	int             cc, ccb, ch;
	char            buf[10240];
	int             len;
	int             one = 1;
	u_int		ifi = 0;
	extern char	*optarg;
	extern int	optind;

	signal(SIGPIPE, BrokenPipe);
	while ((ch = getopt(argc, argv, "i:")) != -1)
		switch(ch) {
		    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 ((s = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		perror("socket");
		exit(1);
	}
	(void) setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));

#ifdef SIN6_LEN
	sin6.sin6_len = sizeof(sin6);
#endif
	sin6.sin6_family = AF_INET6;
	sin6.sin6_port = htons(IPPORT);
	if (bind(s, (struct sockaddr *)&sin6, sizeof(sin6)) < 0) {
		perror("bind");
		exit(1);
	}
	(void) inet_pton(AF_INET6, *argv, &mreq.ipv6mr_multiaddr);
	mreq.ipv6mr_interface = ifi;
	if (setsockopt(s, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,
		       &mreq, sizeof(mreq)) < 0) {
		perror("setsockopt IPV6_ADD_MEMBERSHIP");
		return (0);
	}
	for (;;) {
		cc = read(s, buf, 10240);
		if (cc < 0) {
			perror("read socket");
			return (cc);
		} else if (cc > 0) {
			ccb = write(1, buf, cc);
			if (ccb != cc)
				perror("write file");
			fprintf(stderr, "<-%d-\n", cc);
		} else {
			fprintf(stderr, "..\n");
			return (0);
		}
	}
}
